使用spring-boot制作一个成绩查询登录界面
时间: 2024-05-02 08:22:11 浏览: 8
首先,需要创建一个Spring Boot项目,并添加相关依赖。
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
创建一个Controller类,并添加一个RequestMapping,用于处理GET请求,返回登录页面。
```java
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
}
```
创建一个Thymeleaf模板文件,用于显示登录页面。
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>成绩查询登录</title>
</head>
<body>
<h1>成绩查询登录</h1>
<form method="post" th:action="@{/login}">
<label>用户名:</label>
<input type="text" name="username"/><br/>
<label>密码:</label>
<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
```
创建一个Service类,用于验证用户输入的用户名和密码是否正确。
```java
@Service
public class LoginService {
public boolean login(String username, String password) {
// 在这里进行验证,如果用户名和密码正确则返回true,否则返回false
return "admin".equals(username) && "123456".equals(password);
}
}
```
修改Controller类,添加一个RequestMapping,用于处理POST请求,验证用户输入的用户名和密码,并根据验证结果返回不同的页面。
```java
@Controller
public class LoginController {
@Autowired
private LoginService loginService;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String username, String password, Model model) {
boolean result = loginService.login(username, password);
if (result) {
// 如果验证通过,跳转到成绩查询页面
return "score";
} else {
// 如果验证失败,返回登录页面,并显示错误信息
model.addAttribute("error", "用户名或密码错误");
return "login";
}
}
}
```
创建一个Thymeleaf模板文件,用于显示成绩查询页面。
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>成绩查询</title>
</head>
<body>
<h1>成绩查询</h1>
<p>欢迎您,admin!</p>
<table>
<thead>
<tr>
<th>学生姓名</th>
<th>语文成绩</th>
<th>数学成绩</th>
<th>英语成绩</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>90</td>
<td>80</td>
<td>70</td>
</tr>
<tr>
<td>李四</td>
<td>80</td>
<td>90</td>
<td>70</td>
</tr>
<tr>
<td>王五</td>
<td>70</td>
<td>80</td>
<td>90</td>
</tr>
</tbody>
</table>
</body>
</html>
```
最后,运行Spring Boot应用程序,并访问http://localhost:8080/login,即可看到登录页面。输入正确的用户名和密码,即可跳转到成绩查询页面。输入错误的用户名和密码,会返回登录页面,并显示错误信息。