说明
这篇日志需要使用页面模版,这里选用 thymeleaf,在 pom.xml 中 <dependencies> 标签内添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
编写控制器
src/
+- main/
+- java/
+- com/
+- lee/
+- springbootdemo/
+- pojo/
+- User.java
+- controller/
+- TestController.java
+- TestRestController.java
+- SpringBootDemoApplication.java
+- resources/
+- <other resource>
User.java
public class User {
private Long id;
private String username;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@Controller
TestController.java
@Controller
@RequestMapping("/users")
public class TestController {
@GetMapping("/{id}")
public String user(Model model, @PathVariable Long id) {
User u = new User();
u.setId(id);
u.setUsername("admin");
u.setPassword("admin");
model.addAttribute("user", u);
return "user";
}
}
user.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
ID:<span th:text="${user.id}"></span><br>
username:<span th:text="${user.username}"></span><br>
password:<span th:text="${user.password}"></span><br>
</body>
</html>
运行 SpringBootDemoApplication.java,打开浏览器输入地址
http://localhost:8080/users/1
@ControllerPage.png
@RestController
TestRestController.java
@RestController
@RequestMapping("/api/users")
public class TestRestController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
User u = new User();
u.setId(id);
u.setUsername("admin");
u.setPassword("admin");
return u;
}
}
运行 SpringBootDemoApplication.java,打开浏览器输入地址
http://localhost:8080/api/users/1
TestRestController.png
自定义错误页面
默认错误页面,如下图
defaultErrorPage.png
如果想定义自己的访问错误页面,需要将错误页面放在 /error 文件夹中,错误页面可以是静态页面(放在 /static 中),也可以是一模版页面(放在 /template 中)
1. 作为静态页面
src/
+- main/
+- java/
+- <source code>
+- resources/
+- static/
+- error/
+- 404.html
+- <other static assets>
404.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>static 404 page</h1>
</body>
</html>
运行程序,输入一个错误url,比如 http://localhost:8080/test,看到如下图:
2. 作为模板错误页面
src/
+- main/
+- java/
+- <source code>
+- resources/
+- template/
+- error/
+- 404.html
+- <other templates>
404.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>template 404 page</h1>
</body>
</html>
运行程序,输入一个错误url,比如 http://localhost:8080/test,看到如下图:
上一篇:1. 用 IntelliJ IDEA 创建 Spring Boot 项目
下一篇:3. Spring Boot SQL Databases
网友评论