views:

854

answers:

2

How do I get a spring 3.0 controller to trigger a 404?

I have a controller with @RequestMapping(value = "/**", method = RequestMethod.GET) and for some urls accessing the controller I want the container to come up with a 404.

+3  A: 

Rewrite your method signature so that it accepts HttpServletResponse as a parameter, so that you can call setStatus(int) on it.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments

matt b
+10  A: 

Since Spring 3.0 you also can throw an Exception declared with @ResponseStatus annotation:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    ...
}

@Controller
public class SomeController {
    @RequestMapping.....
    public void handleCall() {
        if (isFound()) {
            // whatever
        }
        else {
            throw new ResourceNotFoundException(); 
        }
    }
}
axtavt
+1 hey, nice, I hadn't noticed that feature yet
skaffman
Interesting. Can you specify which HttpStatus to use at the throw site (i.e. not have it compiled into the Exception class)?
matt b
@mattb: I think the point of `@ResponseStatus` is that you define a whole bunch of strongly-typed, well-named exception classes, each with their own `@ResponseStatus`. That way, you decouple your controller code from the detail of HTTP status codes.
skaffman
I see. Pretty neat idea. I need to start using the 3.0 annoations and learn all this goodness!
matt b
There's a lot of cool stuff in Spring 3 that isn't headline-grabbing... I discovered `@Async` today, and it's bloody nice
skaffman
I was hoping there was an exception to throw. Thanks.
NA
I have no clue why there isn't a NonOkStatusException that handles all this; the annotations seem pointlessly verbose. Still, it beats injecting the HttpResponse...
davetron5000