Springboot对MVC、tomcat扩展配置

Springboot在web层的开发基本都是采用Springmvc框架技术,但是Springmvc中的某些配置在boot是没有的,我们就应该根据自己的需求进行对mvc扩展配置

Springboot1.x版本如何配置

通过注解@Configuration一个类,继承webmvcconfigureradapter,然后根据需求实现里面的方法。

Springboot2.x版本如何配置

通过实现webmvcconfigure接口的方式

上面boot对mvc的扩展配置既保留了mvc的默认配置,也可以使用我们扩展的配置。如何全面接管mvc的配置,所以的webmvc都由我们自己配置?只需要加上注解EnableWebMvc

扩展配置使用举例,如配置拦截器

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * 自定义一个登陆拦截器
 */
@Configuration //声明这是一个配置
public class LoginInterceptor extends WebMvcConfigurerAdapter {
    /*
    用来添加拦截器的方法
    InterceptorRegistry registry拦截器注册
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //使用匿名内部类创建要给拦截器
        HandlerInterceptor loginInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
                //判断session中是否存在用户
                if (request.getSession().getAttribute("user") == null) {
                    response.sendRedirect("/admin");
                    return false;
                }
                return true;
            }
 
            @Override
            public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
 
            }
 
            @Override
            public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
 
            }
        };
        registry.addInterceptor(loginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/admin").excludePathPatterns("/admin/login");
    }
}

tomcat配置

Springboot默认使用的就是嵌入式servlet容器即tomcat,对于web项目,如果使用的是外部tomcat,相关配置比如访问端口、资源路径等可以在tomcat的conf文件下配置。但是在boot中,tomcat配置又两种方式

第一种:通过配置文件直接配置(推荐)

java 复制代码
#如果是tomcat相关的设置用server.tomcat.xx
server.tomcat.uri-encoding=UTF-8
#如果是servlet相关的配置用server.xx
server.port=80

第二种:通过配置类的方式

相关推荐
昵称为空C1 小时前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
架构师沉默2 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
RoyLin2 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在3 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
Moonbit3 小时前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言
Goland猫3 小时前
电商架构图
后端
Java中文社群3 小时前
重要:Java25正式发布(长期支持版)!
java·后端·面试
我是天龙_绍3 小时前
Whisper 通过 mp3输出中文
后端
zjjuejin3 小时前
Maven环境搭建
后端·maven
我是天龙_绍3 小时前
项目根目录有requirements.txt 如何安装
后端