One of the problems that you will inevitably encounter when doing web development is cross-domain, which is blocked by the same-origin policy of the browser, and the request cannot be sent at all. Since the Spring version used is 3.2.13, the @CrossOrigin annotation is not yet supported, and the method of adding a Header such as Access-Control-Allow-Origin to the Response is not very effective, so I won’t talk about it, I just said it here The JSONP method solves the cross-domain problem.
Assuming that the fastjson library is used, the following processing is performed in the Controller:
if(null != user){//登录成功
//放入session
session.setAttribute(Constants.DEV_USER_SESSION, user);
//页面跳转(main.jsp)
JSONPObject jsonpObject = new JSONPObject();
jsonpObject.setFunction(callback);//callback是控制器从请求中接收的参数
jsonpObject.addParameter(user);
return jsonpObject;
}
In fact, the jackson library can also be used. Coincidentally, there is also a JSONPObject class with the same name, but the encapsulation method is a little different.
In addition, some modifications are required in the client JS. The code to initiate the Ajax request is:
<script>
function login(){
//...省略一些表单验证代码
var userName = $("[name=devCode]").val();
var password = $("[name=devPassword]").val();
$.ajax({
type:"POST",//请求类型
url:"http://txtx44.natappfree.cc/AppInfoSystem/dev/dologin",//请求的url
data:{"devCode":userName,"devPassword":password},//请求参数
dataType:"jsonp",//jsonp是为了能跨域请求
jsonp: "callback", //参数名
jsonpCallback: "handleData", //参数值:回调函数名
error:function(res){
alert("请求失败!"+res.toString());
}
});
}
//独立的函数,处理返回的jsonp数据
function handleData(res){
if(res && res.devCode != ""){
alert("登录成功!");//省略跳到主页的代码。。。
}else{
alert("登录失败!")
}
}
</script>
By the way, I want to sell an advertisement. My video account insists on publishing online science popularization and exposing various scams. Follow me and learn strange knowledge together!