登录HTML文件如下
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>登录博客后台</title>
<meta http-equiv="Cache-Control" content="no-siteapp"/>
<link rel="shortcut icon" th:href="@{/user/img/bloglogo.jpg}"/>
<script th:src="@{/assets/js/jquery.min.js}"></script>
<script th:src="@{/assets/js/amazeui.min.js}"></script>
<link rel="stylesheet" th:href="@{/assets/css/amazeui.min.css}"/>
<link rel="stylesheet" th:href="@{/assets/css/app.css}"/>
</head>
<body>
<div class="log">
<div class="am-g">
<div class="am-u-lg-3 am-u-md-6 am-u-sm-8 am-u-sm-centered log-content">
<h1 class="log-title am-animation-slide-top" style="color: black;" th:text="#{login.welcomeTitle}">~欢迎登录博客~</h1>
<br>
<div th:if="${param.error}" style="color: red" th:text="#{login.error}">用户名或密码错误!</div>
<form class="am-form" id="loginForm" th:action="@{/login}" method="post">
<div>
<input type="hidden" name="url" th:value="${url}">
</div>
<div class="am-input-group am-radius am-animation-slide-left">
<input type="text" class="am-radius" th:placeholder="#{login.username}" name="username" />
<span class="am-input-group-label log-icon am-radius">
<i class="am-icon-user am-icon-sm am-icon-fw"></i>
</span>
</div>
<br>
<div class="am-input-group am-animation-slide-left log-animation-delay">
<input type="password" class="am-form-field am-radius log-input" th:placeholder="#{login.password}" name="password" />
<span class="am-input-group-label log-icon am-radius">
<i class="am-icon-lock am-icon-sm am-icon-fw"></i>
</span>
</div>
<label>
<input type="checkbox" name="rememberme"> <font color="#6495ed" >记住我
</label>
<div style="padding-top: 10px;">
<input type="submit" th:value="#{login.sub}"
class="am-btn am-btn-primary am-btn-block am-btn-lg am-radius am-animation-slide-bottom log-animation-delay" />
</div>
<a style="color: #0099CC;" th:href="@{/toRegister}"><p>注册</p></a >
</form>
</div>
</div>
<footer class="log-footer">
<p style="margin: 30px; color: #2E2D3C"><time class="comment-time" th:text="${#dates.format(new java.util.Date().getTime(), 'yyyy')}"></time> © Powered By <a style="color: #0e90d2" rel="nofollow">CrazyStone</a></p>
</footer>
</div>
</body>
</html>
Java代码模样:
@Controller
public class LoginController {
@Autowired
private CustomerService customerService;
// 向登录页面跳转,同时封装原始页面地址
@GetMapping(value = "/login")
public String login(HttpServletRequest request, Map map) {
// 分别获取请求头和参数url中的原始访问路径
String referer = request.getHeader("Referer");
String url = request.getParameter("url");
System.out.println("referer= " + referer);
System.out.println("url= " + url);
// 如果参数url中已经封装了原始页面路径,直接返回该路径
if (url != null && !url.equals("")) {
map.put("url", url);
// 如果请求头本身包含登录,将重定向url设为空,让后台通过用户角色进行选择跳转
} else if (referer != null && referer.contains("/login")) {
map.put("url", "");
} else {
// 否则的话,就记住请求头中的原始访问路径
map.put("url", referer);
}
return "comm/login";
}
// 对Security拦截的无权限访问异常处理路径映射
@GetMapping(value = "/errorPage/{page}/{code}")
public String AccessExecptionHandler(@PathVariable("page") String page,
@PathVariable("code") String code) {
return page + "/" + code;
}
//向用户修改页
@RequestMapping("/toupdateUser")//这里使用 @GetMapping会报错因为 @GetMapping是GET类型不是POST
public String toupdateuser() {
return "/csrf/csrfTest";
}
@RequestMapping("/quit")//这里使用 @GetMapping会报错因为 @GetMapping是GET类型不是POST
public String quit() {
return "/csrf/csrf";
}
//用户修改提交处理
@ResponseBody
@PostMapping(value = "/updateUser")
//通过RedirectView返回一个重定向的URL
public RedirectView updateUser(@RequestParam String username, HttpServletRequest request) {
// 获取应用上下文
SecurityContext context = SecurityContextHolder.getContext();
// 获取用户相关信息
Authentication authentication = context.getAuthentication();
UserDetails principal = (UserDetails) authentication.getPrincipal();
// 创建一个名为"customer"的对象
Customer customer = new Customer();
// 通过用户的用户名(principal.getUsername())查找用户信息并存储在"customer"对象中
customer = customerService.findById(principal.getUsername());
// 打印用户信息
System.out.println(customer);
// 更新用户的用户名
customer.setUsername(username);
// 打印已更新的用户名
System.out.println(customer.getUsername());
// 调用customerService的updateUser方法,将用户的新用户名和用户ID传递给它
customerService.updateUser(customer.getUsername(), customer.getId());
// 获取CSRF令牌并打印
String csrf_token = request.getParameter("_csrf");
System.out.println(csrf_token);
// 重定向到"/quit"页面
return new RedirectView("/quit", true);
}
// 新用户注册
@GetMapping("/toRegister") // http://localhost/toRegister
public String showRegisterForm(Model model) {
model.addAttribute("user", new Customer());
return "client/registerUser";
}
// 用户注册提交处理
@PostMapping(value = "/registerUser")
public String registerUser(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("email") String email) {
// 创建新用户
Customer user = new Customer();
user.setUsername(username);
user.setPassword(password);
user.setPassword(bCryptPasswordEncoder.encode(password)); // 对密码进行加密
user.setEmail(email);
if (isUsernameExist(username)) {
return "csrf/user_errol";
} else {
userMapper.insertUser(user);
// 获取新插入的用户ID
Integer userId = userMapper.getNewUserId();
// 插入用户权限关联信息到t_user_authority表
UserAuthority userAuthority =new UserAuthority();
userAuthority.setUserId(userId);
userAuthority.setAuthorityId(2);
userAuthorityMapper.insertUser(userAuthority);
return "csrf/user_finish";
}
}
// 判断username是否存在
public boolean isUsernameExist(String username) {
List<Customer> users = userMapper.findByUsername(username);
return !users.isEmpty();
}
//注销
@Controller
public class UserController {
@RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
public String deleteUser() {
return "client/user_delete_confirmation";
}
@RequestMapping(value = "/confirmDelete", method = RequestMethod.POST)
public String confirmDelete() {
// 获取当前登录用户
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// 查询当前用户名id
int userId = userMapper.getNewUserId();
userMapper.deleteUser(userId);
userAuthorityMapper.deleteUserAuthority(userId);
// 清除认证信息
Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
if (authentication1 != null) {
SecurityContextHolder.getContext().setAuthentication(null);
}
return "client/user_delete_finish";
}
}
}