SpringBoot的嵌入式容器可以让我们很容易的部署应用,只需要打个jar包即可,简单便携,但是默认情况下,不支持JSP,优化定制比较麻烦。所以,我们有时候,需要使用外置的容器(tomcat),然后以war包的方式打包。
1. idea配置tomcat
1)点击edit Configuration
2)在弹窗中,点击加号,选择tomcat,点击local,如图:
3)在弹窗中点击configure..
4)点击加号
5)选择tomcat目录
2. 创建一个web项目
2.1 创建项目
创建项目,打包方式选择war
2.2 修改pom
将内置的tomcat容器设为provided
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
2.3 生成webapp目录
可以手动创建,也可以使用idea工具创建。
点击右上角的图标,如图:
点击Module——WEB,双击如图所示地方,点击ok
最后添加web.xml文件,也可以通过idea工具生成。
点击加号,选择web.xml,如图:
在弹窗中补全web.xml的路径即可,如图:
2.4 编写初始化类SpringBootServletInitializer
编写一个SpringBootServletInitializer的子类,并调用configure方法
package com.bjc.demo;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//传入SpringBoot应用的主程序
return application.sources(DemoApplication.class);
}
}
2.4 编写一个测试的jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>hello JSP</h1>
</body>
</html>
2.5 启动程序
注意:不是启动boot的启动类,而是启动tomcat,如图:
测试,在浏览器输入url
3. 页面跳转
我们也可以在hello.jsp中写一个超链接,访问controller,并跳转到另一个jsp
操作步骤:
1)超链接
2)success页面
在WEB-INF目录下新建success.jsp页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/6/7 0007
Time: 下午 06:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
Success <h4>${msg}</h4>
</body>
</html>
3)controller
package com.bjc.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Hello {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","hello jsp");
return "success";
}
}
4)视图解析器配置
在SpringMVC中,我们会配置访问的前后缀,这里我们可以在application.properties配置文件中配置,配置之后,在controller中就可以直接返回文件名称就可以了。
# 配置前缀
spring.mvc.view.prefix=/WEB-INF/
# 配置后缀
spring.mvc.view.suffix=.jsp
访问:
点击超链接