使用springboot搭建的maven web工程,模板引擎是jsp,(工程目录照着之前springmvc的配置,jsp文件放在根目录的webapp文件夹下,同时在application.properties下配置视图的前缀和后缀),此时,如果项目的打包形式是war(war需要在web容器下运行),打包后可以正常在容器内运行。
而如果打包形式是jar(jar可以直接部署),打包后无法访问工程文件里面的静态视图文件。虽然有方法可以解决此问题,但还是从根本角度出发,springboot不支持jsp这种模板引擎,还是使用官方推荐的thymeleaf等模板引擎,同时在resource目录下配置静态资源视图文件,而不采用springmvc的webapp那种工程目录结构。
项目打包形式为jar包时,工程静态视图的访问:
1. 在pom.xm中加入支持JSP的依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
2. 创建src/main/webapp/WEB-INF/views目录,JSP文件就放这里
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
Hello ${name}
</body>
</html>
3. 在src/main/resources/application.properties文件中进行解析器的配置
# MVC
spring.view.prefix=/WEB-INF/views/
spring.view.suffix=.jsp
4. 编写Controller
@Controller
public class SampleController {
@RequestMapping("/hello"
)
public String getListaUtentiView(ModelMap map){
map.put("name", "Spring Boot"
);
return "home";
}
}
5. 编写Application类
@SpringBootApplication
public class WebApplication
extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApplication.
class);
}
public static void main(String[] args)
throws Exception {
SpringApplication.run(WebApplication.class, args);
}
}
6. 以java application方式运行后,就可以访问http://locahost:8080/hello
注意:在IDE中可以
java application方式运行,但打包一定是打成war包,需要修改pom中packaging为<packaging>war</packaging>,把war把放入tomcat运行