一、创建一个JavaWEBProject
二、创建一个Servlet(下面的例子中用到了Json--第32行,Json的作用是将一个Object类转换为特定格式的字符串,如果不用Json直接返回字符串也行)。
1 package com.czj.ajax; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet;10 import javax.servlet.http.HttpServletRequest;11 import javax.servlet.http.HttpServletResponse;12 13 public class AJAXServlet extends HttpServlet {14 public void doGet(HttpServletRequest request, HttpServletResponse response)15 throws ServletException, IOException {16 }17 18 public void doPost(HttpServletRequest request, HttpServletResponse response)19 throws ServletException, IOException {20 boolean flag = false;21 System.out.println(request.getParameter("userName"));22 if("陈泽俊".equals(request.getParameter("userName"))) 23 flag = true;//登陆成功标志24 System.out.println(request.getParameter("password"));25 response.setContentType("text/html;charset=utf-8");26 PrintWriter out = response.getWriter();27 28 Mapmap = new HashMap ();29 map.put("userName","陈泽俊");30 map.put("password", "123456");31 map.put("flag", flag);//登陆失败32 out.print(MyJson.objectToJson(map));//返回登录信息33 out.flush();34 out.close();35 }36 }
上面的32行有一个MyJson的类,其代码如下:
【注意】用Json的时候要先引入Json所需的基本jar包
1 package com.czj.ajax; 2 3 4 import net.sf.json.JSONArray; 5 6 public class MyJson { 7 public static String objectToJson(Object resultobj){ 8 if (resultobj != null) { 9 JSONArray obj = JSONArray.fromObject(resultobj); 10 return (obj.toString());11 }12 return "";13 } 14 }
三、写相应的jsp页面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 8 9 10 11 34 35 36 373856 57394440
43- 用户名:
41 42455046
49- 密码:
47 48515552 53
54