分析讲解SpringMVC注解配置如何实现

2022-11-13 08:11:09 注解 讲解 如何实现

简介

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

在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现,名为AbstractAnnotationConfigDispatcherServletInitializer,当我们的类扩展了AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet3.0容器的时候,容器会自动发现它,并用它来配置Servlet上下文。

意思就是容器会自动发现继承了AbstractAnnotationConfigDispatcherServletInitializer的子类,并用它来配置servlet上下文。(用来代替web.xml)

注解类代替web.xml

package com.hxut.rj1192.annoation;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
//代替web.xml   filter过滤器   spring  springmvc的配置类    dispracture的映射路径
public class webXml extends AbstractAnnotationConfigDispatcherServletInitializer {
    //    指定spring配置类
    @Override
    protected Class<?>[] getRootConfiGClasses() {
        return new Class[] {SpringConfig.class};
    }
    //    指定springmvc配置类
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }
    //    指定dispracture的映射路径 即url-pattern
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
//注册编码过滤器
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceRequestEncoding(true);
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        return new Filter[]{encodingFilter, hiddenHttpMethodFilter};
    }
}

注解类代替Spring-mvc.xml

Spring-mvc配置文件(不管是xml还是注解的类)有如下八个功能

  • 视图解析器  
  • 扫描包的范围(组件扫描)  
  • view-controller(只返回视图的控制方法)  
  • defalut-servlet-handler  静态资源处理
  • mvc注解驱动  
  • 文件上传解析器  
  • 异常处理  
  • 拦截器
package com.hxut.rj1192.annoation;
import com.hxut.rj1192.InterceptorReGIStry01;
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.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerInterceptor;
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 java.util.List;
import java.util.Properties;
//1视图解析器   2扫描包的范围(组件扫描)  3view-controller(只返回视图的控制方法)  4defalut-servlet-handler  静态资源处理和
//5  mvc注解驱动  6文件上传解析器   7异常处理   8拦截器
//代替springmvc的配置文件
//扫描包的范围(组件扫描)
@ComponentScan("com.hxut.rj1192")
//开启MVC注解驱动
@EnableWebMvc
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
    //配置视图解析器
//    这个注解是将类放进ioc容器中  因为web.xml中就是嵌套的,
    @Bean
    public ITemplateResolver templateResolver() {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        // ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过WebApplicationContext 的方法获得
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(
                webApplicationContext.getServletContext());
        templateResolver.setPrefix("/WEB-INF/templates/");
        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;
    }
//default-servlet configuure
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        WebMvcConfigurer.super.configureDefaultServletHandling(configurer);
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistry01 interceptorRegistry=new InterceptorRegistry01();
//        addPathPatterns("/");是设置拦截的url
//        excludePathPatterns(); 是设置不拦截的url
        registry.addInterceptor(interceptorRegistry).addPathPatterns("/");
    }
//视图控制器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/hello").setViewName("succes");
    }
    //配置文件上传解析器
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver();
        return commonsMultipartResolver;
    }
    //配置异常映射
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
        Properties prop = new Properties();
        prop.setProperty("java.lang.ArithmeticException", "error");
        //设置异常映射
        exceptionResolver.setExceptionMappings(prop);
        //设置共享异常信息的键
        exceptionResolver.setExceptionAttribute("ex");
        resolvers.add(exceptionResolver);
    }
}

 全用xml写:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
      <!--2.扫描包的范围(组件扫描)-->
    <context:component-scan base-package="com.hxut.rj1192.zyk"/>
    <!-- 1.配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
    <!--4.静态资源处理-->
    <mvc:default-servlet-handler/>
    <!--5.mvc注解驱动-->
    <mvc:annotation-driven/>
<mvc:interceptors>
    <bean class="com.hxut.rj1192.zyk.interceptor.interceptor01"/>
</mvc:interceptors>
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.ArithmeticException">error</prop>
            </props>
        </property>
        <property name="exceptionAttribute" value="ex"></property>
    </bean>
<! --3.view-controller-->
<mvc:view-controller path="/testView" view-name="success"></mvc:view-controller>
<! --4.文件上传解析器-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>
<! --7.异常处理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
                    <prop key="java.lang.ArithmeticException">error</prop>
                </props>
            </property>
            <!--        将错误信息放到ex这个变量中,并放进model中-->
            <property name="exceptionAttribute" value="ex"></property>
        </bean>
<! --8.拦截器-->
 <mvc:interceptors>
        <ref bean="first"></ref>
        <ref bean="second"></ref>
    </mvc:interceptors>
</beans>

拦截器文件

package com.hxut.rj1192;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InterceptorRegistry01 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("prehandle 执行");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("posthandle 执行");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterhandle 执行");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

到此这篇关于分析讲解SpringMVC注解配置如何实现的文章就介绍到这了,更多相关SpringMVC注解配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章