ajax一般用来前端界面与后端界面交互使用。数据格式一般使用json,优点是便于对象与字符串的转化。
1.不适用json对象封装。
jsp:
<script>$.ajax({url: "/LoginServlet",data: {"name":name, "pwd":password},dataType: "json",type: "post",success: function (result) {if (result.code == "200") {alert(result.msg);}}})
</script>
后端:
String json1 = "{\"code\":200, \"message\":\"访问成功\"}";
out.print(json1);
2.使用json对象封装json格式化。
首先导入 fastjson-1.1.13.jar lib库。
这是json格式化代码,这个方法在我们刚导入的jar包中:
public String toJSONString(){
JSONObject jsonObject=new JSONObject();
return jsonObject.toJSONString(this);
}
加一层封装,这是一个工具类,用到了泛型:
package com.hz.utils;import com.alibaba.fastjson.JSONObject;public class JsonMessage<E> {private String code;//状态码private String msg;//状态码描述信息private E data;//数据public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public E getData() {return data;}public void setData(E data) {this.data = data;}public JsonMessage(String code, String msg, E data) {this.code = code;this.msg = msg;this.data = data;}public String toJSONString(){JSONObject jsonObject=new JSONObject();return jsonObject.toJSONString(this);}
}
调用类,把对象传进去,就会返回json格式字符串。
@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//ajax中 相应到页面处理乱码response.setCharacterEncoding("utf-8");String uname=request.getParameter("uname");String upwd=request.getParameter("upwd");//创建out对象PrintWriter out=response.getWriter();String json="";if(uname.equals("张三")&&upwd.equals("123")) {User user1=new User();user1.setId(1111);user1.setUserName("张三");user1.setUserPassword("123");User user2=new User();user2.setId(2222);user2.setUserName("李四");user2.setUserPassword("123");List<User> userList=new ArrayList<>();userList.add(user1);userList.add(user2);json= new JsonMassage<List<User>>("200","请求成功",userList).toJSONString();}out.print(json);}}