在原来的spring中我们通过xml的方式对mvc进行配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
</beans>
现在,我们可以用@EnableWebMvc注释启用MVC配置,如下所示:
@Configuration
@EnableWebMvc //加上EnableWebMvc这个注解,springboot对于springmvc的自动配置就完全失效
public class WebConfig {
}
下面以实例说明。
1. 创建工程
首先创建如下工程:
2. 创建配置类
创建如下配置类:
package cn.tx.sboot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
}
package cn.tx.sboot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class TestController {
@RequestMapping("hello")
public String hello(){
return "hello springmvc";
@RequestMapping("test")
public String test(){
return "test springmvc";
}
}
3. 创建拦截器
创建一个interceptor拦截器:
package cn.tx.sboot.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("前置拦截得到执行");
return true;
}
}
创建好后再到配置类添加拦截方法:
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/hello");
}
}
- addInterceptor:需要一个实现HandlerInterceptor接口的拦截器实例
- addPathPatterns:用于设置拦截器的过滤路径规则; addPathPatterns("/**")对所有请求都拦截
- excludePathPatterns:用于设置不需要拦截的过滤规则
- 拦截器主要用途:进行用户登录状态的拦截,日志的拦截等待
设置好后我们启动进行测试:
拦截成功
4. 创建视图解析器
这里用thymeleaf的方式实现视图解析。
首先引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
4.2 创建HTML模板:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtm11-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
test thymeleaf
</body>
</html>
4.3 在config类添加视图解析方法:
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("t_index").setViewName("index");
}
addViewController:URL请求的路径
setViewName:实际的资源路径
4.4 测试
OK,这样就不用再专门写一个方法来进行跳转了。