springboot外置tomcat,集成jsp
前言:
很多人可能会有疑惑,既然springboot-web-start都集成tomcat了,而且那么方便,为什么还要用外置的tomcat呢?一开始维护一个旧项目时,我也是这样想的,但是随后我也理解了,因为springboot内置tomcat不支持jsp这种模板,在以前jsp写网页也是挺流行的,就在现在可能还有许多项目也都用jsp。
然后我也去网上搜索了一下使用外置tomcat的优势,其实总的来说,还是要根据具体项目背景,业务情况来定的,使用外置的tomcat进行优化web服务器的性能可能要比springboot自定义配置tomcat,优化配置要简单点,还有旧的项目网页编写可能用JSP来展现的,然后项目技术升级到springboot,如果网页模板在换成Thymeleaf可能工作量比较大。
集成外置Tomcat:
- 建web项目的时候,选上集成spring-boot-starter-web(注意创建项目时,打包方式选择war包)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--将嵌入式的Tomcat指定为provided-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
-
编写一个SpringBootServletInitializer的子类,并调用configure方法
public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(PurchaseApplication.class); } }
-
然后配置本地tomcat测试运行
集成jsp:
-
在application.properties里配置视图解析器
在webapp下面新建WEB-INF包,当然你的jsp也可以直接放在webapp下面,但是prefix 就要修改了,能够匹配就行。
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
-
项目部分目录
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kbCSeFH0-1574345080535)(F:\笔记\Linux_zfc\image\1574344847919.png)]
不要忘了配置一下web.xml
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
</web-app>
hello.jsp :
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
hello jsp
<a href="/success">abc</a>
</body>
</html>
controller :
@Controller
public class testController {
@GetMapping("/success")
public String testsueecess(Model model) {
//Model 和 ModelMap 的实例都是spirng mvc框架来自动创建并作为控制器方法参数传入,用户无需自己创建
//封装页面需要的数据,页面获取值可以用el表达式${msg}来获取
model.addAttribute("msg", "nasl");
return "success";
}
}
success.jsp :
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
success
<h3>${msg}</h3>
</body>
</html>