java筆記:SpringSecurity應用(一)

來源:互聯網
上載者:User

  今天領導要了我們前端組從十月到年末的開發計劃,發現年底的項目終於迴歸到了javascript做前端了,到時好好練練手。另外,發現以後可能會經常做許可權管理,所以現在正好有點時間打算把SpringSecurity資料認真整理下,今天是入門級的,希望以後會越來越來越深入。

  java項目首先要提的就是jar包了,Springsecurity的jar:http://static.springsource.org/spring-security/site/downloads.html。不過我的項目裡的jar包比較舊點了,是從以前項目抽取出來的,我的工程結構圖如下:

第一個執行個體:

第一個例子是最基本,最簡單的,我第一次接觸springsecurity時候覺得這個技術真驚豔,不過現在感覺也就那麼回事了。

我首先編寫的是web.xml:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>SpringSecurityPrj</display-name>  <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>  classpath:applicationContext*.xml  </param-value>  </context-param>  <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>  <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

接下來編寫的是applicationContext-security.xml檔案:

<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-3.0.xsd"><!-- 自動設定模式,攔截所有請求,有ROLE_USER才可以通過 --><http auto-config="true"><intercept-url pattern="/**" access="ROLE_USER"/></http><!-- 認證管理器。使用者名稱密碼都整合在設定檔中 --> <authentication-manager><authentication-provider><user-service><user name="sharp" password="sharp" authorities="ROLE_USER"/></user-service></authentication-provider></authentication-manager></beans:beans>

另外我建立了一個index.jsp檔案,作用是登入成功後返回到index.jsp頁面:

 

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>登入首頁</title></head><body><span color="red">登入成功!</span></body></html>

當我們在瀏覽器地址欄裡輸入下面的url:

http://localhost:8080/SpringSecurityPrj/

我們就可以再瀏覽器裡看到使用者登入介面:

 呵呵,內建的登入頁面,挺好玩的。沒有使用過springsecurity可能還沒發現我在那裡配置使用者名稱和密碼吧,看下面一段代碼,這裡就是使用者名稱和密碼:

<user name="sharp" password="sharp" authorities="ROLE_USER"/>

測試一:

我們錄入使用者名稱:admin;密碼:admin,然後點擊提交查詢,最終頁面如下:

登入失敗了哦!

測試二:我們錄入使用者名稱:sharp;密碼:sharp;如:

點擊提交查詢後,頁面如下:

 

頁面跳轉到index.jsp頁面,登入成功了。

哈哈,用這個做登入是不是很easy啊!

(博主溫馨提示:我開始做測試是使用myeclipse,所有操作都沒問題,然後改用eclipse-java EE,每次啟動tomcat,eclipse都報了Server Tomcat v6.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor錯誤,啟動了45秒後tomcat自動停止,我在百度查原因,找到了一個解決方案,解決方案如下:

Server Tomcat v6.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.修改 workspace\.metadata\.plugins\org.eclipse.wst.server.core\servers.xml檔案。<servers><server hostname="localhost" id="JBoss v5.0 at localhost" name="JBoss v5.0 atlocalhost" runtime-id="JBoss v5.0" server-type="org.eclipse.jst.server.generic.jboss5"server-type-id="org.eclipse.jst.server.generic.jboss5" start-timeout="1000" stop-timeout="15" timestamp="0"><map jndiPort="1099" key="generic_server_instance_properties" port="8090"serverAddress="127.0.0.1" serverConfig="default"/></server></servers>把 start-timeout="45" 改為 start-timeout="1000" 或者更長重啟eclipse就可以了。這個原因就是:啟動tomcat需要的時間比45秒大了,Eclipse會判斷tomcat在預設的時間是否啟動了,如果在預設45秒沒有啟動就會報錯了。

在第一個執行個體基礎上我做了第二個執行個體。

第二個執行個體:

 第一個例子裡的登入頁面是springsecurity的預設頁面,這種死板的頁面滿足不了千變萬化的使用者需求,因此這個執行個體裡我將自訂登入介面,這裡我們還要加入幾個jar包,最新的lib包下的目錄如下所示:

 

建立一個login.jsp頁面代碼如下:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>使用者登入</title></head><body onLoad="document.f.j_username.focus();"><c:if test="${not empty param.login_error}"><font color="red">登入失敗,請重試.<br/><br/>原因:<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/></font></c:if><form name="f" action="<c:url value='j_spring_security_check'/>" method="POST"><table><tr><td>使用者名稱:</td><td><input type='text' name='j_username' value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>'/></td></tr><tr><td>密     碼:</td><td><input type='password' name='j_password'></td></tr><tr><td><input type="checkbox" name="_spring_security_remember_me"></td><td>兩周內自動登入</td></tr><tr><td colspan='2' align="center"><input name="submit" type="submit">  <input name="reset" type="reset"></td></tr></table></form></body></html>

修改applicationContext-security.xml設定檔:

<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-3.0.xsd"><!-- 自動設定模式,攔截所有請求,有ROLE_USER才可以通過 --><http auto-config="true"><intercept-url pattern="/login.jsp*"  access="IS_AUTHENTICATED_ANONYMOUSLY" /><intercept-url pattern="/**" access="ROLE_USER"/><form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1"/> </http><!-- 認證管理器。使用者名稱密碼都整合在設定檔中 --> <authentication-manager><authentication-provider><user-service><user name="sharp" password="sharp" authorities="ROLE_USER"/></user-service></authentication-provider></authentication-manager><!-- 指定中文資源 。預設命名空間是security,所以要加首碼beans: -->      <beans:bean id="messageSource"      class="org.springframework.context.support.ReloadableResourceBundleMessageSource">     <beans:property name="basename"  value="classpath:org/springframework/security/messages_zh_CN"/>       </beans:bean></beans:beans>

我們在瀏覽器地址欄裡輸入下面的url,點擊斷行符號,介面如下:

 

測試一:

我們錄入使用者名稱:admin;密碼:admin,然後點擊提交查詢,最終頁面如下:

登入失敗!

測試二:我們錄入使用者名稱:sharp;密碼:sharp;如:

點擊提交查詢,結果如下:

 

第三個執行個體:

只要是接觸過許可權管理的程式員都知道,一般的許可權管理都有角色的概念,但是傳統的角色都是在資料庫建模,然後用編程的方式來實現的。在springsecurity裡面就有角色的概念,用起來也很方便,上面的例子裡我們使用了一個角色ROLE_USER,現在我們添加一個角色ROLE_ADMIN,我們修改applicationContext-security.xml設定檔:

<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-3.0.xsd"><!-- 自動設定模式,攔截所有請求,有ROLE_USER才可以通過 --><http auto-config="true"><intercept-url pattern="/login.jsp*"  access="IS_AUTHENTICATED_ANONYMOUSLY" /><!-- 增加 ROLE_ADMIN角色--><intercept-url pattern="/admin.jsp" access="ROLE_ADMIN"/><intercept-url pattern="/**" access="ROLE_USER"/><form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1"/> </http><!-- 認證管理器。使用者名稱密碼都整合在設定檔中 --> <authentication-manager><authentication-provider><user-service><!-- 添加ROLE_ADMIN角色 --><user name="admin" password="admin" authorities="ROLE_USER,ROLE_ADMIN"/><user name="sharp" password="sharp" authorities="ROLE_USER"/></user-service></authentication-provider></authentication-manager><!-- 指定中文資源 。預設命名空間是security,所以要加首碼beans: -->      <beans:bean id="messageSource"      class="org.springframework.context.support.ReloadableResourceBundleMessageSource">     <beans:property name="basename"  value="classpath:org/springframework/security/messages_zh_CN"/>       </beans:bean></beans:beans>

另外我建立一個admin.jsp頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Admin 管理介面</title></head><body><p style="color:red">admin.jsp頁面</p></body></html>

修改下index.jsp頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>登入首頁</title></head><body><span color="red">登入成功!</span><br/><a href="admin.jsp">admin.jsp</a></body></html>

 測試一:

我們輸入的使用者名稱:sharp;密碼:sharp,登入成功了,我們進入到了頁面index.jsp:

 

點擊admin.jsp連結,結果如下:

 

sharp使用者沒有ROLE_ADMIN角色的許可權,所以sharp訪問不了admin.jsp頁面。

測試二:

我們輸入的使用者名稱:admin;密碼:admin,登入成功了,我們進入到了頁面index.jsp(如),

然後 

點擊admin.jsp連結,結果如下:

 

 使用者admin是可以訪問admin.jsp頁面。

好了,今天學習結束了!

總結下:今天都是具體操作,而且這些操作在網上多的不得了,不過我想學springsecurity都得從這一步開始,現在我對springsecurity理解還不深,整篇文章都是如何去編碼,而沒有一些知識的講解,我會盡全力一步步深入,做軟體最好還是知其所以然,明天看能不能研究原理,下一篇由springsecurity和資料庫的結合開始。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.