Servlet解析JSON数据和发送JSON数据

package com.bsh.util;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
 
public class JsonReader {
	public static JSONObject receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
 
		// 读取请求内容
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		//将json字符串转换为json对象
		JSONObject json=JSONObject.fromObject(sb.toString());
		return json;
	}
}

 

创建用户登录Servlet

package com.bsh.servlet;
 
import java.io.IOException;
import java.io.Writer;
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.bsh.pojos.User;
import com.bsh.service.UserService;
import com.bsh.util.JsonReader;
import net.sf.json.JSONObject;
@WebServlet("/LoginUserServlet")
public class LoginUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	public LoginUserServlet() {
		super();
	}
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// response.setContentType("text/html");
		// 设置字符编码为UTF-8, 这样支持汉字显示
		// response.setCharacterEncoding("UTF-8");
 
		response.setContentType("text/html;charset=utf-8");
 
		/** 设置响应头允许ajax跨域访问 **/
		response.setHeader("Access-Control-Allow-Origin", "*");
		/* 星号表示所有的异域请求都可以接受, */
		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
 
		Writer out = response.getWriter();
 
 
		JSONObject json=JsonReader.receivePost(request);
		System.out.println(json);
		
		UserService userService=new UserService();
		
		//将建json对象转换为java对象
		User loginUser = (User)JSONObject.toBean(json,User.class);
		User user = userService.LoginUser(loginUser);
		JSONObject jsonObject=new JSONObject() ;
		if(user!=null){
			//将java对象转换为json对象
			jsonObject.put("user", JSONObject.fromObject(user));
			jsonObject.put("message", "用户登录成功!");
		}else{
 
			jsonObject.put("message", "用户登录失败!");
		}
		out.write(jsonObject.toString());
		out.flush();
	}
}

用户登录界面代码

<%@ page language="java" contentType="text/html; charset=utf-8"%>




Servlet-json



	
用户名:
密码:

 

附项目中用到的json的jar包和js文件,点击此处进行下载。

创作不易,如果感觉对你有帮助,请支持一下作者,微信扫下面二维码。

微信扫码打赏1元

你可能感兴趣的:(Servlet解析JSON数据和发送JSON数据)