• SpringMVC中的注解配置


    13、注解配置springmvc

    使用配置类和注解代替web.xml和SpringMVC配置文件的功能

    13.1、创建初始化的类,代替web.xml

    在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为

    SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现,名为AbstractAnnotationConfigDispatcherServletInitializer,当我们的类扩展了

    AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet3.0容器的时候,容器会自动发现它,并用它来配置Servlet上下文。

    13.2、使用流程

    1. 声明一个类来继承AbstractAnnotationConfigDispatcherServletInitializer,并且实现他的抽象方法
    2. 实现配置SpringConfig的java文件
      @Override
          protected Class<?>[] getRootConfigClasses() {
              return new Class[]{SpringConfig.class};
          }
      
    3. 实现SpringMvcConfig的java文件
      @Override
      protected Class<?>[] getServletConfigClasses() {
          return new Class[]{SpringMvcConfig.class};
      }
      

    13.3、实例代码

    1.继承AbstractAnnotationConfigDispatcherServletInitializer的java文件
    /**
     * @author ning0
     * @date 2024/6/25 22:24
     * @description WebInit
     */
    public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        //加载spring配置类
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class[]{SpringConfig.class};
        }
    
        //加载springmvc配置类
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class[]{SpringMvcConfig.class};
        }
    
        //设置DispatcherServlet的url-pattern
        @Override
        protected String[] getServletMappings() {
            return new String[]{"/"};
        }
    
        @Override
        protected Filter[] getServletFilters() {
    
            // 创建编码过滤器
            CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
            // 设置编码格式
            characterEncodingFilter.setEncoding("UTF-8");
            // 设置强制编码
            characterEncodingFilter.setForceEncoding(true);
    
            // 创建请求方式的过滤器
            HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
    
            return new Filter[]{characterEncodingFilter, hiddenHttpMethodFilter};
        }
    }
    
    
    2.SpringMvcConfig.java文件
    package com.qc.config;
    
    import com.qc.interceptors.FirstInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.context.ContextLoader;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ViewResolver;
    import org.springframework.web.servlet.config.annotation.*;
    import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
    import org.thymeleaf.spring5.SpringTemplateEngine;
    import org.thymeleaf.spring5.view.ThymeleafViewResolver;
    import org.thymeleaf.templatemode.TemplateMode;
    import org.thymeleaf.templateresolver.ITemplateResolver;
    import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
    
    import javax.servlet.ServletContext;
    import java.util.List;
    import java.util.Properties;
    
    /**
     * @author ning0
     * @date 2024/6/25 22:27
     * @description SpringMvcConfig
     */
    // 配置类
    @Configuration
    // 扫描controller
    @ComponentScan("com.qc.controller")
    // 开启SpringMvc注解
    @EnableWebMvc
    public class SpringMvcConfig implements WebMvcConfigurer {
    
        // 默认servlet处理器 静态资源映射
        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    
    
        @Override
        // 配置视图控制器
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            FirstInterceptor firstInterceptor = new FirstInterceptor();
            registry.addInterceptor(firstInterceptor).addPathPatterns("/**").excludePathPatterns("/");
        }
    
        // 异常解析器
        @Override
        public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
            SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
            Properties properties = new Properties();
            properties.setProperty("java.lang.ArithmeticException", "error");
            simpleMappingExceptionResolver.setExceptionMappings(properties);
            simpleMappingExceptionResolver.setExceptionAttribute("ex");
            resolvers.add(simpleMappingExceptionResolver);
    
        }
    
    
        // 配置视图解析器
        @Bean
        public ITemplateResolver templateResolver() {
            WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
            ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(webApplicationContext.getServletContext());
            templateResolver.setPrefix("/WEB-INF/pages/");
            templateResolver.setSuffix(".html");
            templateResolver.setCharacterEncoding("UTF-8");
            templateResolver.setTemplateMode(TemplateMode.HTML);
            return templateResolver;
        }
    
    
        // 配置模板引擎
        @Bean
        public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            templateEngine.setTemplateResolver(templateResolver);
            return templateEngine;
        }
    
    
        // 配置视图解析器注入引擎
        @Bean
        public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
            ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
            viewResolver.setCharacterEncoding("UTF-8");
            viewResolver.setTemplateEngine(templateEngine);
            return viewResolver;
        }
    
    
    }
    
    3.SpringConfig.java
    package com.qc.config;
    
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @author ning0
     * @date 2024/6/25 22:26
     * @description SpringConfig
     */
    
    //将该类标注为配置类
    @Configuration
    public class SpringConfig {
    
    }
    

    g.springframework.context.annotation.Configuration;

    /**

    • @author ning0
    • @date 2024/6/25 22:26
    • @description SpringConfig
      */

    //将该类标注为配置类
    @Configuration
    public class SpringConfig {

    }

    
    
  • 相关阅读:
    win11 无法登录微软账户 终极解决方案
    C语言:union类型
    排列与二进制(暑假每日一题 33)
    基于PaddleOCR开发easy click文字识别插件
    基于SpringBoot+Vue架构的药物咨询平台
    智能,除了计算,还有……
    TypeScript学习总结(一)
    迭代器的介绍
    三角函数概述
    实现简单的多节点抢注(主)功能
  • 原文地址:https://blog.csdn.net/NiNg_1_234/article/details/140108053