Ajax访问Servlet的跨域请求问题—Access-Control-Allow-Origin

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guoquanyou/article/details/62437997

<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<form >
	用户名:<input type="text" id="userName"/><br/>
	密码:<input type="password" id="userPwd"/><br/>
	<input type="button" value="登录" id="sender"> 
</form>
<div id="messageDiv"></div>

<script>
$('#sender').click(function(){
	var userName=document.getElementById('userName').value;
	var userPwd=document.getElementById('userPwd').value;
	var user={userName:userName,userPwd:userPwd};

	var url="http://10.30.1.102:8080/partner-back/LoginUserServlet";
	$.post(url, JSON.stringify(user), function(data) {
            $("#messageDiv").html(data);
        }); 
});
</script>


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 doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Writer out = response.getWriter();
		JSONObject jsonObject=new JSONObject();
		
		//获取客户端发送的json数据
		JSONObject json=null;		
		try {
			json=JsonReader.receivePost(request);
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("message", "用户登录失败!");
			out.write("{}");
			out.flush();
			return;
		}
		System.out.println(json);

		UserService userService=new UserService();		
		//将建json对象转换为java对象
		User loginUser = (User)JSONObject.toBean(json,User.class);
		User user = userService.LoginUser(loginUser);
		
		if(user!=null){
			//将java对象转换为json对象
			jsonObject.put("user", JSONObject.fromObject(user));
			jsonObject.put("message", "用户登录成功!");
			jsonObject.put("token", token);
		}else{
			jsonObject.put("message", "用户登录失败!");
		}
		out.write(jsonObject.toString());
		out.flush();
	}
}

@WebFilter("/*")
public class CORSFilter implements Filter {

    public CORSFilter() {
    }

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
        //设置跨域请求
        HttpServletResponse response = (HttpServletResponse) res;         
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3628800"); 

        System.out.println("设置跨域请求");
        chain.doFilter(req, response);  
    } 

	public void init(FilterConfig fConfig) throws ServletException {
	}
}


阅读更多

没有更多推荐了,返回首页