Spring Security2.0的自带DEMO浅析

下载地址:http://www.springsource.org/download

如下图所示建立工程:

所需Jar包:

aopalliance-1.0.jar
aspectjrt-1.5.4.jar
aspectjweaver.jar
commons-codec-1.3.jar
commons-collections-3.2.jar
commons-logging-1.1.1.jar
jstl-1.1.2.jar
log4j-1.2.14.jar
spring-aop-2.0.8.jar
spring-beans-2.0.8.jar
spring-context-2.0.8.jar
spring-core-2.0.8.jar
spring-dao-2.0.8.jar
spring-jdbc-2.0.8.jar
spring-security-acl-2.0.4.jar
spring-security-core-2.0.4.jar
spring-security-core-tiger-2.0.4.jar
spring-security-taglibs-2.0.4.jar
spring-support-2.0.8.jar
spring-web-2.0.8.jar
spring-webmvc-2.0.8.jar
standard-1.1.2.jar

代码如下:

ListAccounts.java

  1. package bigbank.web;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.util.Assert;
  5. import org.springframework.web.servlet.ModelAndView;
  6. import org.springframework.web.servlet.mvc.Controller;
  7. import bigbank.BankService;
  8. public class ListAccounts implements Controller {
  9.     private BankService bankService;
  10.     public ListAccounts(BankService bankService) {
  11.         Assert.notNull(bankService);
  12.         this.bankService = bankService;
  13.     }
  14.     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
  15.         ModelAndView mav = new ModelAndView("listAccounts");
  16.         mav.addObject("accounts", bankService.findAccounts());
  17.         return mav;
  18.     }
  19. }

PostAccounts.java

  1. package bigbank.web;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.util.Assert;
  5. import org.springframework.web.bind.ServletRequestUtils;
  6. import org.springframework.web.servlet.ModelAndView;
  7. import org.springframework.web.servlet.mvc.Controller;
  8. import bigbank.Account;
  9. import bigbank.BankService;
  10. public class PostAccounts implements Controller {
  11.     private BankService bankService;
  12.     public PostAccounts(BankService bankService) {
  13.         Assert.notNull(bankService);
  14.         this.bankService = bankService;
  15.     }
  16.     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
  17.         Long id = ServletRequestUtils.getRequiredLongParameter(request, "id");
  18.         Double amount = ServletRequestUtils.getRequiredDoubleParameter(request, "amount");
  19.         Account a = bankService.readAccount(id);
  20.         bankService.post(a, amount);
  21.         return new ModelAndView("redirect:listAccounts.html");
  22.     }
  23. }

Account.java

  1. package bigbank;
  2. public class Account {
  3.     private long id = -1;
  4.     private String holder;
  5.     private double balance;
  6.     public Account(String holder) {
  7.         super();
  8.         this.holder = holder;
  9.     }
  10.     public long getId() {
  11.         return id;
  12.     }
  13.     public void setId(long id) {
  14.         this.id = id;
  15.     }
  16.     public String getHolder() {
  17.         return holder;
  18.     }
  19.     public void setHolder(String holder) {
  20.         this.holder = holder;
  21.     }
  22.     public double getBalance() {
  23.         return balance;
  24.     }
  25.     public void setBalance(double balance) {
  26.         this.balance = balance;
  27.     }
  28.     public String toString() {
  29.         return "Account[id=" + id + ",balance=" + balance +",holder=" + holder + "]";
  30.     }
  31. }
BankDao.java
  1. package bigbank;
  2. public interface BankDao {
  3.     public Account readAccount(Long id);
  4.     public void createOrUpdateAccount(Account account);
  5.     public Account[] findAccounts();
  6. }

BankDaoStub.java

  1. package bigbank;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class BankDaoStub implements BankDao {
  5.     
  6.     private long id = 0;
  7.     private Map<Long, Account> accounts = new HashMap<Long, Account>();
  8.     
  9.     public void createOrUpdateAccount(Account account) {
  10.         if (account.getId() == -1) {
  11.             id++;
  12.             account.setId(id);
  13.         }
  14.         accounts.put(new Long(account.getId()), account);
  15.         System.out.println("SAVE: " + account);
  16.     }
  17.     public Account[] findAccounts() {
  18.         Account[] a = (Account[]) accounts.values().toArray(new Account[] {});
  19.         System.out.println("Returning " + a.length + " account(s):");
  20.         for (int i = 0; i < a.length; i++) {
  21.             System.out.println(" > " + a[i]);
  22.         }
  23.         return a;
  24.     }
  25.     public Account readAccount(Long id) {
  26.         return (Account) accounts.get(id);
  27.     }
  28. }

BankService.java

  1. package bigbank;
  2. import org.springframework.security.annotation.Secured;
  3. public interface BankService {
  4.     
  5.     @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  6.     public Account readAccount(Long id);
  7.         
  8.     @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  9.     public Account[] findAccounts();
  10.     
  11.     @Secured("ROLE_TELLER")
  12.     public Account post(Account account, double amount);
  13. }

BankServiceImpl.java

  1. package bigbank;
  2. import org.aspectj.lang.annotation.Pointcut;
  3. import org.springframework.util.Assert;
  4. public class BankServiceImpl implements BankService {
  5.     
  6.     private BankDao bankDao;
  7.     // Not used unless you declare a <protect-pointcut>
  8.     @Pointcut("execution(* bigbank.BankServiceImpl.*(..))")
  9.     public void myPointcut() {}
  10.     public BankServiceImpl(BankDao bankDao) {
  11.         Assert.notNull(bankDao);
  12.         this.bankDao = bankDao;
  13.     }
  14.     public Account[] findAccounts() {
  15.         return this.bankDao.findAccounts();
  16.     }
  17.     public Account post(Account account, double amount) {
  18.         Assert.notNull(account);
  19.         Assert.notNull(account.getId());
  20.         
  21.         // We read account bank from DAO so it reflects the latest balance
  22.         Account a = bankDao.readAccount(account.getId());
  23.         if (account == null) {
  24.             throw new IllegalArgumentException("Couldn't find requested account");
  25.         }
  26.         
  27.         a.setBalance(a.getBalance() + amount);
  28.         bankDao.createOrUpdateAccount(a);
  29.         return a;
  30.     }
  31.     public Account readAccount(Long id) {
  32.         return bankDao.readAccount(id);
  33.     }
  34. }

SeedData.java

  1. package bigbank;
  2. import org.springframework.beans.factory.InitializingBean;
  3. import org.springframework.util.Assert;
  4. public class SeedData implements InitializingBean {
  5.     
  6.     private BankDao bankDao;
  7.     public void afterPropertiesSet() throws Exception {
  8.         
  9.         Assert.notNull(bankDao);
  10.         bankDao.createOrUpdateAccount(new Account("rod"));
  11.         bankDao.createOrUpdateAccount(new Account("dianne"));
  12.         bankDao.createOrUpdateAccount(new Account("scott"));
  13.         bankDao.createOrUpdateAccount(new Account("peter"));
  14.     }
  15.     
  16.     public void setBankDao(BankDao bankDao) {
  17.         this.bankDao = bankDao;
  18.     }
  19. }

applicationContext-business.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:security="http://www.springframework.org/schema/security"
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  6. http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd">
  7.     <bean id="bankDao" class="bigbank.BankDaoStub" />
  8.     <bean id="seedData" class="bigbank.SeedData">
  9.         <property name="bankDao" ref="bankDao" />
  10.     </bean>
  11.     <bean id="bankService" class="bigbank.BankServiceImpl">
  12.         <constructor-arg ref="bankDao" />
  13.         <security:intercept-methods>
  14.             <security:protect method="bigbank.BankService.*" access="IS_AUTHENTICATED_REMEMBERED" />
  15.             <security:protect method="bigbank.BankService.post" access="ROLE_TELLER" />
  16.         </security:intercept-methods>
  17.     </bean>
  18. </beans>

log4j.properties

  1. # Global logging configuration
  2. log4j.rootLogger=WARN, stdout, fileout
  3. log4j.logger.org.springframework.security=DEBUG, stdout, fileout
  4. # Console output...
  5. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  6. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  7. log4j.appender.stdout.layout.conversionPattern=[%p,%c{1},%t] %m%n
  8. # Rolling log file output...
  9. log4j.appender.fileout=org.apache.log4j.RollingFileAppender
  10. log4j.appender.fileout.File=spring-security-tutorial.log
  11. #log4j.appender.fileout.File=${webapp.root}/WEB-INF/log4j.log
  12. log4j.appender.fileout.MaxFileSize=1024KB
  13. log4j.appender.fileout.MaxBackupIndex=1
  14. log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
  15. log4j.appender.fileout.layout.conversionPattern=%d{ABSOLUTE} %5p %c{1},%t:%L - %m%n

/secure/extreme/index.jsp

  1. <%@ taglib prefix="authz" uri="http://www.springframework.org/security/tags"%>
  2. <html>
  3.     <body>
  4.         <h1>VERY Secure Page</h1>
  5.         This is a protected page. You can only see me if you are a supervisor.
  6.         <authz:authorize ifAllGranted="ROLE_SUPERVISOR">
  7.             You have "ROLE_SUPERVISOR" (this text is surrounded by <authz:authorize> tags).
  8.         </authz:authorize>
  9.         <p>
  10.         <a href="../../">Home</a>
  11.         <p>
  12.         <a href="../../j_spring_security_logout">Logout</a>
  13.     </body>
  14. </html>

/secure/index.jsp

  1. <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
  2. <html>
  3.     <body>
  4.         <h1>Secure Page</h1>
  5.         <p>
  6.             This is a protected page. You can get to me if you've been
  7.             remembered, or if you've authenticated this session.
  8.         </p>
  9.         <sec:authorize ifAllGranted="ROLE_SUPERVISOR">
  10.             You are a supervisor! You can therefore see the 
  11.             <a href="extreme/index.jsp">extremely secure page</a>.<br />
  12.             <br />
  13.         </sec:authorize>
  14.         <h3>Properties obtained using <sec:authentication /> tag</h3>
  15.         <table border="1">
  16.             <tr>
  17.                 <th>Tag</th>
  18.                 <th>Value</th>
  19.             </tr>
  20.             <tr>
  21.                 <td><sec:authentication property='name' /></td>
  22.                 <td><sec:authentication property="name" /></td>
  23.             </tr>
  24.             <tr>
  25.                 <td><sec:authentication property='principal.username' /></td>
  26.                 <td><sec:authentication property="principal.username" /></td>
  27.             </tr>
  28.             <tr>
  29.                 <td><sec:authentication property='principal.enabled' /></td>
  30.                 <td><sec:authentication property="principal.enabled" /></td>
  31.             </tr>
  32.             <tr>
  33.                 <td><sec:authentication property='principal.accountNonLocked' /></td>
  34.                 <td><sec:authentication property="principal.accountNonLocked" /></td>
  35.             </tr>
  36.         </table>
  37.         <p>
  38.         <a href="../">Home</a>
  39.         <p>
  40.         <a href="../j_spring_security_logout">Logout</a>
  41.     </body>
  42. </html>

listAccounts.jsp

  1. <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
  2. <h1>
  3.     Accounts
  4. </h1>
  5. <a href="index.jsp">Home3</a>
  6. <br>
  7. <br>
  8. <table>
  9.     <c:forEach var="account" items="${accounts}">
  10.         <tr>
  11.             <td>
  12.                 <c:out value="${account.id}" />
  13.             </td>
  14.             <td>
  15.                 <c:out value="${account.holder}" />
  16.             </td>
  17.             <td>
  18.                 <c:out value="${account.balance}" />
  19.             </td>
  20.             <td>
  21.                 <a href="post.html?id=<c:out value="${account.id}"/>amount=-20.00">-$20</a>
  22.                 <a href="post.html?id=<c:out value="${account.id}"/>amount=-5.00">-$5</a>
  23.                 <a href="post.html?id=<c:out value="${account.id}"/>amount=5.00">+$5</a>
  24.                 <a href="post.html?id=<c:out value="${account.id}"/>amount=20.00">+$20</a>
  25.             </td>
  26.         </tr>
  27.     </c:forEach>
  28. </table>

applicationContext-security.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/security"
  3.     xmlns:beans="http://www.springframework.org/schema/beans"
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  6.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">
  7.     <global-method-security secured-annotations="enabled">
  8.         <protect-pointcut expression="execution(* bigbank.*Service.post*(..))" access="ROLE_TELLER"/>
  9.     </global-method-security>
  10.     
  11.     <http auto-config="true">
  12.         <intercept-url pattern="/secure/extreme/**" access="ROLE_SUPERVISOR"/>
  13.         <intercept-url pattern="/secure/**" access="IS_AUTHENTICATED_REMEMBERED" />
  14.         <!-- Disable web URI authorization, as we're using <global-method-security> and have @Secured the services layer instead
  15.             <intercept-url pattern="/listAccounts.html" access="IS_AUTHENTICATED_REMEMBERED" />
  16.             <intercept-url pattern="/post.html" access="ROLE_TELLER" />
  17.         -->
  18.         <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />   
  19.     </http>
  20.     <!--
  21.     Usernames/Passwords are
  22.         rod/koala
  23.         dianne/emu
  24.         scott/wombat
  25.         peter/opal
  26.     -->
  27.     <authentication-provider>
  28.         <password-encoder hash="md5"/>
  29.         <user-service>
  30.             <user name="rod" password="a564de63c2d0da68cf47586ee05984d7" authorities="ROLE_SUPERVISOR, ROLE_USER, ROLE_TELLER" />
  31.             <user name="dianne" password="65d15fe9156f9c4bbffd98085992a44e" authorities="ROLE_USER,ROLE_TELLER" />
  32.             <user name="scott" password="2b58af6dddbd072ed27ffc86725d7d3a" authorities="ROLE_USER" />
  33.             <user name="peter" password="22b5c9accc6e1ba628cedc63a72d57f8" authorities="ROLE_USER" />
  34.         </user-service>
  35.     </authentication-provider>
  36. </beans:beans>

bank-servlet.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  5.     <bean name="/listAccounts.html" class="bigbank.web.ListAccounts">
  6.         <constructor-arg ref="bankService"/>
  7.     </bean>
  8.     
  9.     <bean name="/post.html" class="bigbank.web.PostAccounts">
  10.         <constructor-arg ref="bankService"/>
  11.     </bean>
  12.     
  13.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  14.         <property name="prefix" value="/WEB-INF/jsp/"/>
  15.         <property name="suffix" value=".jsp"/>
  16.     </bean>
  17. </beans>

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
  5.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  6. <display-name>Spring Security Tutorial Application</display-name>
  7.     <context-param>
  8.         <param-name>contextConfigLocation</param-name>
  9.         <param-value>
  10.             classpath:applicationContext-business.xml
  11.             /WEB-INF/applicationContext-security.xml
  12.         </param-value>
  13.     </context-param>
  14.     
  15.     <context-param>
  16.         <param-name>log4jConfigLocation</param-name>
  17.         <param-value>/WEB-INF/classes/log4j.properties</param-value>
  18.     </context-param>    
  19.     <filter>
  20.         <filter-name>springSecurityFilterChain</filter-name>
  21.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  22.     </filter>
  23.     <filter-mapping>
  24.       <filter-name>springSecurityFilterChain</filter-name>
  25.       <url-pattern>/*</url-pattern>
  26.     </filter-mapping>
  27.     <listener>
  28.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  29.     </listener>
  30.     <listener>
  31.       <listener-class>org.springframework.security.ui.session.HttpSessionEventPublisher</listener-class>
  32.     </listener>
  33.     
  34.     <listener>
  35.         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  36.     </listener>    
  37.     <servlet>
  38.         <servlet-name>bank</servlet-name>
  39.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  40.         <load-on-startup>1</load-on-startup>
  41.     </servlet>
  42.     <servlet-mapping>
  43.         <servlet-name>bank</servlet-name>
  44.         <url-pattern>*.html</url-pattern>
  45.     </servlet-mapping>
  46.      <welcome-file-list>
  47.         <welcome-file>index.jsp</welcome-file>
  48.     </welcome-file-list>
  49. </web-app>

index.jsp

  1. <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
  2. <html>
  3.     <body>
  4.         <h1>Home Page</h1>
  5.         <p>Anyone can view this page.</p>
  6.         <p>
  7.             If you're logged in, you can
  8.             <a href="listAccounts.html">list accounts</a>.
  9.         </p>
  10.         <p>
  11.             Your principal object is....:
  12.             <%=request.getUserPrincipal()%>
  13.         </p>
  14.         <p><a href="secure/index.jsp">Secure page</a></p>
  15.         <p><a href="secure/extreme/index.jsp">Extremely secure page</a></p>
  16.     </body>
  17. </html>

login.jsp

  1. <%@ taglib prefix='c' uri='http://java.sun.com/jstl/core_rt'%>
  2. <html>
  3.     <head>
  4.         <title>CUSTOM SPRING SECURITY LOGIN</title>
  5.     </head>
  6.     <body onload="document.f.j_username.focus();">
  7.         <h1>
  8.             CUSTOM SPRING SECURITY LOGIN
  9.         </h1>
  10.         <P>
  11.             Valid users:
  12.         <P>
  13.         <P>
  14.             username
  15.             <b>rod</b>, password
  16.             <b>koala</b>
  17.             <br>
  18.             username
  19.             <b>dianne</b>, password
  20.             <b>emu</b>
  21.             <br>
  22.             username
  23.             <b>scott</b>, password
  24.             <b>wombat</b>
  25.             <br>
  26.             username
  27.             <b>peter</b>, password
  28.             <b>opal</b>
  29.         <p>
  30.             <%-- this form-login-page form is also used as the
  31.          form-error-page to ask for a login again.
  32.          --%>
  33.             <c:if test="${not empty param.login_error}">
  34.                 <font color="red"> Your login attempt was not successful, try
  35.                     again.<br />
  36.                     <br /> Reason: <c:out
  37.                         value="${SPRING_SECURITY_LAST_EXCEPTION.message}" /></font>
  38.             </c:if>
  39.         <form name="f" action="<c:url value='j_spring_security_check'/>"
  40.             method="POST">
  41.             <table>
  42.                 <tr>
  43.                     <td>
  44.                         User:
  45.                     </td>
  46.                     <td>
  47.                         <input type='text' name='j_username'
  48.                             value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>' />
  49.                     </td>
  50.                 </tr>
  51.                 <tr>
  52.                     <td>
  53.                         Password:
  54.                     </td>
  55.                     <td>
  56.                         <input type='password' name='j_password'>
  57.                     </td>
  58.                 </tr>
  59.                 <tr>
  60.                     <td>
  61.                         <input type="checkbox" name="_spring_security_remember_me">
  62.                     </td>
  63.                     <td>
  64.                         Don't ask for my password for two weeks
  65.                     </td>
  66.                 </tr>
  67.                 <tr>
  68.                     <td colspan='2'>
  69.                         <input name="submit" type="submit">
  70.                     </td>
  71.                 </tr>
  72.                 <tr>
  73.                     <td colspan='2'>
  74.                         <input name="reset" type="reset">
  75.                     </td>
  76.                 </tr>
  77.             </table>
  78.         </form>
  79.     </body>
  80. </html>

注意:

<!--
    Usernames/Passwords are
        rod/koala
        dianne/emu
        scott/wombat
        peter/opal
-->

其他资源:

http://www.blogjava.net/redhatlinux/archive/2008/08/20/223148.html

http://www.blogjava.net/redhatlinux/archive/2008/09/01/226010.html

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值