Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

java - How to set response header in spring mvc

I have a method in which i want to set response header cache-control and pragma :-

public String addUser(@Valid User user, BindingResult bindingResult)
{
    if(bindingResult.hasErrors())
    {
        bindingResult.getFieldError();
        return"edit";
    }
    return "redirect:/welcome/profile/"+user.getName();
}

In this method i want to set cache-control and pragma like we do in simple servlet code using HttpservletResponse calling setHeader method :-

response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader("Expires", 0);

I searched spring docs and could not find any direct way to do it, but I found this:-

@RequestMapping("/something")
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException 
{
    String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader"));
    byte[] requestBody = requestEntity.getBody();
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("MyResponseHeader", "MyValue");
    return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}

But I dont know how to use it

question from:https://stackoverflow.com/questions/18534478/how-to-set-response-header-in-spring-mvc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to set headers for every response for a controller you can use @ModelAttribute annotation.

@ModelAttribute
public void setVaryResponseHeader(HttpServletResponse response) {
    response.setHeader("Vary", "Accept");
}    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...