0, background
Spring Boot this current development of Web applications, using Restful style to do before and after the end of the separation should be achieved mainstream. But there are also a lot of friends who use template engine, commonly used as Jsp / Thymeleaf / Freemarker.
Note Spring Boot officials have not recommended the use of JSP, and indeed operate too much trouble, but because JSP user body mass is quite large, so it is still a simple demonstration.
1, the introduction of modified JSP dependent pom.xml
Add a dependency, open SpringBoot support for Web projects and the JSP
<!-- 添加web开发功能 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--内嵌的tomcat支持模块 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- 对jstl的支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
2, add webapp directory for JSP files
Manually add src / main / webapp subdirectory and below, while a decentralized directory index.jsp for testing. Note that this directory is a Source Folder source code directory, not a regular file folder directory.
As shown below:
Sign up view resolver
Add in the configuration class view resolver
@SpringBootApplication
public class SpringbootTemplatedemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTemplatedemoApplication.class, args);
}
@Bean//注册视图解析器
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");//自动添加前缀
resolver.setSuffix(".jsp");//自动添加后缀
return resolver;
}
}
Creating a controller
Create a controller for jump to the page index.jsp
@Controller
public class JspController {
@RequestMapping("/jsp") // 访问路径
public String jsp(Model model) {
model.addAttribute("name", "猫哥");//携带属性值
return "index";//跳转页面
}
}
Creating Web Pages
Creating the index.jsp page, remove the back-end through to property values
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${name}
</body>
</html>
test
Direct access http://127.0.0.1:1004/jsp
, you can output the page to complete!