我们在SpringMVC开发中,可以在xml配置中配置拦截器啊,视图解析器啊等功能,这些定制功能依靠boot的自动配置是无法实现的,这时候,我们需要在boot中扩展SpringMVC的功能。
操作步骤:
1)编写一个配置类,继承WebMvcConfigurerAdapter(该类不能标注@EnableWebMvc注解,如果加了就是全面接管MVC了,也就是boot对SpringMVC的自动配置失效了,所有都需要我们自己配置)
2)覆写需要用到的功能
例如:
package com.bjc.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
/** 视图解析器 */
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
// 浏览器发送 /bjc 请求,跳转到success页面
registry.addViewController("/bjc").setViewName("test");
}
}
测试截图:
SpringBoot整合JSP
在SpringBoot官方中,并不推荐我们使用JSP作为视图层技术,但是boot也支持jsp
操作步骤:
1)整合JSP,除了要基本的web启动器依赖外,还需要两个坐标
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- jasper -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
2)在application.properties添加访问jsp的前后缀配置信息
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
注意:这个配置类似于SpringMVC中的视图解析器的配置
3)Controller层
package com.bjc;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
/**
* 处理请求产生数据
*/
@RequestMapping("showUser")
public String showUser(Model model) {
List<User> userList = Stream.of(
new User("张三",1,20),
new User("李四",2,22),
new User("王五",3,23),
new User("赵六",4,24),
new User("钱七",5,22)
).collect(Collectors.toList());
// 数据封装
model.addAttribute("users", userList);
// 跳转到视图
return "users";
}
}
4)JSP
jsp文件的目录由application.properties的文件的配置决定
例如:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${users}" var="user">
id:${user.userid} 姓名:${user.username } 年龄:${user.userage } </br>
</c:forEach>
</body>
</html>
运行效果:
注意:使用JSP的时候需要打war包