日期:2014-05-18  浏览次数:20705 次

新手问题:关于使用Servlet获取非页面信息并操作的方法?
刚开始学习servlet,想通过servlet去获取另一个Java类中的信息或文件系统中的信息,而不是获取页面的信息。然后把获取的信息传给另一个Java类去操作,最后返回第一个Java类或本地文件系统中。

请问高手应该如何编写,最好能有一小段代码学习学习,非常感谢。

------解决方案--------------------
java客户端

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

/**
* @author Yangjs 2007-3-29
*/
public class MessageSender {

// 重写X509TrustManager类的三个方法,信任服务器证书
private static X509TrustManager xTrustManager = new X509TrustManager() {

public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {

return null;
}
};

// 信任主机名
private static HostnameVerifier hostNameVerifier = new HostnameVerifier() {

public boolean verify(String hostname, SSLSession session) {

return true;
}
};

/**
* 信任主机,无论主机名和证书为多少都信任主机,以此来建立连接. 避免了在客户端配置证书
*/
private static void trustServer() {

SSLContext sslContext = null;

try {
sslContext = SSLContext.getInstance( "TLS ");

X509TrustManager[] xtmArray = new X509TrustManager[] { xTrustManager };

sslContext.init(null, xtmArray, new java.security.SecureRandom());

} catch (GeneralSecurityException e) {

e.printStackTrace();
}

if (sslContext != null) {

HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
.getSocketFactory());
}

HttpsURLConnection.setDefaultHostnameVerifier(hostNameVerifier);
}

/**
* 通过HTTPS发送消息
*
* @param url
* 要连接的servlet名
* @param message
* 要保存到文件的字符串
* @return 从另一个文件读取的字符串
*/
static String send(URL url, String message) {

trustServer();

HttpsURLConnection connection = null;

try {
connection = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}

connection.setDoOutput(true);

PrintWriter printWriter = null;

try {
printWriter = new PrintWriter(connection.getOutputStream());

} catch (IOException e) {
e.printStackTrace();
}

printWriter.print(message);
printWriter.flush();
printWriter.close();

BufferedReader in = null;

try {
in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
} catch (IOException e) {