SpringMVC中的拦截器

it2024-02-21  94

6、SpringMVC中的拦截器

6.1、拦截器的作用

SprigMVC的拦截器类似于Serlvet开发中的过滤器Filter,用于对处理器进行预处理和后处理。 用户可以自己定义一些拦截器来实现特定的功能。

拦截器和过滤器的区别:

过滤器是servlet规范中的一部分,任何java web工程都可以使用。 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用。

过滤器是在url-pattern中配置了 /*之后,可以对所有要访问的资源拦截。 拦截器只会拦截访问的控制器方法,如果访问的是jsp,html,css,image或者js,是不会拦截的。

拦截器也是AOP思想的具体应用 我们要想自定义拦截器,就必须实现HandlerIntercepto接口

6.2、异常处理

如果我们不对异常进行处理(编写异常处理器组件),异常抛给前端控制器后,会直接在页面上显示错误信息,非常不好。

步骤是:

编写自定义异常类(做提示信息的)编写异常处理器配置异常处理器(跳转到提示页面)

思路:Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进行处理。

代码:

(1)自定义异常类SysException类

public class SysException extends Exception{ //存储提示信息 private String message; public SysException(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }

(2)自定义异常处理器SysExceptionResolver

//异常处理器 public class SysExceptionResolver implements HandlerExceptionResolver { /** * * @param httpServletRequest * @param httpServletResponse * @param o * @param e 传过来的异常对象 * @return */ public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //获取异常对象 SysException eee = null; if (e instanceof SysException){ eee = (SysException) e; }else { eee = new SysException("系统正在维护"); } //创建ModelAndView对象 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("errorMsg",eee.getMessage()); modelAndView.setViewName("error"); return modelAndView; } }

(3)在springmvc.xml中添加bean

<!--配置异常处理器--> <bean id="sysExceptionResolver" class="com.lu.exception.SysExceptionResolver" />

(4)创建一个error.jsp页面显示错误信息

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <%--获取信息--%> ${errorMsg} </body> </html>

(5)运行点击异常处理,跳出页面

最新回复(0)