SpringBoot整合SpringMVC

时间:2023-03-24 21:59:43

说明

以前SpringMVC要在web.xml中配置核心控制器、Spring的xml中配置扫码包、视图解析器

使用SpringBoot后,这些繁杂的配置都不需要了,虽然默认配置已经可以使用SpringMVC了,不过我们有时候需要进行自定义配置。

 

修改端口

查看SpringBoot的全局属性可知,端口通过以下方式配置:

server.port=8088

  

默认是8080,重启后,就能看到端口变成了8088

SpringBoot整合SpringMVC

 

访问静态资源

现在项目没有webapp,静态资源该放哪里呢?

WebProperties的内部类Resources中,主要定义了静态资源(.js,.html,.css等)的默认查找路径: (说明:版本是2.4.13)

public static class Resources {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
    private String[] staticLocations;
    private boolean addMappings;
    private boolean customized;
    private final WebProperties.Resources.Chain chain;
    private final WebProperties.Resources.Cache cache;

  

默认的静态资源路径为:

  classpath:/META-INF/resources/
  classpath:/resources/
  classpath:/static/
  classpath:/public/

这上面的静态资源不拦截

 

我们习惯会把静态资源放在 classpath:/static/ 目录下

SpringBoot整合SpringMVC

 

重启后测试:

请求的时候,不加上面静态资源所在的文件夹

http://127.0.0.1:8088/wx.bmp

 

如果是下面目录结构,访问的时候要加pic目录

SpringBoot整合SpringMVC

 

http://127.0.0.1:8088/pic/weixin.bmp

 

添加拦截器

拦截器也是我们经常需要使用的,拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了。

可以通过实现 WebMvcConfigurer 并添加 @Configuration 注解来实现自定义部分SpringMvc配置。

 

首先我们定义一个拦截器:

实现HandlerInterceptor接口(源码如下),下面方法前面加了default,方法体可以空实现,是jdk1.8的新特性

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.web.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;

public interface HandlerInterceptor {
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

  

拦截器

package com.qzcsbj.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description 拦截器
 */

public class LoginInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.info("执行preHandle方法了。。。");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        logger.info("执行postHandle方法了。。。");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.info("执行afterCompletion方法了。。。");
    }
}

 

然后,我们定义配置类,注册拦截器:

package com.qzcsbj.config;

import com.qzcsbj.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @description 拦截器配置类
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.loginInterceptor()).addPathPatterns("/**");
    }
}

  

控制器

package com.qzcsbj.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @GetMapping("/test")
    @ResponseBody
    public String hello() {
        return "hello interceptor";
    }
}

  

测试:

请求:http://127.0.0.1:8088/test

SpringBoot整合SpringMVC

 

日志:可以看到拦截器方法执行了

SpringBoot整合SpringMVC

 



本文作者:持之以恒(韧)
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevOps/TestOps)、测开等