前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringMVC 最新 WebMvcConfigurer 视图解析器 异常处理器 拦截器

SpringMVC 最新 WebMvcConfigurer 视图解析器 异常处理器 拦截器

作者头像
陶然同学
发布2023-02-24 09:41:23
2960
发布2023-02-24 09:41:23
举报
文章被收录于专栏:陶然同学博客

目录

WebMvcConfigurer

视图解析器

异常处理器

拦截器


WebMvcConfigurer

1.概述

WebMvcConfigurer配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。基于java-based方式的spring mvc配置,需要创建一个配置类并实现WebMvcConfigurer 接口;

在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现WebMvcConfigurer接口(推荐),方式二继承WebMvcConfigurationSupport类

视图解析器

  实现:

        1.实现WebMvcConfigurer接口

        2.重写configureViewResolvers 该方法是用来配置视图解析器的 该方法有一个参数ViewResolverRegistry是一个注册器 用来注册你想定义的视图解析器    

代码语言:javascript
复制
	/**
	 * Configure view resolvers to translate String-based view names returned from
	 * controllers into concrete {@link org.springframework.web.servlet.View}
	 * implementations to perform rendering with.
	 * @since 4.1
	 */
	default void configureViewResolvers(ViewResolverRegistry registry) {
	}

        3.添加@EnableWebMvc 开启个性化定制

        4.覆盖configurerViewResolvers

代码语言:javascript
复制
@Configuration
@ComponentScan(basePackages="com.czxy.mvc.controller")
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/pages/",".jsp");
    }
}

异常处理器

        异常处理器的实现方式有两种

        第一种:实现类 编写实现类实现HandlerExceptionResolver接口

        第二种:增强类 

                使用@ControllerAdvice对Controller进行增强

                使用ExceptionHandler用于捕获控制器里面的异常 并进行处理?

方式一:实现HandlerExceptionResolver接口

代码语言:javascript
复制
@Component
public class CustomExceptionResolver  implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        // 1 统一异常
        CustomExcption customExcption = null;
        if(e instanceof CustomExcption) {
            customExcption = (CustomExcption) e;
        } else {
            customExcption = new CustomExcption("系统繁忙,请稍后重试!");
        }

        // 2 错误信息返回
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message" ,customExcption.getMessage());
        modelAndView.setViewName("forward:/error.jsp");

        return modelAndView;
    }
}

方式二:通知类

        @CotrollerAdvice 全局异常处理

        @ExceptionHandler 用来统一处理方法异常

代码语言:javascript
复制
@ControllerAdvice
public class GlobalExceptionResolver {

    /**
     * 自定义异常处理器
     * @param ec
     * @param model
     * @return
     */
    @ExceptionHandler(CustomExcption.class)
    public String custom(CustomExcption ec, Model model) {
        model.addAttribute("message", ec.getMessage() + "Global");
        return "forward:/error.jsp";
    }

    /**
     * 其他异常处理器
     * @param e
     * @param model
     * @return
     */
    @ExceptionHandler(Exception.class)
    public String other(Exception e, Model model) {
        model.addAttribute("message", "系统繁忙,请稍后重试!" + "Global");
        return "forward:/error.jsp";
    }
}

拦截器

        preHandler:拦截器之前执行 返回true继续执行 返回false结束

        postHandler:执行完Controller之后执行

        afterCompletion:视图渲染完成之后完成

拦截器:

代码语言:javascript
复制
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("1 拦截前");
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("3 执行中");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("5 最后完成");
    }
}

实现WebMvcConfigurer接口 重写addInterceptor方法 设置拦截路径

代码语言:javascript
复制
@Configuration      //配置类
@ComponentScan(basePackages = {"com.czxy.inter.controller","com.czxy.inter.interceptor"})
@EnableWebMvc
public class SpringMVCConfig implements WebMvcConfigurer {

    @Resource
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration1 = registry.addInterceptor(myInterceptor);
        interceptorRegistration1.addPathPatterns("/**");
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • WebMvcConfigurer
  • 视图解析器
  • 异常处理器
  • 拦截器
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档