SpringMVC础配置

 

1. 静态资源映射

  1. 程序的静态资源js,css.图片等需要直接访问,可以在配置里面重写addResourceHandlers方法来实现

  2. 步骤如下:

    • 创建一个类并继承WebMvcConfigurationSupport

    • 添加注解@Configuration和@EnableWebMvc

    • 重写方法addResourceHanlders方法

@Configuration
@EnableWebMvc
public class MyMvcConfig extends WebMvcConfigurationSupport {
​
​
    /**
     * MVC前后缀等配置
     * @return
     */
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }
​
    /**
     * 静态资源映射
     * 程序的静态文件js,css,图片等需要直接访问,这时可以在配置里重写addResourceHandler方法来实现
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //addResourceLocations指的是文件放置的目录,addResourceHandler指的是对外暴露的访问路径
        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/**");
    }
}

 

2. 拦截器配置

拦截器实现对每一个请求处理前后进行相关的业务处理,类似于Servletde Filter,可让普通的Bean实现HandlerInterceptor或者继承HandlerInterceptorAdapter类来实现自定义拦截器

  • 配置步骤

    • 创建一个拦截器类并继承HandleInterceptor类

    • 在配置文件中配置自定义的拦截器类,并且重写addInterceptor方法,注册拦截器

public class DemoInterceptor extends HandlerInterceptorAdapter {
​
    /**
     * 在请求发生前执行,根据具体的业务需求来编写代码
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime",startTime);
        return true;
    }
​
    /**
     * 在请求发生后执行,根据具体的业务需求来编写代码
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (Long)request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime = System.currentTimeMillis();
​
        System.out.println("本次请求处理时间为:" + new Long(endTime - startTime) + "ms");
        request.setAttribute("handlingTime",endTime-startTime);
​
    }
}

 

@Configuration
@EnableWebMvc
public class MyMvcConfig extends WebMvcConfigurationSupport {
​
    /**
     * 配置拦截器的Bean
     * @return
     */
    @Bean
    public DemoInterceptor demoInterceptor()
    {
        return new DemoInterceptor();
    }
​
    /**
     * 重写addInterceptors方法,注册拦截器
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(demoInterceptor());
    }
}

 

3.文件上传配置

文件上传时一个项目里经常用到的功能,Spring MVC通过配置一个MultipartResolver来上传文件,在Spring的控制器中,通过MultipartFile来接收文件。

 

  • POM文件中添加依赖
     <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.3</version>
        </dependency>
     
  • 新建上传页面upload.jsp

    <div class="upload">
        <form action="upload" enctype="multipart/form-data" method="post">
            <input type="file" name ="file"/>
            <input type="submit" value="上传"/>
        </form>
    </div>
  • 配置文件

    @Configuration
    @EnableWebMvc
    public class MyMvcConfig extends WebMvcConfigurationSupport {
    ​
      @Bean
      public MultipartResolver multipartResolver()
      {
          CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
          multipartResolver.setMaxUploadSize(1000000);
          return multipartResolver;
      }
    }

     

3. 其他配置

  • 快捷的ViewController

    在实际开发中会涉及大量无任何业务处理,只是简单的页面跳转的情况,可以通过重写addViewControllers方法来配置

    @GetMapping("/index")
    public String index()
    {
        return "/index";
    }
    //对于无任何业务逻辑处理,只是简单的页面跳转

     

    重写addViewControllers方法,这样的代码更简洁,管理更集中

    @Configuration
    @EnableWebMvc
    public class MyMvcConfig extends WebMvcConfigurationSupport {
        /**
         * 重写addViewControllers方法,实现简单的页面跳转
         * @param registry
         */
        @Override
        protected void addViewControllers(ViewControllerRegistry registry) {
           registry.addViewController("/index").setViewName("/index");
           registry.addViewController("/homePage").setViewName("/homePage")
        }
    }

     

  • 路径匹配参数配置

    在SpringMVC中,路径参数如果带“.”的话,“.”后面的之将被忽略,通过重写configurationPathMatch方法,可不忽略“.”后面的参数

    @Configuration
    @EnableWebMvc
    public class MyMvcConfig extends WebMvcConfigurationSupport {
       
        @Override
        protected void configurationPathMatch(PathMatchConfigurer configurer) {
           configurer.setUseSuffixPatternMatch(false);
        }
    }
posted @ 2021-05-27 14:21  肖恩雷  阅读(59)  评论(0编辑  收藏  举报