how to set common header for all RequestMappings in a controller

Rohit Bajaj
Rohit Bajaj used Ask the Experts™
In my controller i have the following line in each requestMapping method :
        response.setHeader(contentSecurityolicy.getHttpHeader(), contentSecurityPolicy.toString());

Open in new window

There are 4 such methods... Is there any way i can avoid this so as to specify this header only once in controller and
it gets added to all the responses ?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®


Also in some codebase i saw that they created a filter for adding content security policy header.
Whats the correct approach as per designing ?
Should i just add it like above in each request mapping.. or create a filter and so controller does not know about adding of this header ?
IT Business Systems Analyst / Software Developer
Top Expert 2015
Ok, it is not so obvious but any method annotated with @ModelAttribute will get executed for any of the 4 methods in your controller, so you could add the following to your controller...

public void setContentSecurityPolicyHeader(HttpServletResponse response) {
        response.setHeader(contentSecurityolicy.getHttpHeader(), contentSecurityPolicy.toString());

Open in new window

As for what is the best design, it depends on a few factors... If you are setting the same headers from *multiple* controllers than it might be best to use a filter. Also, only if the resources that need the headers can be distinguished from those that shouldn't have them based on the request path (as that generally decides what filters to run). Also, it may depend on whether any data available in the controller affects what gets set in the headers.

From the limited info that you provide above, it looks like the controller doesn't have much input as to what is set for those headers, so my feeling would be that it would be better set in a filter.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial