這部分,給大家介紹瞭如何配置配置文件,讓我們的security可用
第一步,添加spring-Security的命名空間
第二部分的時候介紹過.可參考Spring Security教程第二部分-工程裏添加spring-security
首先打開applicationContext.xml(也可以單獨寫security.xml),添加如下的這段代碼
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
注意xmlns:security="http://www.springframework.org/schema/security"
這句話就是把我們需要用的security的namespace設置爲security,可能有人會好奇,這些東西是從哪找的?
第一個方法就是百度
至於第二種就是取下載的官方文檔裏面找啊,比如,我們進去spring-security的包,會發現有個samples,如下圖所示
然後進入samples,隨便選擇一個XXXX-xml文件夾,然後打開,我這裏打開的地址是
D:\soft\lib\spring-security-3.2.9.RELEASE\samples\spring-security-samples-openid-xml\src\main\webapp\WEB-INF
會發現有兩個xml文件,這就是我們需要配置的啦,如下圖所示
打開applicationContext-security.xml
是不是就能找到啦,這方法真是百玩不膩啊,相信我,後面有很多文件的配置需要到這裏或者官方文檔去找的,自己度娘出來是絕對靠不住的,,.
第二步,web.xml配置監聽器
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<!-- 攔截所有的請求 -->
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
別問我爲啥這樣配,,,,我也不知道,反正就是這樣第三步,applictaion.xml進一步配置
在這個文件中先添加
<security:http auto-config="true">
<security:intercept-url pattern="/**" access="ROLE_USER" />
</security:http>
這句話表明對於任意的資源,只能允許用戶爲ROLE_USER訪問
此外,auto-config="true"是因爲其實security在初始化的時候有很多步驟.....自己配很麻煩,尤其是還要卸載xml文件中
因此這個設置就省去了我們自己配的過程,一般也不需要我們自己配
對了,需要強調的是,security對用戶身份的管理,必須要以ROLE_開頭,這是規定
接下來,我們把用戶配在哪呢?因爲在這節中我還沒有使用數據庫,所以就存在配置文件裏面啦
配置如下
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="wulalala" password="123456" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
這個配置就是配置了用戶名爲wulalala,密碼爲123456,用戶角色爲ROLE_USER的用戶,如果有多條用戶繼續在裏面添加即可
創建首頁,index.jsp頁面,運行工程,發現出現了登錄頁面,如下圖所示
輸入賬號密碼,點擊login即可正常登錄到首頁,
到這裏security基本配通了
可能有的人會好奇,這個登錄頁面是從哪裏來的?這裏推薦大家去看以爲博主的博客,裏面很好的介紹了一些spring security的源碼分析