欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring security实现权限管理示例

程序员文章站 2024-03-08 10:03:04
spring security实现权限管理示例,具体如下: 1、配置文件 1、pom.xml

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(); 
  } 
 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。