优化代码,我想根据结果完成页面跳转@GetMapping("/login") public String showUserLoginForm(@RequestParam String username, @RequestParam String password) { boolean flag = userService.login(username,password); if(flag){ return "query.html"; }else { return "404.html"; } }
时间: 2024-01-18 10:03:02 浏览: 24
好的,根据您的需求,我们可以对代码进行如下优化:
1. 在前端页面中,将输入框和按钮放在一个表单中,并设置表单的提交地址为后端的登录接口。
2. 后端接口返回的结果中,如果登录成功,则将重定向到查询页面;如果登录失败,则将重定向到404页面。
下面是优化后的示例代码:
前端页面(login.html):
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="/login" method="post">
<label>用户名:</label>
<input type="text" name="username">
<br>
<label>密码:</label>
<input type="password" name="password">
<br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
后端控制器:
```java
@Controller
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, RedirectAttributes attributes) {
boolean flag = userService.login(username, password);
if (flag) {
// 登录成功,重定向到查询页面
return "redirect:/query";
} else {
// 登录失败,重定向到404页面
attributes.addFlashAttribute("errorMsg", "用户名或密码错误");
return "redirect:/404";
}
}
@GetMapping("/query")
public String showQueryPage() {
return "query.html";
}
@GetMapping("/404")
public String showNotFoundPage(Model model) {
String errorMsg = (String) model.asMap().get("errorMsg");
model.addAttribute("errorMsg", errorMsg);
return "404.html";
}
}
```
在这个示例中,我们将登录请求的提交地址设置为 `/login`,并将用户名和密码作为请求参数提交到后端控制器中。后端控制器中的 `login()` 方法会根据用户名和密码验证用户身份,并返回相应的结果。如果登录成功,则使用重定向跳转到查询页面;如果登录失败,则使用重定向跳转到404页面,并将错误信息通过 `RedirectAttributes` 对象传递到下一个请求中。
注意,在重定向跳转时,我们使用了 `redirect:` 前缀来指定跳转地址。同时,为了在404页面中显示错误信息,我们使用了 `RedirectAttributes` 对象来传递数据。在404页面中,我们使用了 `Model` 对象来获取错误信息,然后将其传递到页面中进行显示。