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

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

相关推荐
weixin_419658311 小时前
Spring 的统一功能
java·后端·spring
小许学java1 小时前
Spring AI-流式编程
java·后端·spring·sse·spring ai
canonical_entropy1 小时前
对《DDD本质论》一文的解读
后端·架构·领域驱动设计
码事漫谈2 小时前
我用亲身经历告诉你,为什么程序员千万别不把英语当回事
后端
码事漫谈2 小时前
C++ const 用法全面总结与深度解析
后端
间彧2 小时前
分布式单例模式在微服务架构中的实际应用案例
后端
间彧2 小时前
分布式系统中保证单例唯一性的Java解决方案
后端
间彧2 小时前
为什么避免在单例中保存上下文状态
后端
EnCi Zheng2 小时前
SpringBoot + PostgreSQL 密码认证失败 Windows 系统解决方案
windows·spring boot·postgresql
间彧2 小时前
单例模式防御反射与序列化攻击的意义与实践
后端