场景:
在一个servlet/bean中访问另一个servlet
实现方法:
需要:HttpClient.jar (Apache官方网站下载)
1、调用者
......
//创建client
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("xxx/checkuser");
NameValuePair[] data = {
new NameValuePair("loginaccount", account),
new NameValuePair("loginpassword", password)};
postMethod.setRequestBody(data);
//访问servlet
int statusCode = client.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
response.sendRedirect("/error.html");
}
//读取验证结果
byte[] responseBody = postMethod.getResponseBody();
String str = new String(responseBody);
......
2、被调用者
......
public void service(HttpServletRequest request, HttpServletResponse response) {
try {
String loginaccount = request.getParameter("loginaccount");
String loginpassword = request.getParameter("loginpassword");
.....
String usersxml = "";
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("user");
root.addAttribute("id", ...);
root.addAttribute("nickname", ...);
usersxml = doc.asXML();
response.setCharacterEncoding("UTF-8");
response.getWriter().println(usersxml);
} catch (Exception e) {
......
}
}
.......