2012-07-05 111 views
4

我是Spring MVC的新手。我捕获了异常,我想重定向到error.jsp页面并显示异常消息(ex.getMessage())后捕获异常的控制器。我不想使用Spring的异常处理程序,而是必须以编程方式重定向到error.jsp。从Spring MVC的控制器调用Jsp页面

@RequestMapping(value = "http/exception", method = RequestMethod.GET) 
public String exception2() 
{ 
    try{ 
     generateException(); 
    }catch(IndexOutOfBoundsException e){ 
     handleException(); 
    } 
    return ""; 
} 

private void generateException(){ 
    throw new IndexOutOfBoundsException();  
} 

private void handleException(){ 

    // what should go here to redirect the page to error.jsp 
} 

回答

2

我不确定你为什么要从你的方法中返回String; Spring MVC中的标准是针对使用@RequestMapping注释的方法返回ModelAndView,即使您没有使用Spring的异常处理程序。据我所知,你不能在没有返回ModelAndView的地方发送你的客户端到error.jsp。如果你需要帮助理解Spring控制器的基本思想,我发现this tutorial展示了如何在Spring MVC中创建一个简单的“Hello World”应用程序,并且它有一个简单的Spring控制器的好例子。

如果你想你的方法,如果它遇到异常返回错误页面,但否则返回正常页面,我会做这样的事情:

@RequestMapping(value = "http/exception", method = RequestMethod.GET) 
public ModelAndView exception2() 
{ 
    ModelAndView modelAndview; 
    try { 
     generateException(); 
     modelAndView = new ModelAndView("success.jsp"); 
    } catch(IndexOutOfBoundsException e) { 
     modelAndView = handleException(); 
    } 
    return modelAndView; 
} 

private void generateException(){ 
    throw new IndexOutOfBoundsException();  
} 

private ModelAndView handleException(){ 
    return new ModelAndView("error.jsp"); 
} 
+0

感谢爱德华。你是对的。它应该不是字符串,这种方式将起作用。感谢您的答复 – james01 2012-07-05 23:50:00

相关问题