spring拦截器

2019-05-06  本文已影响0人  万物皆有序和公式
public class ExpectionProcessInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        if (e != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resultCode", 1);
            if (e instanceof BusinessException) {
                jsonObject.put("resultInfo", e.getMessage());
            } else if (e instanceof Exception) {
                jsonObject.put("resultInfo", "系统异常");
            }
            e.printStackTrace();
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            PrintWriter out = response.getWriter();
            out.print(jsonObject.toJSONString());
            out.flush();
            out.close();
        }
    }
}
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 对所有的请求拦截使用/** ,对某个模块下的请求拦截使用:/myPath/* -->
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/**/*.html"/>
            <mvc:exclude-mapping path="/**/*.css"/>
            <mvc:exclude-mapping path="/**/*.js"/>
            <mvc:exclude-mapping path="/**/*.jpeg"/>
            <mvc:exclude-mapping path="/**/*.gif"/>
            <mvc:exclude-mapping path="/**/*.png"/>
            <mvc:exclude-mapping path="/**/*.eot"/>
            <mvc:exclude-mapping path="/**/*.otf"/>
            <mvc:exclude-mapping path="/**/*.svg"/>
            <ref bean="exceptionInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
    <bean name="exceptionInterceptor" class="com.ttf.gateway.web.ExpectionProcessInterceptor"/>
</beans>
上一篇下一篇

猜你喜欢

热点阅读