方式1.利用spring中的一个注解@CrossOrigin(推荐)
将该注解加到controller上,如下:
@Controller
@CrossOrigin
@Scope("prototype")
@RequestMapping(value="/test")
public class HelloWorldController {
@RequestMapping(value="/users/{userName}", method=RequestMethod.GET)
public @ResponseBody User findUser(@PathVariable("userName") String userName) {
User user = new User();
user.setUserName(userName);
user.setSex("男");
System.out.println(123456789);
return user;
}
}
方式2.加过滤器filter
首先添加一个过滤器类类似下面:
package com.ygz.filter;//所在的包 import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; public class CorsFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletResponse httpServletResponse = (HttpServletResponse) arg1; httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); arg2.doFilter(arg0, httpServletResponse); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
然后在web.xml中添加filter过滤器如下即可:
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>spring.mvc.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>