结合Ajax类使用:http://www.cnblogs.com/hfultrastrong/p/7267171.html
javascript代码:
<script type="text/javascript" src="js/AjaxRequest.js"></script> <script type="text/javascript"> var xhr = Ajax(); var url = "IsExistUserAjaxServlet"; var params = "name=张三&age=12&sex=woman"; /* GET */ var des_url_get = url + "?nocache=" + new Date().getTime() + "&" + params; xhr.get(des_url_get, function(data) { console.log(data); }); /* POST*/ /* var des_url_post = url + "?nocache=" + new Date().getTime(); xhr.post(des_url_post, params, function(data) { console.log(data); }); */ </script>
servlet代码:
一定要设置编码,这对于使用中文的数据很重要。
request.setCharacterEncoding("UTF-8");
response.setContentType("text/text;charset=utf-8");
package com.gordon.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "IsExistUserAjaxServlet", urlPatterns = { "/IsExistUserAjaxServlet" })
public class IsExistUserAjaxServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public IsExistUserAjaxServlet() {
super();
}
public void init(ServletConfig config) throws ServletException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/text;charset=utf-8");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
int age = Integer.valueOf(request.getParameter("age"));
System.out.println(name + ", " + sex + ", " + age);
response.getWriter().println("name:" + name + "age:" + age + "sex:" + sex);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}