新冠病毒🦠还在阻挡全世界重启,但我们学习脚步不不能停滞,接下来给大家展示一个现在开发中已经不太常用的一个小知识点,希望对大家有所启发。
在平时 大家可能用 Spring Boot 2 最多就是开发 RESTful API,可能很少有人在 Spring Boot 2 中用过JSP视图,那我就来一起体验下创建一个用 JSP 视图的 Spring Boot 2 应用有多么方便。
一起来看看我们需要些什么
项目结构
咱们可以从 Spring Initializer 获取项目框架。
项目依赖
pom.xml
|
配置
- 启动类配置
SpringBootServletInitializer 按传统的 WAR包 部署方式来运行 SpringBootJspApplication。
SpringBootJspApplication.java
package com.eprogrammerz.examples.spring.springbootjsp; |
- Resources
application.propertiesspring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
Controller and View Template
写一个简单映射方法的Controller
package com.eprogrammerz.examples.spring.springbootjsp.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
public class HelloController {
({"/", "/hello"})
public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String name) {
model.addAttribute("name", name);
return "hello";
}
}将下面内容保存成 JSP 文件,放在
src/main/webapp/WEB-INF/jsp/目录
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello ${name}!</title>
</head>
<body>
<h2 class="hello-title">Hello ${name}!</h2>
</body>
</html>
使用Maven运行
在项目根路径下使用命令行运行程序。
mvn clean spring-boot:run |
访问 localhost:8080 测试你的程序效果。

