一、沿用上一篇博客项目
二、实现前后端分离
2.1、在resource目录下创建templates目录
这一步是必要的,否则等下测试会报错
2.2、在templates下创建登录页面login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Shiro登录验证</h1>
<br>
<form action="/myController/userLogin">
<div>用户名:<input type="text" name="name" value=""></div>
<div>密码:<input type="password" name="pwd" value=""></div>
<div><input type="submit" value="登录"></div>
</form>
</body>
</html>
2.3、更改MyController类如下
package com.massimo.shiro.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("myController")
public class MyController {
@GetMapping("userLogin")
public String userLogin(String name, String pwd, HttpSession session){
//1.获取subject对象
Subject subject = SecurityUtils.getSubject();
//2.封装请求数据到token
AuthenticationToken token = new UsernamePasswordToken(name,pwd);
//3.调用login方法进行登录验证
try {
subject.login(token);
session.setAttribute("user",token.getPrincipal().toString());
return "main";
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("登陆失败");
return "登录失败";
}
}
// //跳转登录页面
@GetMapping("login")
public String login(){
return "login";
}
}
2.4、在ShiroConfig中配置为不认证可以访问的资源
2.5、在tempates下创建main登录成功页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Shiro登录认证后主页面</h1>
<br>
登录用户为:<span th:text="${session.user}"></span>
</body>
</html>
2.6、测试