@CrossOrigin 进行跨域资源访问的处理操作
在这个案例中我返回的值为json类型,所以我们要先引用jars,pom.xml文件:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
在spring-mvc.xml中添加配置:
<mvc:annotation-driven enable-matrix-variables="true">
<mvc:message-converters>
<ref bean="fastJsonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!--设置转换时特性-->
<property name="features">
<array>
<value>WriteNullBooleanAsFalse</value>
<value>WriteNullListAsEmpty</value>
<value>WriteNullStringAsEmpty</value>
<value>WriteNullNumberAsZero</value>
</array>
</property>
</bean>
再编写一个CrosController类:
@Controller
@RequestMapping(value = "/cros")
public class CrosController {
// 可以进行跨域操作的地址:这里我是使用了HBuilder编写了一个页面,进行了异步请求
@CrossOrigin(value = {"http://127.0.0.1:8020"})
//produces:指明响应content-type
@GetMapping(value = "loadUser",produces={"application/json"})
@ResponseBody
public User loadUser(){
User user=new User();
user.setId(123123);
user.setName("mj");
user.setPwd("1");
return user;
}
}
我在HBuilder这个软件中写了一个页面:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /></head>
<body>
<script src="js/jquery.js"></script>
<script>
$.ajax({
type:"get",
url:"http://localhost:8080/cros/loadUser",
success:function(data){
alert(data.id);
}
});
</script>
</body>
</html>
这里直接点击访问:
出现页面结果:
F12查看: