<script type="text/javascript" src="js/jquery-1.10.2.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.post("LoginServlet", {name:"ding", pass:"ying"}, function(data){ alert(data.label + ", " + data.value); }, "json"); }); </script>
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dys.model.Message; import com.google.gson.Gson; @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String pass = request.getParameter("pass"); if("ding".equals(name) && "ying".equals(pass)) { Message message = new Message(); message.setLabel("系统提示"); message.setValue("用户登录成功!"); Gson gson = new Gson(); String messageGSon = gson.toJson(message); response.setContentType("text/plain;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter printWriter = response.getWriter(); printWriter.print(messageGSon); printWriter.flush(); } } }