Question

I have a case where i need to :

  • Return a 304 not modified status if the blog hasnt been modified
  • Or return the blog view if it's been modified since If-Modified-Since request header

The problem is when i want to return 304 status, how do i tell spring mvc not to assume another view from the null return, and start sending the response with the status immediately ?

@RequestMapping(value={"/blogs/{blogId}"}, method=RequestMethod.GET)
public String hello(final HttpServletRequest req, final HttpServletResponse resp, final Model model,
        @PathVariable("blogId") final String blogId) {
    if (isModified(req, blogId)) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return null; // this doesnt stop spring mvc to assume a view name
    }

    populate(model, grabBlog(blogId));
    return "blog";
}
Was it helpful?

Solution

From the HTTP perspective returning a view doesn't make sense at all. The Spring documentation covers that use case:

@RequestMapping
public String myHandleMethod(WebRequest webRequest, Model model) {

    long lastModified = // 1. application-specific calculation

    if (request.checkNotModified(lastModified)) {
        // 2. shortcut exit - no further processing necessary
        return null;
    }

    // 3. or otherwise further request processing, actually preparing content
    model.addAttribute(...);
    return "myViewName";
}

There are two key elements to note: calling request.checkNotModified(lastModified) and returning null. The former sets the response status to 304 before it returns true. The latter, in combination with the former, causes Spring MVC to do no further processing of the request.

OTHER TIPS

You can create an exception with the appropriate annotation and then throw it. Spring will then generate a page for that error code.

From: http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
public class OrderNotFoundException extends RuntimeException {
    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top