在Spring MVC中从控制器调用JSP页面

4

我是Spring MVC的新手。我有一个控制器捕获了一个异常,捕获异常后我想要重定向到error.jsp页面并显示异常消息(ex.getMessage())。我不想使用Spring的异常处理程序,而是要通过编程方式重定向到error.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
}
1个回答

4
我不确定为什么你的方法要返回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");
}

谢谢Edward。你是对的。它不应该是String,这种方法会起作用。感谢您的回复。 - james01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接