1.利用myecilpse建立一个web项目
2.导入需要的包:
commons-beanutils.jar
commons-collections-3.1.jar
commons-lang-2.3.jar
commons-logging-1.1.jar
ezmorph-1.0.6.jar
json-lib-2.1.jar
json-lib.2.2.2-jdk15.jar
3.建立index.jsp页面(记得导入jquery包)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> <Meta http-equiv="pragma" content="no-cache"> <Meta http-equiv="cache-control" content="no-cache"> <Meta http-equiv="expires" content="0"> <Meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <Meta http-equiv="description" content="This is my page"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> function test() { //alert(1); $.ajax({ url:'<%=path%>/HelloServlet',dataType: "json" },type :'GET'alert(data.length); var stu = eval("(" + data + ")"); alert( $(data).get(0).name); alert( $(data).get("age")); } }); } </script> </head> <body> <table> <tr> <td>姓名:</td> <td><input type="text" id="userName" name="userName"></td> </tr> <tr> <td>密码:</td> <td><input type="text" id="passWord" name="passWord"></td> </tr> <tr> <td><input type="button" value="提交" onclick="test();"></td> </tr> </table> </body> </html>
4.建立Servlet
public class HelloServlet extends HttpServlet { public HelloServlet() { super(); } void destroy() { super.destroy(); Just puts "destroy" string in log Put your code here } doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { System.out.println("执行了-------------"); String name = (String)request.getParameter("name"); String password = (String)request.getParameter("password"); System.out.println(name + "," + password); student stu = new student(); stu.setAge(18); stu.setName("zhangsan"); JSONArray arr=JSONArray.fromObject(stu); PrintWriter out = response.getWriter(); out.println(arr.toString()); out.flush(); out.close(); } doPost(HttpServletRequest request,IOException { } void init() ServletException { } }
5.web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http:java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>com.milk.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>