下载地址: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
- package bigbank.web;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.util.Assert;
- import org.springframework.web.servlet.ModelAndView;
- import org.springframework.web.servlet.mvc.Controller;
- import bigbank.BankService;
- public class ListAccounts implements Controller {
- private BankService bankService;
- public ListAccounts(BankService bankService) {
- Assert.notNull(bankService);
- this.bankService = bankService;
- }
- public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
- ModelAndView mav = new ModelAndView("listAccounts");
- mav.addObject("accounts", bankService.findAccounts());
- return mav;
- }
- }
PostAccounts.java
- package bigbank.web;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.util.Assert;
- import org.springframework.web.bind.ServletRequestUtils;
- import org.springframework.web.servlet.ModelAndView;
- import org.springframework.web.servlet.mvc.Controller;
- import bigbank.Account;
- import bigbank.BankService;
- public class PostAccounts implements Controller {
- private BankService bankService;
- public PostAccounts(BankService bankService) {
- Assert.notNull(bankService);
- this.bankService = bankService;
- }
- public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
- Long id = ServletRequestUtils.getRequiredLongParameter(request, "id");
- Double amount = ServletRequestUtils.getRequiredDoubleParameter(request, "amount");
- Account a = bankService.readAccount(id);
- bankService.post(a, amount);
- return new ModelAndView("redirect:listAccounts.html");
- }
- }
Account.java
- package bigbank;
- public class Account {
- private long id = -1;
- private String holder;
- private double balance;
- public Account(String holder) {
- super();
- this.holder = holder;
- }
- public long getId() {
- return id;
- }
- public void setId(long id) {
- this.id = id;
- }
- public String getHolder() {
- return holder;
- }
- public void setHolder(String holder) {
- this.holder = holder;
- }
- public double getBalance() {
- return balance;
- }
- public void setBalance(double balance) {
- this.balance = balance;
- }
- public String toString() {
- return "Account[id=" + id + ",balance=" + balance +",holder=" + holder + "]";
- }
- }
- package bigbank;
- public interface BankDao {
- public Account readAccount(Long id);
- public void createOrUpdateAccount(Account account);
- public Account[] findAccounts();
- }
BankDaoStub.java
- package bigbank;
- import java.util.HashMap;
- import java.util.Map;
- public class BankDaoStub implements BankDao {
- private long id = 0;
- private Map<Long, Account> accounts = new HashMap<Long, Account>();
- public void createOrUpdateAccount(Account account) {
- if (account.getId() == -1) {
- id++;
- account.setId(id);
- }
- accounts.put(new Long(account.getId()), account);
- System.out.println("SAVE: " + account);
- }
- public Account[] findAccounts() {
- Account[] a = (Account[]) accounts.values().toArray(new Account[] {});
- System.out.println("Returning " + a.length + " account(s):");
- for (int i = 0; i < a.length; i++) {
- System.out.println(" > " + a[i]);
- }
- return a;
- }
- public Account readAccount(Long id) {
- return (Account) accounts.get(id);
- }
- }
BankService.java
- package bigbank;
- import org.springframework.security.annotation.Secured;
- public interface BankService {
- @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
- public Account readAccount(Long id);
- @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
- public Account[] findAccounts();
- @Secured("ROLE_TELLER")
- public Account post(Account account, double amount);
- }
BankServiceImpl.java
- package bigbank;
- import org.aspectj.lang.annotation.Pointcut;
- import org.springframework.util.Assert;
- public class BankServiceImpl implements BankService {
- private BankDao bankDao;
- // Not used unless you declare a <protect-pointcut>
- @Pointcut("execution(* bigbank.BankServiceImpl.*(..))")
- public void myPointcut() {}
- public BankServiceImpl(BankDao bankDao) {
- Assert.notNull(bankDao);
- this.bankDao = bankDao;
- }
- public Account[] findAccounts() {
- return this.bankDao.findAccounts();
- }
- public Account post(Account account, double amount) {
- Assert.notNull(account);
- Assert.notNull(account.getId());
- // We read account bank from DAO so it reflects the latest balance
- Account a = bankDao.readAccount(account.getId());
- if (account == null) {
- throw new IllegalArgumentException("Couldn't find requested account");
- }
- a.setBalance(a.getBalance() + amount);
- bankDao.createOrUpdateAccount(a);
- return a;
- }
- public Account readAccount(Long id) {
- return bankDao.readAccount(id);
- }
- }
SeedData.java
- package bigbank;
- import org.springframework.beans.factory.InitializingBean;
- import org.springframework.util.Assert;
- public class SeedData implements InitializingBean {
- private BankDao bankDao;
- public void afterPropertiesSet() throws Exception {
- Assert.notNull(bankDao);
- bankDao.createOrUpdateAccount(new Account("rod"));
- bankDao.createOrUpdateAccount(new Account("dianne"));
- bankDao.createOrUpdateAccount(new Account("scott"));
- bankDao.createOrUpdateAccount(new Account("peter"));
- }
- public void setBankDao(BankDao bankDao) {
- this.bankDao = bankDao;
- }
- }
applicationContext-business.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
- http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd">
- <bean id="bankDao" class="bigbank.BankDaoStub" />
- <bean id="seedData" class="bigbank.SeedData">
- <property name="bankDao" ref="bankDao" />
- </bean>
- <bean id="bankService" class="bigbank.BankServiceImpl">
- <constructor-arg ref="bankDao" />
- <security:intercept-methods>
- <security:protect method="bigbank.BankService.*" access="IS_AUTHENTICATED_REMEMBERED" />
- <security:protect method="bigbank.BankService.post" access="ROLE_TELLER" />
- </security:intercept-methods>
- </bean>
- </beans>
log4j.properties
- # Global logging configuration
- log4j.rootLogger=WARN, stdout, fileout
- log4j.logger.org.springframework.security=DEBUG, stdout, fileout
- # Console output...
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.conversionPattern=[%p,%c{1},%t] %m%n
- # Rolling log file output...
- log4j.appender.fileout=org.apache.log4j.RollingFileAppender
- log4j.appender.fileout.File=spring-security-tutorial.log
- #log4j.appender.fileout.File=${webapp.root}/WEB-INF/log4j.log
- log4j.appender.fileout.MaxFileSize=1024KB
- log4j.appender.fileout.MaxBackupIndex=1
- log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
- log4j.appender.fileout.layout.conversionPattern=%d{ABSOLUTE} %5p %c{1},%t:%L - %m%n
/secure/extreme/index.jsp
- <%@ taglib prefix="authz" uri="http://www.springframework.org/security/tags"%>
- <html>
- <body>
- <h1>VERY Secure Page</h1>
- This is a protected page. You can only see me if you are a supervisor.
- <authz:authorize ifAllGranted="ROLE_SUPERVISOR">
- You have "ROLE_SUPERVISOR" (this text is surrounded by <authz:authorize> tags).
- </authz:authorize>
- <p>
- <a href="../../">Home</a>
- <p>
- <a href="../../j_spring_security_logout">Logout</a>
- </body>
- </html>
/secure/index.jsp
- <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
- <html>
- <body>
- <h1>Secure Page</h1>
- <p>
- This is a protected page. You can get to me if you've been
- remembered, or if you've authenticated this session.
- </p>
- <sec:authorize ifAllGranted="ROLE_SUPERVISOR">
- You are a supervisor! You can therefore see the
- <a href="extreme/index.jsp">extremely secure page</a>.<br />
- <br />
- </sec:authorize>
- <h3>Properties obtained using <sec:authentication /> tag</h3>
- <table border="1">
- <tr>
- <th>Tag</th>
- <th>Value</th>
- </tr>
- <tr>
- <td><sec:authentication property='name' /></td>
- <td><sec:authentication property="name" /></td>
- </tr>
- <tr>
- <td><sec:authentication property='principal.username' /></td>
- <td><sec:authentication property="principal.username" /></td>
- </tr>
- <tr>
- <td><sec:authentication property='principal.enabled' /></td>
- <td><sec:authentication property="principal.enabled" /></td>
- </tr>
- <tr>
- <td><sec:authentication property='principal.accountNonLocked' /></td>
- <td><sec:authentication property="principal.accountNonLocked" /></td>
- </tr>
- </table>
- <p>
- <a href="../">Home</a>
- <p>
- <a href="../j_spring_security_logout">Logout</a>
- </body>
- </html>
listAccounts.jsp
- <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
- <h1>
- Accounts
- </h1>
- <a href="index.jsp">Home3</a>
- <br>
- <br>
- <table>
- <c:forEach var="account" items="${accounts}">
- <tr>
- <td>
- <c:out value="${account.id}" />
- </td>
- <td>
- <c:out value="${account.holder}" />
- </td>
- <td>
- <c:out value="${account.balance}" />
- </td>
- <td>
- <a href="post.html?id=<c:out value="${account.id}"/>amount=-20.00">-$20</a>
- <a href="post.html?id=<c:out value="${account.id}"/>amount=-5.00">-$5</a>
- <a href="post.html?id=<c:out value="${account.id}"/>amount=5.00">+$5</a>
- <a href="post.html?id=<c:out value="${account.id}"/>amount=20.00">+$20</a>
- </td>
- </tr>
- </c:forEach>
- </table>
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-2.0.xsd
- http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">
- <global-method-security secured-annotations="enabled">
- <protect-pointcut expression="execution(* bigbank.*Service.post*(..))" access="ROLE_TELLER"/>
- </global-method-security>
- <http auto-config="true">
- <intercept-url pattern="/secure/extreme/**" access="ROLE_SUPERVISOR"/>
- <intercept-url pattern="/secure/**" access="IS_AUTHENTICATED_REMEMBERED" />
- <!-- Disable web URI authorization, as we're using <global-method-security> and have @Secured the services layer instead
- <intercept-url pattern="/listAccounts.html" access="IS_AUTHENTICATED_REMEMBERED" />
- <intercept-url pattern="/post.html" access="ROLE_TELLER" />
- -->
- <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
- </http>
- <!--
- Usernames/Passwords are
- rod/koala
- dianne/emu
- scott/wombat
- peter/opal
- -->
- <authentication-provider>
- <password-encoder hash="md5"/>
- <user-service>
- <user name="rod" password="a564de63c2d0da68cf47586ee05984d7" authorities="ROLE_SUPERVISOR, ROLE_USER, ROLE_TELLER" />
- <user name="dianne" password="65d15fe9156f9c4bbffd98085992a44e" authorities="ROLE_USER,ROLE_TELLER" />
- <user name="scott" password="2b58af6dddbd072ed27ffc86725d7d3a" authorities="ROLE_USER" />
- <user name="peter" password="22b5c9accc6e1ba628cedc63a72d57f8" authorities="ROLE_USER" />
- </user-service>
- </authentication-provider>
- </beans:beans>
bank-servlet.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="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-2.0.xsd">
- <bean name="/listAccounts.html" class="bigbank.web.ListAccounts">
- <constructor-arg ref="bankService"/>
- </bean>
- <bean name="/post.html" class="bigbank.web.PostAccounts">
- <constructor-arg ref="bankService"/>
- </bean>
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/jsp/"/>
- <property name="suffix" value=".jsp"/>
- </bean>
- </beans>
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name>Spring Security Tutorial Application</display-name>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- classpath:applicationContext-business.xml
- /WEB-INF/applicationContext-security.xml
- </param-value>
- </context-param>
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>/WEB-INF/classes/log4j.properties</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>
- <listener>
- <listener-class>org.springframework.security.ui.session.HttpSessionEventPublisher</listener-class>
- </listener>
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
- <servlet>
- <servlet-name>bank</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>bank</servlet-name>
- <url-pattern>*.html</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
index.jsp
- <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
- <html>
- <body>
- <h1>Home Page</h1>
- <p>Anyone can view this page.</p>
- <p>
- If you're logged in, you can
- <a href="listAccounts.html">list accounts</a>.
- </p>
- <p>
- Your principal object is....:
- <%=request.getUserPrincipal()%>
- </p>
- <p><a href="secure/index.jsp">Secure page</a></p>
- <p><a href="secure/extreme/index.jsp">Extremely secure page</a></p>
- </body>
- </html>
login.jsp
- <%@ taglib prefix='c' uri='http://java.sun.com/jstl/core_rt'%>
- <html>
- <head>
- <title>CUSTOM SPRING SECURITY LOGIN</title>
- </head>
- <body onload="document.f.j_username.focus();">
- <h1>
- CUSTOM SPRING SECURITY LOGIN
- </h1>
- <P>
- Valid users:
- <P>
- <P>
- username
- <b>rod</b>, password
- <b>koala</b>
- <br>
- username
- <b>dianne</b>, password
- <b>emu</b>
- <br>
- username
- <b>scott</b>, password
- <b>wombat</b>
- <br>
- username
- <b>peter</b>, password
- <b>opal</b>
- <p>
- <%-- this form-login-page form is also used as the
- form-error-page to ask for a login again.
- --%>
- <c:if test="${not empty param.login_error}">
- <font color="red"> Your login attempt was not successful, try
- again.<br />
- <br /> Reason: <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>
- User:
- </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>
- Password:
- </td>
- <td>
- <input type='password' name='j_password'>
- </td>
- </tr>
- <tr>
- <td>
- <input type="checkbox" name="_spring_security_remember_me">
- </td>
- <td>
- Don't ask for my password for two weeks
- </td>
- </tr>
- <tr>
- <td colspan='2'>
- <input name="submit" type="submit">
- </td>
- </tr>
- <tr>
- <td colspan='2'>
- <input name="reset" type="reset">
- </td>
- </tr>
- </table>
- </form>
- </body>
- </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