最近想要多学习一些权限管理的东西,以前用SpringSecurity,现在学一学Shiro。因为在网上查的资料都是写好的Demo,直接用可以但是不利与学习,我就自己参照网上的Shiro教程和SpringBoot集成Shiro的项目,一步步的自己搭建项目。
首先我们使用SpringBoot构建一个带简单登录功能Web应用。
pom.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> </parent> <dependencies> <!-- spring web 默认集成tomcat--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- thmleaf模板依赖. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.2</version> <scope>provided</scope> </dependency> </dependencies>
Application和Controller
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 @Controller 2 public class HomeController { 3 4 @RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET) 5 public String index() { 6 return "index"; 7 } 8 @RequestMapping(value = "/login", method = RequestMethod.GET) 9 public String loginGet(Model model) { 10 model.addAttribute("msg", "请登录"); 11 return "login"; 12 } 13 @RequestMapping(value = "/login", method = RequestMethod.POST) 14 public String loginPost(Model model, String username, String password) { 15 if ("admin".equals(username) && "123456".equals(password)) { 16 return "index"; 17 } else { 18 model.addAttribute("msg", "登录失败"); 19 return "login"; 20 } 21 } 22 @RequestMapping(value = "/logout", method = RequestMethod.GET) 23 public String logout() { 24 return "redirect:login"; 25 } 26 }
最后加上登录页面和登录成功页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!—index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>welcome</title> </head> <body> 欢迎登录网页 <a href="/logout">点击退出</a> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!—login.html--> <!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <h5 th:text="'提示消息:'+${msg}"></h5> <form action="login" method="post"> <p>账号:<input type="text" name="username"/></p> <p>密码:<input type="text" name="password"/></p> <p><input type="submit" value="登录"/></p> </form> </body> </html>
启动服务就可以测试登录效果了。
到这里Web环境就搭建好了,下一章将Shiro继承进去,替代现有的登录功能
GitHub地址:https://github.com/StarkTan/SpringBootShiro