有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring,显示异常或404上发生的错误视图

我有

@Controller
@RequestMapping(value="core/*")
public class CoreController {

    public static String exceptionOccurredView = "/core/exceptionOccurred";

    @ExceptionHandler(Throwable.class)
    public ModelAndView exceptionOccurred(Throwable exception, HttpServletResponse response, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName ( exceptionOccurredView );
        mv.addObject   ( "requestedUrl", Core.getCurrentUrlWithParams() );
        mv.addObject   ( "exception", exception );

        System.out.println( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + Core.getCurrentUrlWithParams() );
        return mv;
    }   

    @RequestMapping
    public void test0(HttpServletResponse response, HttpServletRequest request) throws IOException {
        throw new IOException();
    } 

}

这适用于核心url下发生的所有例外

如果我去url

localhost:8080/core/test0

将显示错误页面。如果我去:

localhost:8080/core/actionDoesNotExist

但如果我使用:

localhost:8080/controllerDoesNotExist/test0

不会显示错误,因为注释@ExceptionHandler仅对每个控制器有效

那么,如何实现一个全局的、非控制器连接的异常/错误处理程序呢


共 (1) 个答案

  1. # 1 楼答案

    一种方法是使用HandlerExceptionResolver的一些实现

    例如,要使用“SimpleMappingExceptionResolver”,请将其放在上下文中:

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
          <map>
             <entry key="IOException" value="io-error" />
          </map>
        </property>
        <property name="defaultErrorView" value="default-error"/>
    </bean>
    

    这样就可以定义从异常到错误页面的全局映射。如果需要更复杂的错误处理,请实现自己的解析器