2014-01-26 71 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