我正在寻找一种干净的方法,当没有找到请求的资源时,在Spring4中返回定制的404错误页面。对不同域类型的查询应该会导致不同的错误页面。
下面是一些代码来显示我的意图(Meter是一个域类):
@RequestMapping(value = "/{number}", method = RequestMethod.GET)
public String getMeterDetails(@PathVariable("number") final Long number, final Model model) {
final Meter result = meterService.findOne(number);
if (result == null) {
// here some code to return an errorpage
}
model.addAttribute("meter", result);
return "meters/details";
}
我设想了几种处理这个问题的方法。首先,可以创建像这样的RuntimeException
@ResponseStatus(HttpStatus.NOT_FOUND)
public class MeterNotFoundExcption extends RuntimeException { }
然后使用异常处理程序呈现自定义错误页(可能包含指向仪表列表的链接或其他合适的链接)。
但我不喜欢污染我的应用程序,因为有许多小的例外。
另一种可能是使用HttpServletResponse
并手动设置状态代码:
@RequestMapping(value = "/{number}", method = RequestMethod.GET)
public String getMeterDetails(@PathVariable("number") final Long number, final Model model,
final HttpServletResponse response) {
final Meter meter = meterService.findOne(number);
if (meter == null) {
response.setStatus(HttpStatus.NOT_FOUND.value());
return "meters/notfound";
}
model.addAttribute("meter", meter);
return "meters/details";
}
但在这个解决方案中,我必须为许多控制器方法(如edit、delete)复制前5行。
有没有一种优雅的方法来避免多次重复这些代码行?
发布于 2014-01-14 21:53:34
解决方案比想象的要简单得多。可以使用如下定义的一个通用ResourceNotFoundException
:
public class ResourceNotFoundException extends RuntimeException { }
然后,可以使用ExceptionHandler
注释来处理每个控制器中的错误:
class MeterController {
// ...
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {
return "meters/notfound";
}
// ...
@RequestMapping(value = "/{number}/edit", method = RequestMethod.GET)
public String viewEdit(@PathVariable("number") final Meter meter,
final Model model) {
if (meter == null) throw new ResourceNotFoundException();
model.addAttribute("meter", meter);
return "meters/edit";
}
}
每个控制器都可以为ResourceNotFoundException
定义自己的ExceptionHandler
。
发布于 2015-02-05 06:51:34
您可以像下面这样在web.xml中映射错误代码
<error-page>
<error-code>400</error-code>
<location>/400</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500</location>
</error-page>
现在,您可以创建一个控制器来映射当发现这些错误时命中的url。
@Controller
public class HTTPErrorHandler{
String path = "/error";
@RequestMapping(value="/404")
public String error404(){
// DO stuff here
return path+"/404";
}
}
完整示例请参见my tutorial about this
发布于 2015-01-31 04:45:16
https://stackoverflow.com/questions/21061638
复制相似问题