SpringBoot使用Jsp开发Web项目
1.简述
以前都是使用JSP页面开发,但是因为JSP无法实现Spring Boot的多种特性,所以Spring Boot不推荐使用JSP进行页面开发。
2.使用示例
引入相关依赖:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!--JavaServer Pages Standard Tag Library,JSP标准标签库--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!--内置tomcat对Jsp支持的依赖,用于编译Jsp--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency>
application.yml文件中添加Jsp模板配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
##添加jsp模板配置 spring: mvc: view: prefix: /WEB-INF/jsp/ suffix: .jsp
在webapp/css文件夹下添加main.css样式文件,内容如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
h1 {
color: #0000FF;
}
h2 {
color: #FF0000;
}
在webapp/WEB-INF/JSP文件夹下添加index.jsp文件,内容如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="./css/main.css"/> <title>测试页面</title> </head> <body> <h1>Spring Boot + Thymeleaf demo</h1> <h2>Message: + ${message}</h2> <!-- ${xxx} 引用 SpringMVC 中 HttpServletRequest 属性 --> </body> </html>
创建一个HelloController.java,内容如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Controller @RequestMapping("/hello") public class HelloController { @RequestMapping(method= RequestMethod.GET,produces="text/html;charset=UTF-8") public String hello(HttpServletRequest req) { req.setAttribute("message", "Hello World!"); return "index"; // templates\index.jsp } }
最后启动DemoApplication就可以访问,相关文件夹需要自己创建。
项目结构图如下: