赞
踩
这一步是必要的,否则等下测试会报错
<!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>
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"; } }
<!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>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。