Spring security完成權限管理示例。本站提示廣大學習愛好者:(Spring security完成權限管理示例)文章只能為提供參考,不一定能成為您想要的結果。以下是Spring security完成權限管理示例正文
Spring security完成權限管理示例,詳細如下:
1、配置文件
1、POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.nercita</groupId> <artifactId>BCP</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>BCP</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.0.5.RELEASE</spring.version> <spring.security.version>3.2.3.RELEASE</spring.security.version> <hibernate.version>4.3.5.Final</hibernate.version> </properties> <dependencies> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.annotation</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.ejb</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.jboss.weld</groupId> <artifactId>weld-osgi-bundle</artifactId> <version>1.0.1-SP3</version> <exclusions> <exclusion> <groupId>javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.servlet</artifactId> <version>3.0.1</version> </dependency> <!-- spring4 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- spring mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> <version>${spring.version}</version> </dependency> --> <!-- spring security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>${spring.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.security.version}</version> </dependency> <!-- aspectj weaver.jar 這是SpringAOP所要用到的依賴包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.2</version> </dependency> <!-- 數據庫驅動-mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> <!-- 數據庫驅動-oracle --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>12.1.0.1</version> </dependency> <!-- 數據庫銜接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5</version> </dependency> <!-- hibernate4 中心及依賴包 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> <exclusions> <exclusion> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> </exclusion> <exclusion> <artifactId>c3p0</artifactId> <groupId>c3p0</groupId> </exclusion> </exclusions> </dependency> <!-- 支持JPA標准的core門面 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> <exclusions> <exclusion> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> </dependency> <!-- JPA注解的完成 --> <!-- <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> --> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <!-- 為了讓Hibernate運用代理形式,需求javassist --> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.1-GA</version> </dependency> <!-- antlr --> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <!-- dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- apache commons --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.0</version> </dependency> <!-- pinyin4j --> <dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.0</version> </dependency> <!-- 其他必選依賴包 --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!--ehcache緩存 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.8.3</version> </dependency> <!--其他組件 --> <dependency> <groupId>org.springframework.osgi</groupId> <artifactId>spring-osgi-annotation</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>wsdl4j</groupId> <artifactId>wsdl4j</artifactId> <version>1.6.3</version> </dependency> <!----> <dependency> <groupId>org.apache</groupId> <artifactId>cxf</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.sitemesh</groupId> <artifactId>sitemesh</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.1.7</version> <exclusions> <exclusion> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.0.Final</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.1</version> </dependency> <dependency> <groupId>com.fasterxml</groupId> <artifactId>classmate</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.2</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.12</version> <exclusions> <exclusion> <groupId>javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.12</version> </dependency> <dependency> <groupId>org.dbunit</groupId> <artifactId>dbunit</artifactId> <version>2.4.7</version> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymock</artifactId> <version>3.2</version> </dependency> <dependency> <groupId>org.apache.ws.commons.schema</groupId> <artifactId>XmlSchema</artifactId> <version>1.4.7</version> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.2.1</version> </dependency> <!-- log4j 日志--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- slf4j-api 日志接口 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <!-- slf4j-log4j12 日志接口橋接 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <!-- slf4j-nop 日志 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.7.7</version> </dependency> <!-- log4j2 日志--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.1</version> </dependency> <!-- 文件上傳 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- fastJson json數組有關的 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.1</version> </dependency> <!-- 運用 Jackson 把 Java對象轉換成 JSON字符串 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.13</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.13</version> </dependency> <!-- <dependency> <groupId>org.apache.poi</groupId> <artifactId>openxml4j</artifactId> <version>1.0-beta</version> </dependency> --> <!-- jxls --> <dependency> <groupId>net.sf.jxls</groupId> <artifactId>jxls-core</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>net.sf.jxls</groupId> <artifactId>jxls-reader</artifactId> <version>1.0.6</version> </dependency> <!-- xmlpull xml to java --> <dependency> <groupId>xmlpull</groupId> <artifactId>xmlpull</artifactId> <version>1.1.3.4a</version> </dependency> <!-- 運用JSONObject,將接納到的後果轉成JSON格式 --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier><!--指定jdk版本--> </dependency> <!-- net.sf.json-lib包依賴以下包:--> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.7</version> </dependency> <!-- 雲通訊短信發送API--> <dependency> <groupId>com.yuntongxun</groupId> <artifactId>ccp</artifactId> <version>2.6.3</version> </dependency> </dependencies> <build> <finalName>BCP</finalName> </build> </project>
2.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name>SSH-Application</display-name> <!--初始化參數--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext*.xml</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>message/message-info</param-value> </context-param> <!--Spring ContextLoaderListener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- ETag過濾器,節省帶寬 --> <filter> <filter-name>etagFilter</filter-name> <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class> </filter> <filter-mapping> <filter-name>etagFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--UTF-8編碼 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- OpenSessionInViewFilter --> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <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> <!-- 頁面裝配-sitemesh --> <filter> <filter-name>sitemesh</filter-name> <filter-class>org.sitemesh.config.ConfigurableSiteMeshFilter</filter-class> </filter> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 清算內存 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- WebService-CXF --> <servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <!-- spring-MVC --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/webmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- session過時時長 --> <session-config> <session-timeout>60</session-timeout> </session-config> <!--默許首頁 --> <welcome-file-list> <welcome-file>/main.jsp</welcome-file> </welcome-file-list> <!-- 異常頁面 --> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/common/500.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/common/500.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/common/404.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/common/403.jsp</location> </error-page> <!-- <servlet> <servlet-name>coreServlet</servlet-name> <servlet-class> org.nercita.bcp.wechat.servlet.CoreServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>coreServlet</servlet-name> <url-pattern>/wx.do</url-pattern> </servlet-mapping> --> </web-app>
3.application-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-4.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd"> <!-- 配置不要過濾的圖片等靜態資源 --> <http pattern="/services*" security="none" /> <http pattern="/wx.do*" security="none" /> <http pattern="/api/**" security="none" /> <http pattern="/services/**" security="none" /> <http pattern="/common/**" security="none" /> <http pattern="/images/**" security="none" /> <http pattern="/styles/**" security="none" /> <http pattern="/js/**" security="none" /> <http pattern="/css/**" security="none" /> <http pattern="/htm/**" security="none" /> <http pattern="/main.jsp*" security="none" /> <http pattern="/login.jsp*" security="none" /> <http pattern="/install.jsp*" security="none" /> <http pattern="/system/springSecurity/init*" security="none" /> <http pattern="/system/user/registPage*" security="none" /> <http pattern="/system/user/regist*" security="none" /> <http pattern="/mr*" security="none" /> <http pattern="/system/user/mobile/regist*" security="none" /> <http pattern="/system/user/activate*" security="none" /> <http pattern="/system/user/checkImg*" security="none" /> <http pattern="/system/user/checkName*" security="none" /> <http pattern="/system/user/checkValidateCode*" security="none" /> <http pattern="/system/user/forgotPassword*" security="none" /> <http pattern="/system/user/resetRequest*" security="none" /> <http pattern="/system/user/resetPasswordPage*" security="none" /> <http pattern="/system/user/resetPassword*" security="none" /> <http pattern="/system/message/save*" security="none" /> <http pattern="/system/message/introduction" security="none" /> <http auto-config="true" create-session="always" access-denied-page="/common/403.jsp" use-expressions="true" disable-url-rewriting="true"> <!-- 配置登錄頁面 --> <form-login login-page="/login.jsp" login-processing-url="/j_spring_security_check" authentication-failure-url="/login.jsp?error=true" default-target-url="/index" always-use-default-target="true" authentication-success-handler-ref="authenticationSuccess" authentication-failure-handler-ref="exceptionMappingAuthenticationFailureHandler"/> <!-- "記住我"功用,采用耐久化戰略(將用戶的登錄信息寄存cookie --> <remember-me key="bcp" use-secure-cookie="true" /> <!-- 用戶加入的跳轉頁面 --> <!-- <logout invalidate-session="true" logout-url="/j_spring_security_logout" logout-success-url="/login.jsp"/> --> <logout invalidate-session="true" logout-url="/j_spring_security_logout" success-handler-ref="logoutSuccessHandler" /> <!-- 會話管理,設置最多登錄異常,error-if-maximum-exceeded = false為第二次登錄就會使前一個登錄生效 --> <session-management invalid-session-url="/login.jsp?expired=true"> <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" expired-url="/login.jsp?expired=true"/> </session-management> <!-- 添加自定義的過濾器 放在FILTER_SECURITY_INTERCEPTOR之前無效 --> <custom-filter ref="customFilterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR" /> <custom-filter ref="switchUserProcessingFilter" after="FILTER_SECURITY_INTERCEPTOR"/> <anonymous enabled="false" /> </http> <!-- 登陸成功跳轉 --> <beans:bean id="authenticationSuccess" class="org.nercita.bcp.system.service.CustomSavedRequestAwareAuthenticationSuccessHandler"> <beans:property name="defaultTargetUrl" value="/index"/> </beans:bean> <!-- 登記成功 --> <beans:bean id="logoutSuccessHandler" class="org.nercita.bcp.system.service.CustomLogoutSuccessHandler"> <beans:property name="defaultTargetUrl" value="/login.jsp"></beans:property> </beans:bean> <beans:bean id="customUserDetailsService" class="org.nercita.bcp.system.service.CustomUserDetailsService"/> <!-- 用戶登陸處置 --> <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="customUserDetailsService"> <password-encoder hash="md5" base64="true" > <salt-source user-property="username"/> </password-encoder> </authentication-provider> </authentication-manager> <beans:bean id="exceptionMappingAuthenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler"> <beans:property name="exceptionMappings"> <beans:props> <beans:prop key="org.springframework.security.authentication.DisabledException">/login.jsp?role=false</beans:prop> <beans:prop key="org.springframework.security.authentication.BadCredentialsException">/login.jsp?error=true</beans:prop> <beans:prop key="org.springframework.security.authentication.LockedException">/login.jsp?locked=true</beans:prop> </beans:props> </beans:property> </beans:bean> <beans:bean id="switchUserProcessingFilter" class="org.springframework.security.web.authentication.switchuser.SwitchUserFilter"> <beans:property name="userDetailsService" ref="customUserDetailsService" /> <beans:property name="switchUserUrl" value="/j_spring_security_switch_user" /> <beans:property name="exitUserUrl" value="/j_spring_security_exit_user" /> <beans:property name="targetUrl" value="/index" /> </beans:bean> </beans:beans>
4. applicationContext.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 引入屬性文件 --> <context:property-placeholder location="classpath*:/application.properties" /> <context:spring-configured /> <!-- 注解bean及依賴注入 --> <context:component-scan base-package="org.nercita.bcp"> <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation" /> </context:component-scan> <!-- 數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" > <property name="driverClass" value="${db.driverClass}"/> <property name="jdbcUrl" value="${db.url}"/> <property name="user" value="${db.username}"/> <property name="password" value="${db.password}"/> </bean> <!-- sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl}</prop> </props> </property> <property name="packagesToScan"> <list> <value>org.nercita.bcp.**.domain**</value> </list> </property> </bean> <!-- 事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 開啟注解事務 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 獲取spring上下文 的ApplicationContextAware的完成Bean --> <bean class="org.nercita.core.utils.SpringContextHolder" lazy-init="false" /> </beans>
5.application.properties
#jdbc settings #Mysql settings 3306 #db.url=jdbc:mysql://localhost:3306/bcp #db.driverClass=com.mysql.jdbc.Driver #db.username=root #db.password=0729 #hibernate.dialect=org.hibernate.dialect.MySQLDialect #hibernate settings hibernate.show_sql=true hibernate.format_sql=true hibernate.use_second_level_cache=true hibernate.use_query_cache=true hibernate.hbm2ddl=update
6. springMVC-config.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 靜態資源 不阻攔 --> <mvc:resources location="/common/" mapping="/common/**"/> <mvc:resources location="/images/" mapping="/images/**" /> <mvc:resources location="/js/" mapping="/js/**" /> <mvc:resources location="/css/" mapping="/css/**" /> <mvc:resources location="/styles/" mapping="/styles/**" /> <mvc:resources location="/htm/" mapping="/htm/**" /> <import resource="view-controller.xml" /> <context:annotation-config/> <context:component-scan base-package="org.nercita.bcp" use-default-filters="false"> <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation" /> </context:component-scan> <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.nercita.core.web.springmvc.StringHttpMessageConverter" /> <ref bean="msgConverter"/> </list> </property> <property name="webBindingInitializer"> <bean class="org.nercita.core.web.springmvc.CustomBindInitializer"> <!-- <property name="validator" ref="validator" /> <property name="conversionService" ref="conversionService" /> --> </bean> </property> </bean> <bean id="msgConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!-- <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/> --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="ignoreAcceptHeader" value="true"/> <property name="defaultContentType" value="text/html"/> <property name="mediaTypes"> <map> <entry key="json" value="application/json"/> <entry key="xml" value="application/xml"/> </map> </property> <property name="favorParameter" value="false"/> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </list> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/> <bean class="org.springframework.web.servlet.view.xml.MarshallingView"> <property name="marshaller"> <bean class="org.springframework.oxm.xstream.XStreamMarshaller"/> </property> </bean> </list> </property> </bean> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView" value="error" /> <property name="exceptionMappings"> <props> <prop key=".DataAccessException">dataAccessFailure</prop> <prop key=".NoSuchRequestHandlingMethodException">resourceNotFound</prop> <prop key=".TypeMismatchException">resourceNotFound</prop> <prop key=".lang.Exception">uncaughtException</prop> </props> </property> </bean> <!-- 文件上傳--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="104857600"/> <property name="maxInMemorySize" value="4096"/> </bean> <!-- 處置國際化資源文件 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="message/message-info" /> <property name="useCodeAsDefaultMessage" value="true" /> </bean> </beans>
2、完成代碼
1、CustomAccessDecisionManager.Java
package org.nercita.bcp.system.service; import java.util.Collection; import java.util.Iterator; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Service; /** * 該類為訪問決策器,決議某個用戶具有的角色,能否有足夠的權限去訪問某個資源,完成用戶和訪問權限的對應關。 * 這個類次要是處置用戶在訪問某個URL的時分,就會經過訪問該類的權限與登錄用戶所擁有的權限做比擬, * 假如用戶擁有權限,那就可以到訪問資源,假如沒有權限,那不能訪問資源,還會拋一個異常。 * AccessdecisionManager在Spring security中是很重要的。 * 驗證局部簡單提過一切的Authentication完成需求保管在一個GrantedAuthority對象數組中。 這就是賦予給主體的權限。 * GrantedAuthority對象經過AuthenticationManager 保管到 Authentication對象裡,然後從AccessDecisionManager讀出來,停止受權判別。 * Spring Security提供了一些阻攔器,來控制對平安對象的訪問權限,例如辦法調用或web懇求。 * 一個能否允許執行調用的預調用決議,是由AccessDecisionManager完成的。 * 這個 AccessDecisionManager被AbstractSecurityInterceptor調用, 用來作最終訪問控制的決議。 * * 這個AccessDecisionManager接口包括三個辦法: * void decide(Authentication authentication, Object secureObject, List<ConfigAttributeDefinition> config); * boolean supports(ConfigAttribute attribute); boolean supports(Class clazz); * 第一個辦法:AccessDecisionManager運用辦法參數傳遞一切信息,認證評價時停止決議。 * 假如訪問被回絕,完成將拋出一個AccessDeniedException異常。 * 第二個辦法:在啟動的時分被 AbstractSecurityInterceptor調用, * 來決議AccessDecisionManager 能否可以執行傳遞ConfigAttribute。 * 第三個辦法:被平安阻攔器完成調用, 平安阻攔器將顯示的AccessDecisionManager支持平安對象的類型。 */ @Service("customAccessDecisionManager") public class CustomAccessDecisionManager implements AccessDecisionManager { /** * 該辦法:需求比擬權限和權限配置 * object參數是一個 URL, 同一個過濾器該url對應的權限配置被傳遞過去. * 檢查authentication能否存在權限在configAttributes中 * 假如沒有婚配的權限, 扔出一個回絕訪問的異常 */ @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (configAttributes==null){ return; } Iterator<ConfigAttribute> iter = configAttributes.iterator(); while(iter.hasNext()){ ConfigAttribute ca = iter.next(); String needRole = ((SecurityConfig) ca).getAttribute(); //gra 為用戶所被賦予的權限,needRole為訪問相應的資源應具有的權限 for (GrantedAuthority gra : authentication.getAuthorities()) { if (needRole.trim().equals(gra.getAuthority().trim())) { return; } } } throw new AccessDeniedException("Access Denied"); } @Override public boolean supports(ConfigAttribute attribute) { return true; } @Override public boolean supports(Class<?> clazz) { return true; } }
2、CustomFilterInvocationSecurityMetadataSource.java
package org.nercita.bcp.system.service; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.annotation.PostConstruct; import org.nercita.bcp.system.domain.Authority; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.stereotype.Service; /** * 該類是資源的訪問權限的定義,完成資源和訪問權限的對應關系 * 該類的次要作用是在Spring Security的整個過濾鏈啟動後, * 在容器啟動的時分,順序就會進入到該類中的init()辦法,init調用了loadResourceDefine()辦法, * 該辦法的次要目的是將數據庫中的一切資源與權限讀取到本地緩存中保管起來! * 類中的resourceMap就是保管的一切資源和權限的集合,URL為Key,權限作為Value! * * @author zhangwenchao * */ @Service("customFilterInvocationSecurityMetadataSource") public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { @Autowired private AuthorityService authorityService; //運用的是AntUrlPathMatcher這個path matcher來反省URL能否與資源定義婚配 //private RequestMatcher urlMatcher = null; //resourceMap就是保管的一切資源和權限的集合,URL為Key,權限作為Value! private static HashMap<String, Collection<ConfigAttribute>> resourceMap = null; /** * * 自定義辦法,這個類放入到Spring容器後, * 指定init為初始化辦法,從數據庫中讀取資源 */ @PostConstruct public void init() { loadResourceDefine(); } /** * * 順序啟動的時分就加載一切資源信息 * 初始化資源與權限的映射關系 */ private void loadResourceDefine() { // 在Web服務器啟動時,提取零碎中的一切權限authority.name. List<Authority> authorities = authorityService.findAll(); //該當是資源為key, 權限為value。 資源通常為url, 權限就是那些以ROLE_為前綴的角色。 一個資源可以由多個權限來訪問。 resourceMap = new HashMap<String, Collection<ConfigAttribute>>(); if(authorities!=null && authorities.size()>0 ) for (Authority auth : authorities) { String authName = auth.getCode(); //獲取權限的name 是以 ROLE_為前綴的代碼值 ConfigAttribute ca = new SecurityConfig(authName); //將ROLE_XXX 封裝成spring的權限配置屬性 //依據權限名獲取一切資源 String url = auth.getResourceUrl(); //判別資源文件和權限的對應關系,假如曾經存在相關的資源url,則要經過該url為key提取出權限集合,將權限添加到權限集合中。 if (resourceMap.containsKey(url)) { //假如已存在url 參加權限 Collection<ConfigAttribute> value = resourceMap.get(url); value.add(ca); resourceMap.put(url, value); } else {//假如不存存在url 參加url和權限 Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>(); atts.add(ca); resourceMap.put(url, atts); } } } /** * 依據URL獲取該URL權限的配置 */ @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { //object是一個URL ,為用戶懇求URL String url = ((FilterInvocation)object).getRequestUrl(); int firstQuestionMarkIndex = url.indexOf("?"); if (firstQuestionMarkIndex != -1) { url = url.substring(0, firstQuestionMarkIndex); } Iterator<String> iter = resourceMap.keySet().iterator(); String matchUrl=null;//婚配url //取到懇求的URL後與下面取出來的資源做比擬 while (iter.hasNext()) { String resURL = iter.next(); // if(urlMatcher.pathMatchesUrl(resURL,url)){ if(url.startsWith(resURL)){ // return resourceMap.get(resURL); //前往權限的集合 //初次婚配或以後婚配的url更長則更新婚配url if(matchUrl==null||matchUrl.length()<resURL.length()) matchUrl=resURL; } } if(matchUrl!=null){ //假如存在婚配的url則前往需具有的權限 // System.out.println(matchUrl+"-------"+resourceMap.get(matchUrl)); return resourceMap.get(matchUrl); } // 當零碎中沒配資源權限url,用戶在訪問這個資源的狀況下,前往null 表示放行 , // 假如當零碎分配了資源url,但是這個用戶立屬的角色沒有則 提示用戶無權訪問這個頁面 return null; } /* * @return * @link org.springframework.security.access.SecurityMetadataSource#getAllConfigAttributes() */ @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } @Override public boolean supports(Class<?> clazz) { return true; } }
3、CustomFilterSecurityInterceptor.java
package org.nercita.bcp.system.service; import java.io.IOException; import javax.annotation.Resource; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.nercita.bcp.system.util.LogInfoService; import org.springframework.security.access.AccessDeniedException; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; import org.springframework.security.access.intercept.InterceptorStatusToken; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.stereotype.Service; @Service("customFilterSecurityInterceptor") public class CustomFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { // 注入資源數據定義器 @Resource @Qualifier("customFilterInvocationSecurityMetadataSource") private FilterInvocationSecurityMetadataSource securityMetadataSource; // 注入訪問決策器 @Resource @Qualifier("customAccessDecisionManager") @Override public void setAccessDecisionManager(AccessDecisionManager accessDecisionManager){ super.setAccessDecisionManager(accessDecisionManager); } // 注入認證管理器 @Resource @Qualifier("authenticationManager") @Override public void setAuthenticationManager(AuthenticationManager newManager) { super.setAuthenticationManager(newManager); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest)request; HttpServletResponse httpResponse = (HttpServletResponse)response; // 用戶未登錄狀況下 經過在地址欄輸出無效的url 訪問零碎 能夠形成零碎呈現問題,所以限制匿名用戶登錄 自動跳轉到登錄頁面 if(LogInfoService.getLoginUserName()==null){ httpResponse.sendRedirect(httpRequest.getContextPath()+"/login.jsp"); return; } FilterInvocation fi = new FilterInvocation(request, response, chain); invoke(fi); } /** * * @param fi * @throws ServletException * @throws IOException */ private void invoke(FilterInvocation fi) throws IOException, ServletException { // InterceptorStatusToken token = super.beforeInvocation(fi); // try { // fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); // } finally { // super.afterInvocation(token, null); // } InterceptorStatusToken token = null; try { token = super.beforeInvocation(fi); } catch (Exception e) { // 用戶登錄狀況下 零碎中存在用戶訪問的資源url和權限,但是以後用戶的角色中沒有這個權限 所以提示跳轉用戶無權訪問的頁面 if( e instanceof AccessDeniedException){ // HttpServletRequest httpRequest = fi.getRequest(); // HttpServletResponse httpResponse = fi.getResponse(); // // String path = httpRequest.getContextPath(); // String basePath = httpRequest.getScheme()+"://"+httpRequest.getServerName()+":"+httpRequest.getServerPort()+path+"/"; // httpResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); // RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(basePath+"/common/403.jsp"); // // dispatcher.forward(httpRequest, httpResponse); // httpResponse.sendRedirect(basePath+"/common/403.jsp"); throw new AccessDeniedException("用戶無權訪問"); } return; } try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } } @Override public void init(FilterConfig arg0) throws ServletException { } @Override public Class<? extends Object> getSecureObjectClass() { return FilterInvocation.class; } @Override public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } @Override public void destroy() { } public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return securityMetadataSource; } public void setSecurityMetadataSource( FilterInvocationSecurityMetadataSource securityMetadataSource) { this.securityMetadataSource = securityMetadataSource; } }
3、中心處置類:CustomUserDetailsService.java
package org.nercita.bcp.system.service; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.annotation.Resource; import org.nercita.bcp.system.dao.AuthorityDao; import org.nercita.bcp.system.dao.UserDao; import org.nercita.bcp.system.domain.Authority; import org.nercita.bcp.system.domain.User; import org.nercita.bcp.system.domain.reference.UserDetail; import org.nercita.bcp.system.domain.reference.UserState; import org.nercita.bcp.system.domain.reference.UserType; import org.springframework.dao.DataAccessException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; /** * 該類是用戶信息的定義和驗證 * 這個類次要是處置用戶登錄信息,在用戶輸出用戶名和密碼後, * spring security會帶著用戶名調用類外面的loadUserByUsername(usrename)辦法, * 經過用戶名查出用戶信息,然後把數據庫中查出的用戶密碼和剛剛用戶輸出的存儲在session中的密碼做比擬,然後判別該用戶能否合法! * */ @Service("customUserDetailsService") public class CustomUserDetailsService implements UserDetailsService { //用戶耐久類 @Resource(name="userDao") private UserDao userDao; @Resource(name="authorityDao") private AuthorityDao authorityDao; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException { //依據登錄名獲取登陸用戶 User user = userDao.findByName(userName); if(null == user) { throw new UsernameNotFoundException("用戶" + userName + "不存在"); } //依據用戶的 類型獲取用戶權限 if(user.getUserType() == UserType.SysAdmin){ //用戶類型為0, 表示是零碎平台管理員用戶 Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); List<Authority> authorities = authorityDao.findAll(); //獲取零碎中一切權限 for(Iterator<Authority> iter =authorities.iterator();iter.hasNext();){ auths.add(new SimpleGrantedAuthority(iter.next().getCode())); } //UserDetail userDetail = new UserDetail(userName, user.getPassword(), true, true, true, true, auths); //修正為前台零碎,不能讓零碎管理員登陸 UserDetail userDetail = new UserDetail(userName, user.getPassword(), false, true, true, true, auths); userDetail.setUserGroupId(user.getUserGroup().getId()); userDetail.setRealName(user.getRealName()); userDetail.setUserType(user.getUserType()); return userDetail; }else if(user.getUserType() == UserType.TeamAdmin){ //團隊管理員 //用戶能否可用 boolean enabled = user.getEnabled(); //獲取團隊管理員的一切權限 Set<Authority> authorities = user.getAuthoritySet(); Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); for(Iterator<Authority> iter=authorities.iterator();iter.hasNext();){ auths.add(new SimpleGrantedAuthority(iter.next().getCode())); } //由於spring security包中的User也完成了UserDetails,所以也可以直接前往User UserDetail userDetail =null; if(UserState.Enable == user.getUserState()){ userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, true, auths); }else{ userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, false, auths); //throw new LockedException("用戶" + userName + "被鎖定"); } userDetail.setUserGroupId(user.getUserGroup().getId()); userDetail.setTeamGroupId(user.getUserGroup().getId()); userDetail.setRealName(user.getRealName()); userDetail.setUserType(user.getUserType()); return userDetail; }else{//團隊用戶 //用戶能否可用 boolean enabled = user.getEnabled(); Set<Authority> authorities = user.getAuthoritySet(); Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); for(Iterator<Authority> iter=authorities.iterator();iter.hasNext();){ auths.add(new SimpleGrantedAuthority(iter.next().getCode())); } //由於spring security包中的User也完成了UserDetails,所以也可以直接前往User UserDetail userDetail =null; if(user.getUserGroup().getTeamAdmin().getUserState()==UserState.Disable){//假如團隊管理員被禁用,其上司團隊用也不能登錄 userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, false, auths); return userDetail; } if(UserState.Enable == user.getUserState()){ userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, true, auths); }else{ userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, false, auths); //throw new LockedException("用戶" + userName + "被鎖定"); } userDetail.setUserGroupId(user.getUserGroup().getId()); userDetail.setTeamGroupId(user.getUserGroup().getTeamAdmin().getUserGroup().getId()); userDetail.setRealName(user.getRealName()); userDetail.setUserType(user.getUserType()); return userDetail; } } }
4.附加類登錄成功和加入成功處置
1、CustomSavedRequestAwareAuthenticationSuccessHandler.java
package org.nercita.bcp.system.service; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.nercita.bcp.basic.domain.Crop; import org.nercita.bcp.system.domain.SystemLog; import org.nercita.bcp.system.domain.User; import org.nercita.bcp.system.domain.reference.UserType; import org.nercita.bcp.system.util.LogInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.savedrequest.RequestCache; public class CustomSavedRequestAwareAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // 添加登錄日志 private static Logger logger = LogManager.getLogger(CustomSavedRequestAwareAuthenticationSuccessHandler.class); @Autowired private SystemLogService systemLogService; @Autowired private UserService userService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { System.out.println("用戶登錄成功處置。。。。"); User u = LogInfoService.getLoginUser(); HttpSession session =request.getSession(); if(u.getUserType()==UserType.TeamAdmin ){//用戶為團隊管理員 List<Crop> croplist = u.getCropSet(); for(Iterator<Crop> iter = croplist.iterator();iter.hasNext();){//去除被制止的作物 String status = userService.getUserCropStatus(u.getId(),iter.next().getId()); if(status!=null && !status.equals("1")){ iter.remove(); } } session.setAttribute("croplist", croplist); }else if(u.getUserType()==UserType.TeamUser){//用戶為普通用戶 List<Crop> croplist = u.getCropSet(); for(Iterator<Crop> iter = croplist.iterator();iter.hasNext();){//去除團隊管理員被制止的作物 String status = userService.getUserCropStatus(u.getUserGroup().getTeamAdmin().getId(),iter.next().getId()); if(status!=null && !status.equals("1")){ iter.remove(); } } session.setAttribute("croplist", croplist); }else{//用戶為零碎管理員 session.setAttribute("croplist", LogInfoService.getAllCrops()); } String userName = authentication.getName(); //用戶名 String address = request.getRemoteAddr(); //近程地址 //寫入日志 systemLogService.save(new SystemLog(address, "登錄", "用戶登錄零碎", userName, new Date())); logger.info("用戶" + userName + "在地址" + address + "登入零碎,時間:"+new Date()); super.onAuthenticationSuccess(request, response, authentication); } @Override public void setRequestCache(RequestCache requestCache) { super.setRequestCache(requestCache); } }
2、CustomLogoutSuccessHandler.java
package org.nercita.bcp.system.service; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.nercita.bcp.system.domain.SystemLog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler { private static Logger logger = LogManager.getLogger(CustomLogoutSuccessHandler.class); @Autowired private SystemLogService systemLogService; @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { System.out.println("用戶加入成功處置。。。。"); String userName = authentication.getName(); //用戶名 String address = request.getRemoteAddr(); //近程地址 systemLogService.save(new SystemLog(address, "加入", "用戶加入零碎", userName, new Date())); logger.info("日志:ip:"+request.getRemoteAddr() +"host:"+request.getRemoteHost()+"加入時間:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); super.onLogoutSuccess(request, response, authentication); } }
3、實體Bean
1、User.java
package org.nercita.bcp.system.domain; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.Cacheable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.nercita.bcp.basic.domain.Crop; import org.nercita.bcp.system.domain.reference.ExamineStatus; import org.nercita.bcp.system.domain.reference.UserState; import org.nercita.bcp.system.domain.reference.UserType; import org.nercita.core.orm.BaseUidEntity; import com.alibaba.fastjson.annotation.JSONField; /** * 用戶實體 * @author zhangwenchao */ @Entity @Table(name = "T_P_User") @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class User extends BaseUidEntity { private static final long serialVersionUID = -2512321822386351911L; // 用戶名 @Column(length = 64, unique = true, nullable = false) private String name; // 密碼 @Column(length = 64, nullable = false) private String password; // 真實姓名 @Column(length = 64, nullable = false) private String realName; // 手機 @Column(length = 13) private String phone; // 公司或單位 @Column(length = 64) private String company; // 電子郵件 @Column(length = 64) private String email; // 能否可用 private Boolean enabled; // 激活碼 @Column(unique=true,nullable=true) private String activationCode; // 重置碼 @Column(unique=true,nullable=true) private String resetCode; /* * 用戶類型: 0:平台管理員 1:團隊管理員 2:團隊用戶 */ private UserType userType; /* * 用戶形態 0:禁用(未激活) 1:啟用(激活) */ private UserState userState = UserState.Disable; /* * 能否黑名單 0:白名單 1:黑名單 */ @Column(length=1) private int abolished=0; //用戶代號 @Column(length=1) private String userMark; //PDA imei信息 @Column(nullable=true) private String imei; // 用戶所在用戶組 @ManyToOne(optional = true, cascade = {CascadeType.PERSIST,CascadeType.MERGE}) @JoinColumn(name = "userGroup_id") private UserGroup userGroup; //權限集合 @ManyToMany(fetch = FetchType.LAZY) @JSONField(serialize=false) private Set<Authority> authoritySet = new HashSet<Authority>(); // 用戶所屬的作物集合 @ManyToMany(fetch = FetchType.EAGER) // @JSONField(serialize=false) private List<Crop> cropSet = new ArrayList<Crop>(); // 用戶的菜單包 @ManyToOne(optional = true, fetch = FetchType.EAGER) @JSONField(serialize=false) private MenuPackage menuPackage; // 用戶的團隊配置 @ManyToOne(optional = true, fetch = FetchType.EAGER) @JSONField(serialize=false) private CollocateTeam collocateTeam; //注冊時間 private Date registData; //截止日期 private Date expirationDate; //審核形態(未審核、已上傳、已審核) private ExamineStatus examineStatus; //審核資料途徑 private String certificationUrls; // 記載人 @Column(updatable = false) private String recorder; // 記載時間 @Temporal(TemporalType.TIMESTAMP) @Column(updatable = false) private Date recordTime; // 修正人 private String modifier; // 修正時間 @Temporal(TemporalType.TIMESTAMP) @Column(updatable = true) private Date modifyTime; @Column(length = 255) private String remark; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getActivationCode() { return activationCode; } public void setActivationCode(String activationCode) { this.activationCode = activationCode; } public String getResetCode() { return resetCode; } public void setResetCode(String resetCode) { this.resetCode = resetCode; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public UserType getUserType() { return userType; } public void setUserType(UserType userType) { this.userType = userType; } public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public UserState getUserState() { return userState; } public void setUserState(UserState userState) { this.userState = userState; } public int getAbolished() { return abolished; } public void setAbolished(int abolished) { this.abolished = abolished; } public UserGroup getUserGroup() { return userGroup; } public void setUserGroup(UserGroup userGroup) { this.userGroup = userGroup; } public Set<Authority> getAuthoritySet() { return authoritySet; } public void setAuthoritySet(Set<Authority> authoritySet) { this.authoritySet = authoritySet; } public List<Crop> getCropSet() { return cropSet; } public void setCropSet(List<Crop> cropSet) { this.cropSet = cropSet; } public MenuPackage getMenuPackage() { return menuPackage; } public void setMenuPackage(MenuPackage menuPackage) { this.menuPackage = menuPackage; } public CollocateTeam getCollocateTeam() { return collocateTeam; } public void setCollocateTeam(CollocateTeam collocateTeam) { this.collocateTeam = collocateTeam; } public String getRecorder() { return recorder; } public void setRecorder(String recorder) { this.recorder = recorder; } public Date getRecordTime() { return recordTime; } public void setRecordTime(Date recordTime) { this.recordTime = recordTime; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getUserMark() { return userMark; } public void setUserMark(String userMark) { this.userMark = userMark; } public User() { } public Date getRegistData() { return registData; } public void setRegistData(Date registData) { this.registData = registData; } public Date getExpirationDate() { return expirationDate; } public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } public ExamineStatus getExamineStatus() { return examineStatus; } public void setExamineStatus(ExamineStatus examineStatus) { this.examineStatus = examineStatus; } public String getCertificationUrls() { return certificationUrls; } public void setCertificationUrls(String certificationUrls) { this.certificationUrls = certificationUrls; } public User(String name, String password, String realName, Boolean enabled, UserType userType, UserState userState) { super(); this.name = name; this.password = password; this.realName = realName; this.enabled = enabled; this.userType = userType; this.userState = userState; } }
2.Authority.java
package org.nercita.bcp.system.domain; import java.util.Date; import javax.persistence.Cacheable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Index; import org.nercita.core.orm.BaseUidEntity; /** * 用戶權限 * @author zhangwenchao * */ @SuppressWarnings("deprecation") @Entity @Table(name="T_P_Authority") @Cacheable @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class Authority extends BaseUidEntity{ private static final long serialVersionUID = 1558957611918721365L; //ROLE_"為前綴的代碼 @Column(length=64, nullable=false, unique=true) @Index(name="Index_Authority_code") private String code; //權限稱號 @Column(length=64,nullable=false) private String name; //父權限 @ManyToOne private Authority parentAuthority; //資源途徑 private String resourceUrl; //能否為父權限 private boolean isParent; //權限樹形深度 private Integer deepLevel = 0; //權限能否可用 private boolean enabled=true; //所屬菜單 @ManyToOne(optional = true, cascade = {CascadeType.PERSIST}) @JoinColumn(name="menu_id") private Menu menu; //記載人 @Column(updatable = false) private String recorder; private Integer orderNum = 0; //記載時間 @Temporal(TemporalType.TIMESTAMP) @Column(updatable = false) private Date recordTime; //修正人 private String modifier; //修正時間 @Temporal(TemporalType.TIMESTAMP) @Column(updatable = true) private Date modifyTime; //備注 @Column(length=255) private String remark; public Integer getOrderNum() { return orderNum; } public void setOrderNum(Integer orderNum) { this.orderNum = orderNum; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authority getParentAuthority() { return parentAuthority; } public void setParentAuthority(Authority parentAuthority) { this.parentAuthority = parentAuthority; } public String getResourceUrl() { return resourceUrl; } public void setResourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; } public boolean isParent() { return isParent; } public void setParent(boolean isParent) { this.isParent = isParent; } public Integer getDeepLevel() { return deepLevel; } public void setDeepLevel(Integer deepLevel) { this.deepLevel = deepLevel; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Menu getMenu() { return menu; } public void setMenu(Menu menu) { this.menu = menu; } public String getRecorder() { return recorder; } public void setRecorder(String recorder) { this.recorder = recorder; } public Date getRecordTime() { return recordTime; } public void setRecordTime(Date recordTime) { this.recordTime = recordTime; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Authority other = (Authority) obj; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; return true; } }
3. UserGroup.java
package org.nercita.bcp.system.domain; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.Cacheable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.nercita.core.orm.BaseUidEntity; import com.alibaba.fastjson.annotation.JSONField; @Entity @Table(name="T_P_UserGroup") @Cacheable @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class UserGroup extends BaseUidEntity{ private static final long serialVersionUID = -2723021723072060418L; //用戶組名 private String name; //父用戶組 ---允許為空 @ManyToOne(optional=true,cascade=CascadeType.PERSIST,fetch=FetchType.EAGER) private UserGroup parentUserGroup; //子用戶組 @OneToMany(mappedBy="parentUserGroup") @JSONField(serialize=false) private Set<UserGroup> childrenUserGroups = new HashSet<UserGroup>(); //該用戶組的團隊管理員 @ManyToOne(optional=true, cascade=CascadeType.PERSIST) @JoinColumn(name="teamAdmin_id") private User teamAdmin; //組內用戶列表 @OneToMany(mappedBy="userGroup") @JSONField(serialize=false) private List<User> userList = new ArrayList<User>(); //用戶組深度級別 :0:團隊管理員, 1...N:子用戶 @Column(nullable=false) private Integer deepLevel; //記載人 @Column(updatable = false) private String recorder; //記載時間 @Temporal(TemporalType.TIMESTAMP) @Column(updatable = false) private Date recordTime; //修正人 private String modifier; //修正時間 @Temporal(TemporalType.TIMESTAMP) @Column(updatable = true) private Date modifyTime; @Column(length=255) private String remark; public String getName() { return name; } public void setName(String name) { this.name = name; } public UserGroup getParentUserGroup() { return parentUserGroup; } public void setParentUserGroup(UserGroup parentUserGroup) { this.parentUserGroup = parentUserGroup; } public Set<UserGroup> getChildrenUserGroups() { return childrenUserGroups; } public void setChildrenUserGroups(Set<UserGroup> childrenUserGroups) { this.childrenUserGroups = childrenUserGroups; } public User getTeamAdmin() { return teamAdmin; } public void setTeamAdmin(User teamAdmin) { this.teamAdmin = teamAdmin; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } public Integer getDeepLevel() { return deepLevel; } public void setDeepLevel(Integer deepLevel) { this.deepLevel = deepLevel; } public String getRecorder() { return recorder; } public void setRecorder(String recorder) { this.recorder = recorder; } public Date getRecordTime() { return recordTime; } public void setRecordTime(Date recordTime) { this.recordTime = recordTime; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
4.BaseUidEntity.java
@SuppressWarnings("serial") @MappedSuperclass public class BaseUidEntity implements Serializable,Cloneable{ @Id @GenericGenerator(name="uu_id", strategy="uuid") @GeneratedValue(generator="uu_id") private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } public Object clone() { Object o=null; try { o=(Object)super.clone(); } catch(CloneNotSupportedException e) { System.out.println(e.toString()); } return o; } }
5. UserDetail.java
package org.nercita.bcp.system.domain.reference; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; /** * 登錄用戶詳細信息 * @author zhangwenchao * */ public class UserDetail extends User{ private static final long serialVersionUID = -6889247576063361649L; private String userId; //用戶名(賬號) private String realName; //真實姓名 public UserDetail(String username, String password,Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); } public UserDetail(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } }
6.UserState.java
package org.nercita.bcp.system.domain.reference; public enum UserState { /** * 禁用(0) */ Disable { @Override public String getTitle() { return "Disable"; } }, /** * 啟用(1) */ Enable { @Override public String getTitle() { return "Enable"; } }; @Override public String toString() { return this.getTitle(); } public abstract String getTitle(); public int getValue() { return this.ordinal(); } }
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。