2014-11-02 56 views
1

我想要做的是,當用戶輸入無處不在的url時,我的意思是這個url沒有任何資源比專門的映射工作。如何在Spring MVC中爲不存在的資源設置url映射?

例如,我有一個控制器:

@Controller 
public class LoginController { 

    @RequestMapping(value = {"/", "/login"}, method = RequestMethod.GET) 
    public ModelAndView welcome() { 
     return new ModelAndView("mainPage"); 
    } 
} 

這種映射工作時,當用戶進入{contextPath中} /或{contextPath中} /登錄 現在我想所有其他URL映射,我喜歡這:

@Controller 
public class LoginController { 

    @RequestMapping(value = {"/", "/login"}, method = RequestMethod.GET) 
    public ModelAndView welcome() { 
     return new ModelAndView("mainPage"); 
    } 

    @RequestMapping(value = {"/**"}, method = RequestMethod.GET) 
    public ModelAndView notFound() { 
     return new ModelAndView("customized404Page"); 
    } 
} 

現在,當用戶進入例如{的contextPath}無效路徑/ sdfsdf customized404Page被示出爲他

但是最後的映射是更一般的並且它始終工作,這就是爲什麼第一次映射不起作用。

問題: 如何映射所有無效的URL? 或者也許在春季有一些簡單的方法來解決這個問題?

回答

1

有一個自定義的404頁面的最簡單方法是將它們配置在web.xml

<error-page> 
    <error-code>404</error-code> 
    <location>/error404.jsp</location> 
</error-page> 

當一個簡單的jsp是不夠的,因爲你需要一個完全成熟的春天控制器,然後您可以將位置映射到控制器的映射:

@Controller 
public class HttpErrorController { 

    @RequestMapping(value="/error404") 
    public String error404() { 
     ... 
     return "error404.jsp"; 
    } 
} 

<error-page> 
    <error-code>404</error-code> 
    <location>/error404</location> 
</error-page>