聲明本文只適合初學者,本人也是剛接觸而已,經過一段時間的研究小有收獲,特來分享下希望和大家互相交流學習。
首先配置我們的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>
user == subject:用戶, group(role):角色
permission:權限(擁有權限比較細的情況,一般只要user和group就滿足要求了)
最后 提一下jar包,別弄錯了。是shiro-all.jar。可以從官網下載 http://shiro.apache.org/download.html
