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

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

相关推荐
一枚小小程序员哈1 小时前
基于asp.net 的在线餐饮订餐系统的设计与实现/基于c#的网上订餐系统/餐厅管理系统
后端·c#·asp.net
Best_Liu~6 小时前
策略模式 vs 适配器模式
java·spring boot·适配器模式·策略模式
你的人类朋友6 小时前
【Node&Vue】什么是ECMAScript?
前端·javascript·后端
你的人类朋友7 小时前
说说你对go的认识
后端·云原生·go
我崽不熬夜8 小时前
Java中基本的输入输出(I/O)操作:你知道如何处理文件吗?
java·后端·java ee
我崽不熬夜8 小时前
Java的异常处理机制:如何优雅地捕获和抛出异常?
java·后端·java ee
Ice__Cai8 小时前
Flask 之 Cookie & Session 详解:用户状态管理
后端·python·flask·cookie·session
我崽不熬夜9 小时前
掌握Java中的数组与集合:如何灵活处理不同的数据结构?
java·后端·java ee
jiunian_cn9 小时前
【Linux】线程
android·linux·运维·c语言·c++·后端
coding随想9 小时前
前端常见焦点事件(Focus)解析
后端