SpringBoot实践(一)之整合SpringMVC

lombok使用

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
</dependency>

@Data:自动提供getter和setter、hashCode、equals、toString等方法

@Getter:自动提供getter方法

@Setter:自动提供setter方法

@Slf4j:自动在bean中提供log变量,其实用的是Slf4觉得日志功能。

idea还得下载lombok插件

在这里插入图片描述
接下来,我们来看看如何用SpringBoot来玩转以前的SSM,我们沿用之前讲解SSM用到的数据库tb_user和实体类User

整合SpringMVC

引入

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

虽然默认配置已经可以使用SpringMVC了,不过我们有时候需要进行自定义配置。

日志级别控制:包名:级别
下面配置文件都是基于yml格式的

 logging:
    level:
       com.sise: debug
       org.springframework: debug

1.1.修改端口

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

# 映射端口
server:
     port: 8088

1.2.访问静态资源

现在,我们的项目是一个jar工程,那么就没有webapp,我们的静态资源该放哪里呢?

回顾我们上面看的源码,有一个叫做ResourceProperties的类,里面就定义了静态资源的默认查找路径:
默认的静态资源路径为:

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

只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理。

我们习惯会把静态资源放在classpath:/static/目录下。我们创建目录,并且添加一些静态资源:
在这里插入图片描述
通过浏览器访问:http://localhost:8088/1234.png
在这里插入图片描述

1.3.添加拦截器

拦截器也是我们经常需要使用的,在SpringBoot中该如何配置呢?

拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了。在SpringBoot官方文档中有这么一段说明:

If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

翻译:

如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器, 视图控制器、消息转换器 等等),你应该让一个类实现WebMvcConfigurer,并且添加@Configuration注解,但是千万不要@EnableWebMvc注解。如果你想要自定义HandlerMappingHandlerAdapterExceptionResolver等组件,你可以创建一个WebMvcRegistrationsAdapter实例 来提供以上组件。

如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一切特征,你可以自己定义类并且添加@Configuration注解和@EnableWebMvc注解

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

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

public class LoginInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.debug("preHandle method is now running!");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        logger.debug("postHandle method is now running!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.debug("afterCompletion method is now running!");
    }
}

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

@Configuration
public class MvcConfig implements WebMvcConfigurer{
    /**
     * 通过@Bean注解,将我们定义的拦截器注册到Spring容器
     * @return
     */
    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }

    /**
     * 重写接口中的addInterceptors方法,添加自定义拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 通过registry来注册拦截器,通过addPathPatterns来添加拦截路径
        registry.addInterceptor(this.loginInterceptor()).addPathPatterns("/**");
    }
}

结构如下:
在这里插入图片描述
浏览器再次访问:http://localhost:8088/1234.png
发现拦截器已经执行了,preHandle method is now running!

2019-10-22 23:16:28.056 DEBUG 3068 --- [nio-8088-exec-2] o.s.web.servlet.DispatcherServlet        : GET "/1234.png", parameters={}
2019-10-22 23:16:28.072 DEBUG 3068 --- [nio-8088-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-10-22 23:16:28.075 DEBUG 3068 --- [nio-8088-exec-2] com.sise.interceptor.LoginInterceptor    : preHandle method is now running!
2019-10-22 23:16:28.084 DEBUG 3068 --- [nio-8088-exec-2] com.sise.interceptor.LoginInterceptor    : postHandle method is now running!
2019-10-22 23:16:28.085 DEBUG 3068 --- [nio-8088-exec-2] com.sise.interceptor.LoginInterceptor    : afterCompletion method is now running!
2019-10-22 23:16:28.086 DEBUG 3068 --- [nio-8088-exec-2] o.s.web.servlet.DispatcherServlet        : Completed 304 NOT_MODIFIED
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值