2014-01-26 80 views
0

我的使用案例实践:
我有多个“之类的逻辑部分的”我的应用程序,由URL分开。是这样的:
- someUrl/servletPath/onePartOfMyApplication/...
- someUrl/servletPath/otherPartOfMyApplication/...最佳的处理PageNotFound未映射的请求映射

现在我想办理各部分不同映射的请求(404)。

如何我现在处理它:
我的web.xml:

... 
<error-page> 
<error-code>404</error-code> 
<location>/servletPath/404.html</location> 
</error-page> 

我的控制器:

@Controller 
public class ExceptionController 
{ 
    @ResponseStatus(value = HttpStatus.NOT_FOUND) 
    @RequestMapping(value = "/404.html") 
    protected String show404Page(final HttpServletRequest request) 
    { 
    final String forward = (String) request.getAttribute("javax.servlet.forward.request_uri"); 

    // parse string and redirect to whereever, depending on context 
    final String redirectPath = parse(forward); 

    return "redirect: " + redirectPath; 
    } 
    ... 

我的目标:
是否有一个更优雅(类似Spring的)处理404s,而不是在控制器或拦截器中解析请求,并声明错误页面e在我的web.xml中?

将是很好,如果我的控制器应能是这个样子:

@Controller 
    public class ExceptionController 
    { 
     @ResponseStatus(value = HttpStatus.NOT_FOUND) 
     @RequestMapping(value = "/onePartOfMyApplication/404.html") 
     protected String show404PageForOnePart(final HttpServletRequest request) 
     { 
     // do something 
     ... 
     return "onePartPage"; 
     } 

     @ResponseStatus(value = HttpStatus.NOT_FOUND) 
     @RequestMapping(value = "/otherPartOfMyApplication/404.html") 
     protected String show404PageForOtherPart(final HttpServletRequest request) 
     { 
     // do something different 
     ... 
     return "otherPartPage"; 
     } 

回答

2

我用@ExceptionHandler注解。在控制器我有类似:

private class ItemNotFoundException extends RuntimeException { 
    private static final long serialVersionUID = 1L; 
    public ItemNotFoundException(String message) { 
     super(message); 
    } 
    } 

    @ExceptionHandler 
    @ResponseStatus(HttpStatus.NOT_FOUND) 
    public void handleINFException(ItemNotFoundException ex) { 

    } 

然后我抛出一个异常,无论是在控制器(或服务层):

@RequestMapping("/{id}") 
    @ResponseBody 
    public Item detail(@PathVariable int id) { 
    Item item = itemService.findOne(id); 
    if (item == null) { throw new ItemNotFoundException("Item not found!"); } 
    return item; 
    } 

你可以做任何你喜欢的方法注解与@ExceptionHandler。现在在我的例子中,它显示了一个标准的404错误,你可以在web.xml中自定义,但是你可以做更多的事情。请参阅文档:http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html

+0

对于您的映射变得“不好”的情况,这是一个很好的做法。但我正在寻找一种解决方案来抓住所有其他未匹配的网址。 – user871611

+1

看到这个博客文章:http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc –

+0

这就是我之前阅读的,非常好的博客文章但是这篇文章没有处理我的问题。或者我在这里错过了一些东西。请纠正我。 – user871611