聲明本文只適合初學者,本人也是剛接觸而已,通過一段時間的研究小有收穫,特來分享下但願和你們互相交流學習。
首先配置咱們的web.xml代碼以下:
<filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
}
各部分代碼功能上面註釋已基本解釋了,我要說的是,咱們平時有可能比較喜歡使用currUser對象,可是貌似在這裏沒有辦法獲得了。其實否則,首先shiro給咱們提供的Subject的會話能夠知足咱們的需求
Session session = subject.getSession();
Session session = subject.getSession(boolean create);
這些方法在概念上等同於HttpServletRequest API。第一個方法會返 回Subject的現有會話,或者若是尚未會話,它會建立一個新的並將之返回。
第二個方法接受一個布爾參數,這個參數用於斷定會話不存在時是否建立新會話 。一旦得到Shiro的會話,你幾乎能夠像使用HttpSession同樣使用它。Shiro團 隊以爲對於Java開發者,HttpSession API用起來太舒服了,因此咱們保留了它 的不少感受。固然,最大的不一樣在於,你能夠在任何應用中使用Shiro會話,不 僅限於Web應用。 所以你能夠再驗證登錄裏寫這樣的一句話來完成咱們的代碼轉換 SecurityUtils.getSubject().getSession().setAttribute("currUser", user); 注意在異常處理裏須要移除此currUser。 固然官方推薦使用 Subject
最後就是咱們的Controller了。 在這裏我介紹登錄和退出
@RequestMapping("/user/login")
@RequestMapping("/user/exit")
好了,這樣基本算是完成任務了,接下來就是頁面上的操做了。爲此shiro還提供了相應的標籤,在這裏我就照搬官方的了,由於這個實在簡單,你們一看就明白
引用 <%@
驗證當前用戶是否爲「訪客」,即未認證(包含未記住)的用戶
- <shiro:guest>
-
Hi there! Please <a href="login.jsp">Login</a> or <ahref="signup.jsp">Signup</a> today! - </shiro:guest>
user標籤
認證經過或已記住的用戶
- <shiro:user>
-
Welcome back John! Not John? Click <a href="login.jsp">here<a> to login. - </shiro:user>
authenticated標籤
已認證經過的用戶。不包含已記住的用戶,這是與user標籤的區別所在。
- <shiro:authenticated>
-
<a href="updateAccount.jsp">Update your </a>.contact information - </shiro:authenticated>
notAuthenticated標籤
未認證經過用戶,與authenticated標籤相對應。與guest標籤的區別是,該標籤包含已記住用戶。
- <shiro:notAuthenticated>
-
Please <a href="login.jsp">login</a> in order to update your credit card information. - </shiro:notAuthenticated>
principal 標籤
輸出當前用戶信息,一般爲登陸賬號信息
- Hello,
<shiro:principal/>, how are you today?
hasRole標籤
驗證當前用戶是否屬於該角色
- <shiro:hasRole
name="administrator"> -
<a href="admin.jsp">Administer the </a>system - </shiro:hasRole>
lacksRole標籤
與hasRole標籤邏輯相反,當用戶不屬於該角色時驗證經過
- <shiro:lacksRole
name="administrator"> -
Sorry, you are not allowed to administer the system. - </shiro:lacksRole>
hasAnyRole標籤
驗證當前用戶是否屬於如下任意一個角色。
- <shiro:hasAnyRoles
name="developer, project >manager, administrator" -
You are either a developer, project manager, or administrator. - </shiro:lacksRole>
hasPermission標籤
驗證當前用戶是否擁有制定權限
- <shiro:hasPermission
name="user:create"> -
<a href="createUser.jsp">Create a </a>new User - </shiro:hasPermission>
lacksPermission標籤
與hasPermission標籤邏輯相反,當前用戶沒有制定權限時,驗證經過
Xml代碼
- <shiro:hasPermission
name="user:create"> -
<a href="createUser.jsp">Create a </a>new User - </shiro:hasPermission>
![shiro權限框架簡單快速入門 shiro權限框架簡單快速入門](http://static.javashuo.com/static/loading.gif)
user == subject:用戶, group(role):角色
permission:權限(擁有權限比較細的狀況,通常只要user和group就知足要求了)
最後 提一下jar包,別弄錯了。是shiro-all.jar。能夠從官網下載 http://shiro.apache.org/download.html