在 Spring-MVC 控制器中触发 404?
问题描述:
如何让 Spring 3.0 控制器触发 404?
How do I get a Spring 3.0 controller to trigger a 404?
我有一个带有 @RequestMapping(value = "/**", method = RequestMethod.GET)
的控制器,还有一些 URLs 访问控制器,我希望容器提供 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.
答
自 Spring 3.0 起,您还可以抛出用 @ResponseStatus
注释:
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();
}
}
}