spring 自动为每个响应添加标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16190699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
automatically add header to every response
提问by Mayank Sharma
I want to add this header "Access-Control-Allow-Origin", "*" to every response made to the client whenever a request has made for rest controllers in my application to allow cross origin resource sharing Currently I 'm manually adding this header to each and every method like this
我想将此标头“Access-Control-Allow-Origin”,“*”添加到对客户端的每个响应,每当我的应用程序中的其余控制器发出请求以允许跨源资源共享目前我正在手动添加这个像这样的每个方法的标题
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Allow-Origin", "*");
Its working but its very frustrating . I found webContentInterceptor in spring docs which allow us to modify headers on each response
它的工作,但它非常令人沮丧。我在 spring 文档中找到了 webContentInterceptor,它允许我们修改每个响应的标题
<mvc:interceptors>
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="Access-Control-Allow-Origin" value="*"/>
</bean>
</mvc:interceptors>
but when i use this it throws error that property not found of name Access-Control-Allow-Origin so is there any other way we can automatically add header to every response
但是当我使用它时,它会抛出错误,找不到名称 Access-Control-Allow-Origin 的属性,所以有没有其他方法可以自动向每个响应添加标头
Update ! Spring framework 4.2 greatly simplifies this by adding @CrossOrigin annotation to either a method or a controller itself?https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
更新 !Spring 框架 4.2 通过向方法或控制器本身添加 @CrossOrigin 注释大大简化了这一点?https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
回答by Dayde
I recently got into this issue and found this solution. You can use a filter to add these headers :
我最近遇到了这个问题并找到了这个解决方案。您可以使用过滤器添加这些标题:
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null
&& "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers",
"X-Requested-With,Origin,Content-Type, Accept");
}
filterChain.doFilter(request, response);
}
}
Don't forget add the filter to your spring context:
不要忘记将过滤器添加到您的 spring 上下文中:
<bean id="corsFilter" class="my.package.CorsFilter" />
and the mapping in the web.xml:
以及 web.xml 中的映射:
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
To go a little further you can specify a Spring profile to enable or disable this filter with something like that:
更进一步,您可以指定一个 Spring 配置文件来启用或禁用此过滤器,如下所示:
<beans profile="!cors">
<bean id="corsFilter" class="my.package.FilterChainDoFilter" />
</beans>
<beans profile="cors">
<bean id="corsFilter" class="my.package.CorsFilter" />
</beans>
(providing the FilterChainDoFilter similar to the CorsFilter but which only does filterChain.doFilter(request, response);in the doFilterInternal(..))
(提供类似于 CorsFilter 但仅filterChain.doFilter(request, response);在 doFilterInternal(..) 中起作用的 FilterChainDoFilter )
回答by Mayank Sharma
Update ! Spring framework 4.2 greatly simplifies this by adding @CrossOrigin annotation to either a method or a controller itself https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
更新 !Spring 框架 4.2 通过向方法或控制器本身添加 @CrossOrigin 注释大大简化了这一点 https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
回答by Andrei N
If you want to set headers for controller you can use @ModelAttributeannotation.
如果要为控制器设置标头,可以使用@ModelAttribute注释。
@ModelAttribute
public void setVaryResponseHeader(HttpServletResponse response) {
response.setHeader("Vary", "Accept");
}
回答by Sudhakar
In the Spring 4, You can use the @CrossOrigin() which allows you the cross origin issue.
在 Spring 4 中,您可以使用 @CrossOrigin() 来解决跨源问题。
For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin. For example, as you're checking your bank account in one tab, you could have the evil.com website in another tab. The scripts from evil.com shouldn't be able to make AJAX requests to your bank API (withdrawing money from your account!) using your credentials.
出于安全原因,浏览器禁止对驻留在当前源之外的资源进行 AJAX 调用。例如,当您在一个选项卡中查看您的银行帐户时,您可以在另一个选项卡中查看 evil.com 网站。来自 evil.com 的脚本不应该能够使用您的凭据向您的银行 API 发出 AJAX 请求(从您的帐户中提取资金!)。
Cross-origin resource sharing (CORS) is a W3C specification implemented by most browsers that allows you to specify in a flexible way what kind of cross domain requests are authorized, instead of using some less secured and less powerful hacks like IFrame or JSONP.
跨域资源共享 (CORS) 是大多数浏览器实现的 W3C 规范,它允许您以灵活的方式指定授权的跨域请求类型,而不是使用一些安全性较低且功能较弱的黑客,如 IFrame 或 JSONP。
Spring Framework 4.2 GA provides first class support for CORS out-of-the-box, giving you an easier and more powerful way to configure it than typical filter based solutions.
Spring Framework 4.2 GA 为 CORS 提供了开箱即用的一流支持,与典型的基于过滤器的解决方案相比,它为您提供了一种更简单、更强大的配置方式。
You can add an @CrossOrigin annotation to your @RequestMapping annotated handler method in order to enable CORS on it. By default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation:
您可以向 @RequestMapping 带注释的处理程序方法添加 @CrossOrigin 注释,以便在其上启用 CORS。默认情况下,@CrossOrigin 允许 @RequestMapping 注释中指定的所有来源和 HTTP 方法:
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html
https://spring.io/guides/gs/rest-service-cors/
https://spring.io/guides/gs/rest-service-cors/
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
回答by Poocholamannan
I am also face this issue and i have add this code issue fixed.
我也面临这个问题,我已经添加了这个代码问题。
public static HttpServletResponse getResponse(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
return response;
}
回答by NilsH
WebContentInterceptordoesn't have a property named Access-Control-Allow-Origin, and as far as I can see, it does not expose any methods for setting response headers. It only sets some cache related headers by enabling/disabling some properties. But it's trivial to write your own interceptor (or servlet filter) that does this.
WebContentInterceptor没有名为 的属性Access-Control-Allow-Origin,据我所知,它没有公开任何设置响应标头的方法。它仅通过启用/禁用某些属性来设置一些与缓存相关的标头。但是编写自己的拦截器(或 servlet 过滤器)来执行此操作是微不足道的。

