最近想要多學習一些權限管理的東西,以前用SpringSecurity,現在學一學Shiro。因為在網上查的資料都是寫好的Demo,直接用可以但是不利與學習,我就自己參照網上的Shiro教程和SpringBoot集成Shiro的項目,一步步的自己搭建項目。
首先我們使用SpringBoot構建一個帶簡單登錄功能Web應用。
pom.xml

<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

@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

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 }
最后加上登錄頁面和登錄成功頁面

<!—index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>welcome</title> </head> <body> 歡迎登錄網頁 <a href="/logout">點擊退出</a> </body> </html>

<!—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