2011-11-16 64 views
1

我正在研究J2EE,Spring mvc中的應用程序。針對一個錯誤顯示不同主題的錯誤頁面

應用程序有兩個主題。如果java.lang.Exception來處理它。 我在web.xml配置錯誤頁爲:任何主題

<error-page> 
    <exception-type>java.lang.Exception</exception-type> 
    <location>/WEB-INF/jsp/uncaughtException.jsp</location> 
</error-page> 

每次顯示uncaughtException.jsp。我想爲不同的主題展示不同的頁面。

回答

3

我做了以下工作,以顯示不同的異常不同的消息,我認爲這個技巧可以幫助你。

我每次都用不同的消息重新定向異常,並在同一頁面上顯示此消息。

@ExceptionHandler(Exception.class) 
     public ModelAndView handleMyException(Exception exception) { 
     ModelAndView mv = new ModelAndView("redirect:errorMessage?error="+exception.getMessage()); 
     return mv; 
       } 

    @RequestMapping(value="/errorMessage", method=RequestMethod.GET) 
    public ModelAndView handleMyExceptionOnRedirect(@RequestParamter("error") String error) { 
     ModelAndView mv = new ModelAndView("uncaughtException"); 
     mv.addObject("error", error); 
     return mv; 
     } 

更新:

您還可以使用SimpleMappingExceptionResolver它可能是你的情況更爲有用: 你可以映射每個異常的每一頁和默認頁面。

<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 
    <property name="exceptionMappings"> 
     <props> 
      <prop key="org.springframework.dao.DataAccessException">/general/error/500</prop> 
      <prop key="freemarker.core.InvalidReferenceException">/general/error/500</prop> 
      <prop key="NumberFormatException">/general/error/500</prop> 
     </props> 
    </property> 
    <property name="defaultErrorView" value="/general/error/500" /> 
</bean> 

Update 2: I think you need to treat 404 separately. 

<error-page> 
    <error-code>404</error-code> 
    <location>/WEB-INF/pages/404.jsp</location> 
    </error-page> 
+0

感謝這麼好的答案。該解決方案是控制器特定的我想要應用程序特定的解決方案來處理應用程序級別的異常請幫忙。 –

+0

查看我的更新,我認爲這可能會有所幫助。 –

+0

我也是這麼做的。當然,它的作品。參考:http://thinkinginsoftware.blogspot.com/2011/02/handling-errors-in-spring-framework.html –