2014-12-22 60 views
2

我是Spring,也是JSP中的新成員。我正在項目中工作,我需要創建一個頁面,在特定的例外情況下應用程序將被重定向。 我有服務的方法拋出一個例外。這個方法在我們的一個頁面控制器中用@RequestMapping註解來調用。因此,爲了重定向到特定的錯誤頁面,我使用@ExceptionHanlder創建了兩個方法來處理此控制器中的這些異常。它看起來如何:使用JSP處理由Spring處理的異常顯示消息

@ExceptionHandler(IllegalStateException.class) 
public ModelAndView handleIllegalStateException (IllegalStateException ex) { 
    ModelAndView modelAndView = new ModelAndView("redirect:/error"); 
    modelAndView.addObject("exceptionMsg", ex.getMessage()); 
    return modelAndView; 
} 

但還不夠。我還需要創建ErrorPageController:

@Controller 
@RequestMapping("/error") 
public class ErrorPageController { 
    @RequestMapping(method = RequestMethod.GET) 
    public ModelAndView displayErrorPage() { 
     return new ModelAndView("error"); 
    } 
} 

現在工程顯示錯誤頁面。但我的問題是,我不能在JSP中顯示錯誤信息...... 我:

<h3>Error page: "${exceptionMsg}"</h3> 

但我沒有看到一個消息; /取而代之的是,我在URL看到消息:

localhost/error?exceptionMsg=Cannot+change+participation+status+if+the+event+is+cancelled+or+it+has+ended. 

而且因爲在網址我想有隻「本地主機/錯誤」,僅此而已這是錯的。這條消息我想在JSP中顯示。

+0

因爲您使用空模型創建新模型和視圖。但爲什麼你需要一個自定義異常處理程序?默認的策略包括拋出的異常在一個名爲'exception'的屬性中。這樣它應該可用於您的錯誤頁面。這裏的主要問題是你正在做一個重定向來觸發一個新的請求,因此你需要一個控制器。默認情況下,模型參數被編碼爲請求參數。在處理錯誤的控制器中,不要創建新的模型和視圖,只需在頁面中返回「錯誤」,或者在配置中聲明視圖控制器,就可以爲您節省一個類。 –

+0

嗯,它的工作原理,但如何在JSP中顯示消息?是否有可能打印其他網址?因爲現在我有我打開的URL,但我想看到或被重定向到「localhost/error」。我需要這個,因爲應用程序以這種方式工作... – Lui

+0

重定向不是問題在於控制器選擇視圖時,您正在使用該控制器銷燬模型(即使其爲空)。此外,對於重定向,您希望使用「RedirectAttributes」而不是普通模型。 –

回答

3

要解決這兩個問題的(顯示的消息,並有正確的URL )你應該在原代碼中將你的異常處理方法改爲例如

@ExceptionHandler(IllegalStateException.class) 
public RedirectView handleIllegalStateException(IllegalStateException ex, HttpServletRequest request) { 
    RedirectView rw = new RedirectView("/error"); 
    FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request); 
    if (outputFlashMap != null) { 
     outputFlashMap.put("exceptionMsg", ex.getMessage()); 
    } 
    return rw; 
} 

爲什麼?如果你想讓你的屬性通過重定向持久化,你需要將它們添加到flash範圍。上面的代碼使用FlashMap,從文檔

甲FlashMap被重定向(通常在會話)之前保存並 被重定向之後可用,並立即除去。

如果它是一個正常的控制器的方法,你可以簡單地添加RedirectAttributes作爲參數,但@ExceptionHandler方法,RedirectAttributes的參數都沒有得到解決,所以你需要添加HttpServletRequest和使用RedirectView的。

+0

Oooo!現在太棒了! :D謝謝:) – Lui

2

你必須改變ModelAndView到:

@ExceptionHandler(IllegalStateException.class) 
public ModelAndView handleIllegalStateException (IllegalStateException ex) { 
    ModelAndView modelAndView = new ModelAndView("error"); 
    modelAndView.addObject("exceptionMsg", ex.getMessage()); 
    return modelAndView; 
} 

而且有這部分的error.jsp中:

<h3>Error page: "${exceptionMsg}"</h3> 
+0

它也有效,但仍然有與URL相同的問題...我需要有「localhost/error」URL。 – Lui