Adding headers to Spring controllers

人走茶凉 提交于 2020-01-23 08:05:17

问题


I know this question is very similar to this one, but I feel its different and specific enough to warrant its own question here.

I've just inherited a Java web app project from a sole developer who left no documentation behind. Its a Spring MVC app with a basic package structure as follows:

com.ourOrg.app.controllers
    ImageController
    ProgramController
    UserController
com.ourOrg.app.otherPackages

Each Controller class is just a POJO annotated with @Controller and @RequestMapping("/blah"). For instance:

@Controller
@RequestMapping("/images")
public class ImageController() {
    @RequestMapping(value="/saveImage", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> saveImage(@RequestParam(value="imageData", required=true) String imageXML, HttpServletRequest request){
        // This method gets executed whenever the:
        // http://ourSite.com/images/saveImage
        // URL is hit
    }
}

I have been asked to add the following HTTP headers to the Spring config so that we disable browser caching:

Pragma: no-cache

Cache-Control: no-cache

Expires: -1

The article I linked to above makes it sound like our controllers should be extending this WebContentGenerator class. Unfortunately, there are dozens of controllers with an enormous number of methods, so refactoring each one to extend or inherit some base type is not really a viable option (unless its the only option!).

I've also seen articles that make it sound like you have to configure Spring to use AOP interceptors that modify your response headers, but now I'm really getting into unfamiliar territory.

Given our setup and implementation of Spring MVC, whats the easiest way for me to add these three simple headers to every response sent back by the server (regardless of which controller or method is executed)?

Thanks in advance!


回答1:


Hoping you are using Spring 3, you can look at an interceptor, then you won't have to modify all of your controllers (since you said you had many). It looks like they may already have one implemented that you can just use. Check out Bozho's answer to this question how to set header no cache in spring mvc 3 by annotation




回答2:


I realize this is an old post but maybe this will help somebody. I am using spring for this example. The main thing is use the annotation for parameters.
@Controller public class HelloController {

@RequestMapping(value = "/hello.htm")
public String hello(@RequestHeader(value="User-Agent") String userAgent)

    //..
}

}



来源:https://stackoverflow.com/questions/10607729/adding-headers-to-spring-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!