- 解决ajax跨域操作
- ajax与spring通信中,json字符串和js对象及java对象之间的转化。
前端和后端分离是一种趋势,但前端和后端的通信,其实大多由ajax来承担。
spring mvc 中,由ajax 传递来的json字符串,在本文中用的是spring mvc的注解:@RequestBody来解析成java对象。
spring中返回的对象,自动传递给前端json字符串的操作,我们用spring web的配置:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
这里,我们选择了
FastJsonHttpMessageConverter
来使得我们的对象自动转换为json字符串,并返回到前端。
在本例子中,我用maven 的jetty插件运行一个web 服务,用web storm 写了一个简单的html5页面。
由于ajax跨域操作的原因,虽然web请求返回200,但是,前端始终不能正确执行,所以,我在spring mvc那层解决跨域操作,在web.xml配置一个过滤器:
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
,这个过滤器就解决了ajax跨域操作。
记得添加maven依赖:
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.4</version>
</dependency>
spring mvc 那层写了一个简单controller测试:
@Controller
public class SImpleController {
@RequestMapping("/getAString.do")
@ResponseBody
public ModelResult<String> getAString() {
ModelResult<String> modelResult = new ModelResult<>();
modelResult.setModel("hello doctor");
return modelResult;
}
@RequestMapping("/update.do")
@ResponseBody
public ModelResult<UserInfo> updateUserInfo(@RequestBody UserInfo userInfo) {
ModelResult<UserInfo> modelResult = new ModelResult<>();
userInfo.setName("hello doctor");
userInfo.setPasswd("1235678");
userInfo.setSex("man");
modelResult.setModel(userInfo);
return modelResult;
}
}
html5,ajax请求代码:
function getString(){
$.ajax({
url:"http://localhost:8080/getAString.do",
type:"POST",
dataType:'json',
success: function( data ) {
if(data.success == true) {
$(".divget").html("<strong>" + data.model + "</strong> ");
}else{
var errorInfo = data.error;
var str = "";
for(var p in errorInfo){
str += p +":" + errorInfo[p];
}
$( ".divget" ).html( "<strong>" + str + "</strong> " );
}
},
});
}
function update(){
var info ={
name:"",
passwd:"",
sex:""
};
$.ajax({
url:"http://localhost:8080/update.do",
type:"POST",
dataType:'json',
contentType:"application/json",
data:JSON.stringify(info),
success: function( data ) {
if(data.success == true) {
$(".update").html("<strong>" + JSON.stringify(data.model) + "</strong> ");
}else{
var errorInfo = data.error;
var str = "";
for(var p in errorInfo){
str += p +":" + errorInfo[p];
}
$( ".update" ).html( "<strong>" + str + "</strong> " );
}
}
});
}
dataType:'json',代表返回的内容格式。
contentType:"application/json", data:JSON.stringify(info),这个两行代表我们请求数据的格式是json字符串。js对象转json字符串的操作也有函数执行。
代码运行结果:
代码:https://github.com/sdcuike/springmvc-ajax
今天中秋,写的粗略了点,前端也没怎么接触过。