Spring+SpringMVC+Mybatis+shiro权限登录管理
来源:互联网 发布:众筹平台源码 编辑:程序博客网 时间:2024/06/06 02:18
最近公司要做一个新闻发布的系统,需要实现前台展示新闻页面,任何人都可以访问,后台需要权限登录,实现管理功能。我使用Spring 4.3.6.RELEASE,mybatis 3.4.2版本,shiro 1.2.3版本,maven搭建项目。
一. 环境搭建:
1. 开发工具:myeclipse 2014;
2. maven管理版本:apache-maven-3.3.9;
3. jdk 1.7.0_67
4. chrome浏览器
二:工程搭建:
工程结构:
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>com.gcx</groupId> <artifactId>iccndrc</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>iccndrc</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.3.6.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.4.2</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.22</slf4j.version> <log4j.version>1.2.17</log4j.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <shiro.version>1.2.3</shiro.version> </properties> <repositories> <repository> <id>nexus-repository</id> <name>MavenMirror</name> <url>http://192.168.100.181:9000/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>java</id> <name>java official repository</name> <url>http://download.java.net/maven/2/</url> </repository> </repositories> <!-- 配置部署的远程仓库 --> <distributionManagement> <snapshotRepository> <id>nexus-snapshots</id> <name>nexus distribution snapshot repository</name> <url>http://192.168.100.181:9000/nexus/content/repositories/snapshots/</url> </snapshotRepository> </distributionManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.10</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0.pr2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0.pr2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0.pr2</version> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context</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-oxm</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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</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-aop</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-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.28</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- JSTL标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- 格式化对象,方便输出日志 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.24</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.25-incubating</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0-b05</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.2-b02</version> </dependency> <dependency> <version>2.0.0.Alpha1</version> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency> <dependency> <version>5.4.0.Final</version> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring</artifactId> <version>5.22.0</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20140107</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.6</version> </dependency> <!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.9</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.3</version> </dependency> </dependencies> <build> <finalName>iccndrc</finalName> <defaultGoal>compile</defaultGoal> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> <compilerArguments> <extdirs>src\main\webapp\WEB-INF\lib</extdirs> </compilerArguments> </configuration> </plugin> </plugins> </build></project>
缓存配置ehcache.properties
<?xml version="1.0" encoding="UTF-8"?><!-- <ehcache name="shirocache"> --><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"> <diskStore path="java.io.tmpdir"/> <!-- 登录记录缓存 锁定10分钟 --> <cache name="passwordRetryCache" maxEntriesLocalHeap="200000" eternal="false" timeToIdleSeconds="360000" timeToLiveSeconds="0" overflowToDisk="true" statistics="true"> </cache> <cache name="authorizationCache" maxEntriesLocalHeap="200000" eternal="false" timeToIdleSeconds="360000" timeToLiveSeconds="0" overflowToDisk="true" statistics="true"> </cache> <cache name="authenticationCache" maxEntriesLocalHeap="200000" eternal="false" timeToIdleSeconds="360000" timeToLiveSeconds="0" overflowToDisk="true" statistics="true"> </cache> <cache name="shiro-activeSessionCache" maxEntriesLocalHeap="20000" eternal="false" timeToIdleSeconds="360000" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache></ehcache>
jdbc.properties
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/icc-ndrc?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=trueusername=rootpassword=isoftadmininitialSize=5maxActive=50maxIdle=10minIdle=1maxWait=10000
日志管理 log4j.properties
log4j.rootLogger=DEBUG,Console,Filelog4j.logger.org.apache.shiro=DEBUGlog4j.logger.net.sf.ehcache=DEBUGlog4j.logger.org.apache.commons=DEBUGlog4j.logger.org.springframework=DEBUGlog4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.Target=System.outlog4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.appender.Console.layout.ConversionPattern=[%c]%m%nlog4j.appender.File=org.apache.log4j.RollingFileAppender log4j.appender.File.File=D\:\\gcx_iccndrc_api.loglog4j.appender.File.MaxFileSize=10MBlog4j.appender.File.Threshold=ALLlog4j.appender.File.layout=org.apache.log4j.PatternLayoutlog4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
pageHelper 分页配置 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <plugins> <!-- com.github.pagehelper为PageHelper类所在包名 --> <plugin interceptor="com.github.pagehelper.PageHelper"> <property name="dialect" value="mysql"/> <!-- 该参数默认为false --> <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 --> <!-- 和startPage中的pageNum效果一样--> <property name="offsetAsPageNum" value="true"/> <!-- 该参数默认为false --> <!-- 设置为true时,使用RowBounds分页会进行count查询 --> <property name="rowBoundsWithCount" value="true"/> <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 --> <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)--> <property name="pageSizeZero" value="true"/> <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 --> <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 --> <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 --> <property name="reasonable" value="false"/> <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 --> <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 --> <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 --> <!-- 不理解该含义的前提下,不要随便复制该配置 --> <property name="params" value="pageNum=start;pageSize=limit;"/> </plugin></plugins></configuration>
jdbc事务管理 spring-activiti.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.100.181:3306/activiti" /> <property name="username" value="root" /> <property name="password" value="isoftadmin" /> <property name="defaultAutoCommit" value="false" /> </bean> <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration"> <property name="dataSource" ref="dataSource" /> <property name="databaseType" value="mysql"/> <property name="databaseSchemaUpdate" value="true" /> <property name="jobExecutorActivate" value="false" /> </bean> <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration" /> </bean> <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService" /> <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService" /> <bean id="taskService" factory-bean="processEngine" factory-method="getTaskService" /> <bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService" /> <bean id="managementService" factory-bean="processEngine" factory-method="getManagementService" /> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean></beans>
spring mvc 视图控制器,适配器,映射器配置 spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 它背后注册了很多用于解析注解的处理器,其中就包括<context:annotation-config/>配置的注解所使用的处理器 --> <!-- 所以配置了<context:component-scan base-package="">之后,便无需再配置<context:annotation-config> --> <context:component-scan base-package="com.gcx.iccndrc.controller"/> <!-- 启用SpringMVC的注解功能,它会自动注册HandlerMapping、HandlerAdapter、ExceptionResolver的相关实例 --> <mvc:annotation-driven/> <!-- 配置SpringMVC的视图解析器 --> <!-- 其viewClass属性的默认值就是org.springframework.web.servlet.view.JstlView --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 默认访问跳转到登录页面(即定义无需Controller的url<->view直接映射) --> <!-- <mvc:view-controller path="/" view-name="forward:/login_in.jsp"/> --> <!-- 由于web.xml中设置是:由SpringMVC拦截所有请求,于是在读取静态资源文件的时候就会受到影响(说白了就是读不到) --> <!-- 静态文件防止过滤 --> <mvc:default-servlet-handler/> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/error_fileupload.jsp页面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">WEB-INF/error_fileupload</prop> <!-- 处理其它异常(包括Controller抛出的) --> <prop key="java.lang.Throwable">WEB-INF/500</prop> </props> </property> </bean> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
数据库 mybatis 配置 spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.100.181:3306/icc-ndrc?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true" /> <property name="username" value="root" /> <property name="password" value="isoftadmin" /> <!-- 初始化连接大小 --> <property name="initialSize" value="1"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="2"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="2"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="1"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="10000"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/gcx/iccndrc/mapping/**/*.xml"></property> <!-- <property name="configLocation" value="classpath:mybatis-config.xml" /> --> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.gcx.iccndrc.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
Spring+shrio 权限配置 spring.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd "> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <context:property-placeholder location="classpath:config.properties" /> <!-- 自动扫描(自动注入) --> <context:component-scan base-package="com.gcx.iccndrc.service..*" ><!-- .service..* --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/userLogin/goTologin" /> <property name="unauthorizedUrl" value="/userLogin/toLogin" /> <property name="filterChainDefinitions"> <value> # static file chains /aa/** = anon /css/**=anon /Explain/** = anon /images/**=anon /js/**=anon /meeting/** = anon /model/** = anon /plugins/** = anon /WEB-INF/**=anon /index.jsp=anon /login_in.jsp =anon /userLogin/getCode=anon # user chain /indexLogin.jsp=user /sllr_indexLogin.jsp=user /slsh_indexLogin.jsp=user /userLogin/login=user /userLogin/toLogin=user </value> </property> </bean> <!-- 缓存管理器 使用Ehcache实现 --> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache.xml" /> </bean> <bean id="myRealm" class="com.gcx.iccndrc.security.MyRealm"> <property name="cachingEnabled" value="true" /> <property name="authenticationCachingEnabled" value="true" /> <property name="authenticationCacheName" value="authenticationCache" /> <property name="authorizationCachingEnabled" value="true" /> <property name="authorizationCacheName" value="authorizationCache" /> </bean> <!-- 会话ID生成器 --> <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" /> <!-- 会话Cookie模板 --> <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> <constructor-arg value="shiroId" /> <property name="httpOnly" value="true" /> <property name="maxAge" value="1800000" /> </bean> <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler"> <property name="interval" value="1800000" /> <property name="sessionManager" ref="shiroSessionManager" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <bean id="shiroSessionManager" class="com.gcx.iccndrc.security.DefaultWebSessionManager"> <property name="sessionDAO" ref="sessionDAO" /> <property name="deleteInvalidSessions" value="true" /> <property name="globalSessionTimeout" value="1800000" /> <property name="sessionIdCookieEnabled" value="true" /> <property name="sessionIdCookie" ref="sessionIdCookie" /> <property name="sessionValidationSchedulerEnabled" value="true" /> <property name="sessionValidationScheduler" ref="sessionValidationScheduler" /> </bean> <bean id="sessionDAO" class="com.gcx.iccndrc.security.EnterpriseCacheSessionDAO"> <property name="activeSessionsCacheName" value="shiro-activeSessionCache" /> <property name="sessionIdGenerator" ref="sessionIdGenerator" /> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm" /> <property name="sessionManager" ref="shiroSessionManager" /> <property name="cacheManager" ref="cacheManager" /> </bean></beans>
web.xml 配置
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>iccndrc</display-name> <!-- Web容器加载顺序ServletContext context-param listener filter servlet --> <!-- 指定Spring的配置文件 --> <!-- 否则Spring会默认从WEB-INF下寻找配置文件,contextConfigLocation属性是Spring内部固定的 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml;classpath:spring-mybatis.xml</param-value> </context-param> <context-param> <param-name>spring.profiles.active</param-name> <param-value>dev</param-value> </context-param> <context-param> <param-name>spring.profiles.default</param-name> <param-value>dev</param-value> </context-param> <context-param> <param-name>spring.liveBeansView.mbeanDomain</param-name> <param-value>dev</param-value> </context-param> <!-- 防止发生java.beans.Introspector内存泄露,应将它配置在ContextLoaderListener的前面 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 实例化Spring容器 --> <!-- 应用启动时,该监听器被执行,它会读取Spring相关配置文件,其默认会到WEB-INF中查找spring.xml--> <!-- http://starscream.iteye.com/blog/1107036 --> <!-- http://www.davenkin.me/post/2012-10-18/40039948363 --> <!-- WebApplicationContextUtils.getWebApplicationContext() --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解决乱码问题 --> <!-- forceEncoding默认为false,此时效果可大致理解为request.setCharacterEncoding("UTF-8") --> <!-- forceEncoding=true后,可大致理解为request.setCharacterEncoding("UTF-8")和response.setCharacterEncoding("UTF-8") --> <filter> <filter-name>encodingFilter</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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 --> <!-- 这里filter-name必须对应applicationContext.xml中定义的<bean id="shiroFilter"/> --> <!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 --> <!-- 通常会将此filter-mapping放置到最前面(即其他filter-mapping前面),以保证它是过滤器链中第一个起作用的 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 --> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 浏览器form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,spring3.0添加了一个过滤器, 可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT与DELETE请求,该过滤器为HiddenHttpMethodFilter。适用于restful风格 HiddenHttpMethodFilter必须作用于dispatcher前 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- SpringMVC核心分发器 --> <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:spring-mvc.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超时30分钟(零或负数表示会话永不超时) --> <session-config> <session-timeout>0</session-timeout> </session-config> <!-- 默认欢迎页 --> <!-- Servlet2.5中可直接在此处执行Servlet应用,如<welcome-file>servlet/InitSystemParamServlet</welcome-file> --> <!-- 这里使用了SpringMVC提供的<mvc:view-controller>标签,实现了首页隐藏的目的,详见applicationContext.xml --> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <error-page> <error-code>405</error-code> <location>/WEB-INF/405.html</location> </error-page> <error-page> <error-code>404</error-code> <location>/WEB-INF/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/WEB-INF/500.jsp</location> </error-page> </web-app>
登录controller
/** * <p>Title: UserLoginController</p> * <p>Description: </p> * <p>Company: GCX</p> * @author chengshen * @date 2017年5月3日 */@Controller@RequestMapping("/userLogin")public class UserLoginController { @Autowired IccUserMapper iccUserMapper; /** * 生成 * @param request * @param response * @throws IOException */ @RequestMapping(value="/getCode") public void getCode(HttpServletRequest request,HttpServletResponse response) throws IOException{ // 通知浏览器不要缓存 response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "-1"); CaptchaUtil util = CaptchaUtil.Instance(); // 将验证码输入到session中,用来验证 String code = util.getString(); request.getSession().setAttribute("code", code); // 输出打web页面 ImageIO.write(util.getImage(), "jpg", response.getOutputStream()); } /** * 跳转到登陆页面 * @param request * @return */ @RequestMapping(value = "/goTologin", method = RequestMethod.GET) public String login(HttpServletRequest request) { return "login_in"; } /** * 无权限访问页面 * @param request * @return */ @RequestMapping(value = "/goToIndex",method=RequestMethod.GET) public String goToIndexlogin(HttpServletRequest request) { return "index"; } /** * 登录 * * @param request * @param userName * @param password * @return */ @RequestMapping(value = "/login/{userName}/{password}/{remeberMe}", method = RequestMethod.POST) public @ResponseBody boolean login(HttpServletRequest request, @PathVariable("userName")String userName, @PathVariable("password")String password,@PathVariable("remeberMe")String remeberMe,HttpServletResponse response) { boolean callback = false; IccUser user = null; String MD5password = null; String cookiesUserName = null; Cookie[] cookies = null; cookies = request.getCookies(); String cookiesPassword = null; RecordSessionListener listener = new RecordSessionListener(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; if ("userName".equals(cookie.getName())) { cookiesUserName = cookie.getValue(); try { cookiesUserName = URLDecoder.decode(cookiesUserName, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } if ("password".equals(cookie.getName())) { cookiesPassword = cookie.getValue(); } } if (userName.equals(cookiesUserName) && password.equals(cookiesPassword)) { MD5password = cookiesPassword; } else { MD5password = MD5.MD5ofStr(password); } if(remeberMe.equals("yes")){ Cooick.rememberMe(request, response); } try { user = iccUserMapper.search(userName, MD5password); } catch (Exception e) { e.printStackTrace(); } if (user != null) { Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(user.getId().toString(), MD5password); subject.login(token); /* if (subject.isAuthenticated()) { callback= false; } else { callback = true; } */ callback = true; request.getSession().setAttribute(listener.loginFlag, user); request.getSession().setAttribute("user", user); } return callback; } /** * 校验验证码是否匹配成功 * * @param request * @param authcode * @return */ @RequestMapping(value = "/checkCode/{authcode}", method = RequestMethod.POST) public @ResponseBody boolean checkCode(HttpServletRequest request,@PathVariable("authcode") String authcode) { boolean message = false; HttpSession session = request.getSession(); String sessionCode = (String) session.getAttribute("code"); if (authcode.equalsIgnoreCase(sessionCode)) { message = true; } return message; } /** * 登录成功后跳转页面 * @param request * @return */ @RequestMapping(value="/toLogin",method=RequestMethod.GET) public ModelAndView goToLogin(HttpServletRequest request){ ModelAndView mav= new ModelAndView(); IccUser user = (IccUser) request.getSession().getAttribute("user"); mav.addObject("user", user); mav.setViewName("indexLogin"); return mav; } /** * 登录后退出功能 * @param request * @return */ @RequestMapping("toLogout") public ModelAndView toLogout(HttpServletRequest request){ ModelAndView mav= new ModelAndView(); request.getSession().removeAttribute("user"); HttpSession session =request.getSession(); IccUser user = (IccUser) session.getAttribute("user"); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(user.getId().toString(), MD5password); subject.logout(token); mav.setViewName("login_in"); return mav; } }
DefaultWebSessionManager session 管理类
/** * Web-application capable {@link org.apache.shiro.session.mgt.SessionManager SessionManager} implementation. * * @since 0.9 */public class DefaultWebSessionManager extends DefaultSessionManager implements WebSessionManager { private static final Logger log = LoggerFactory.getLogger(DefaultWebSessionManager.class); private Cookie sessionIdCookie; private boolean sessionIdCookieEnabled; public DefaultWebSessionManager() { Cookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); cookie.setHttpOnly(true); //more secure, protects against XSS attacks this.sessionIdCookie = cookie; this.sessionIdCookieEnabled = true; } public Cookie getSessionIdCookie() { return sessionIdCookie; } @SuppressWarnings({"UnusedDeclaration"}) public void setSessionIdCookie(Cookie sessionIdCookie) { this.sessionIdCookie = sessionIdCookie; } public boolean isSessionIdCookieEnabled() { return sessionIdCookieEnabled; } @SuppressWarnings({"UnusedDeclaration"}) public void setSessionIdCookieEnabled(boolean sessionIdCookieEnabled) { this.sessionIdCookieEnabled = sessionIdCookieEnabled; } private void storeSessionId(Serializable currentId, HttpServletRequest request, HttpServletResponse response) { if (currentId == null) { String msg = "sessionId cannot be null when persisting for subsequent requests."; throw new IllegalArgumentException(msg); } Cookie template = getSessionIdCookie(); Cookie cookie = new SimpleCookie(template); String idString = currentId.toString(); cookie.setValue(idString); cookie.saveTo(request, response); log.trace("Set session ID cookie for session with id {}", idString); } private void removeSessionIdCookie(HttpServletRequest request, HttpServletResponse response) { getSessionIdCookie().removeFrom(request, response); } private String getSessionIdCookieValue(ServletRequest request, ServletResponse response) { if (!isSessionIdCookieEnabled()) { log.debug("Session ID cookie is disabled - session id will not be acquired from a request cookie."); return null; } if (!(request instanceof HttpServletRequest)) { log.debug("Current request is not an HttpServletRequest - cannot get session ID cookie. Returning null."); return null; } HttpServletRequest httpRequest = (HttpServletRequest) request; return getSessionIdCookie().readValue(httpRequest, WebUtils.toHttp(response)); } private Serializable getReferencedSessionId(ServletRequest request, ServletResponse response) { String id = getSessionIdCookieValue(request, response); if (id != null) { request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE); } else { //not in a cookie, or cookie is disabled - try the request URI as a fallback (i.e. due to URL rewriting): //try the URI path segment parameters first: id = getUriPathSegmentParamValue(request, ShiroHttpSession.DEFAULT_SESSION_ID_NAME); if (id == null) { //not a URI path segment parameter, try the query parameters: String name = getSessionIdName(); id = request.getParameter(name); if (id == null) { //try lowercase: id = request.getParameter(name.toLowerCase()); } } if (id != null) { request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, ShiroHttpServletRequest.URL_SESSION_ID_SOURCE); } } if (id != null) { request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id); //automatically mark it valid here. If it is invalid, the //onUnknownSession method below will be invoked and we'll remove the attribute at that time. request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE); } return id; } //SHIRO-351 //also see http://cdivilly.wordpress.com/2011/04/22/java-servlets-uri-parameters/ //since 1.2.2 private String getUriPathSegmentParamValue(ServletRequest servletRequest, String paramName) { if (!(servletRequest instanceof HttpServletRequest)) { return null; } HttpServletRequest request = (HttpServletRequest)servletRequest; String uri = request.getRequestURI(); if (uri == null) { return null; } int queryStartIndex = uri.indexOf('?'); if (queryStartIndex >= 0) { //get rid of the query string uri = uri.substring(0, queryStartIndex); } int index = uri.indexOf(';'); //now check for path segment parameters: if (index < 0) { //no path segment params - return: return null; } //there are path segment params, let's get the last one that may exist: final String TOKEN = paramName + "="; uri = uri.substring(index+1); //uri now contains only the path segment params //we only care about the last JSESSIONID param: index = uri.lastIndexOf(TOKEN); if (index < 0) { //no segment param: return null; } uri = uri.substring(index + TOKEN.length()); index = uri.indexOf(';'); //strip off any remaining segment params: if(index >= 0) { uri = uri.substring(0, index); } return uri; //what remains is the value } //since 1.2.1 private String getSessionIdName() { String name = this.sessionIdCookie != null ? this.sessionIdCookie.getName() : null; if (name == null) { name = ShiroHttpSession.DEFAULT_SESSION_ID_NAME; } return name; } protected Session createExposedSession(Session session, SessionContext context) { if (!WebUtils.isWeb(context)) { return super.createExposedSession(session, context); } ServletRequest request = WebUtils.getRequest(context); ServletResponse response = WebUtils.getResponse(context); SessionKey key = new WebSessionKey(session.getId(), request, response); return new DelegatingSession(this, key); } protected Session createExposedSession(Session session, SessionKey key) { if (!WebUtils.isWeb(key)) { return super.createExposedSession(session, key); } ServletRequest request = WebUtils.getRequest(key); ServletResponse response = WebUtils.getResponse(key); SessionKey sessionKey = new WebSessionKey(session.getId(), request, response); return new DelegatingSession(this, sessionKey); } /** * Stores the Session's ID, usually as a Cookie, to associate with future requests. * * @param session the session that was just {@link #createSession created}. */ @Override protected void onStart(Session session, SessionContext context) { super.onStart(session, context); if (!WebUtils.isHttp(context)) { log.debug("SessionContext argument is not HTTP compatible or does not have an HTTP request/response " + "pair. No session ID cookie will be set."); return; } HttpServletRequest request = WebUtils.getHttpRequest(context); HttpServletResponse response = WebUtils.getHttpResponse(context); if (isSessionIdCookieEnabled()) { Serializable sessionId = session.getId(); storeSessionId(sessionId, request, response); } else { log.debug("Session ID cookie is disabled. No cookie has been set for new session with id {}", session.getId()); } request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE); } @Override public Serializable getSessionId(SessionKey key) { Serializable id = super.getSessionId(key); if (id == null && WebUtils.isWeb(key)) { ServletRequest request = WebUtils.getRequest(key); ServletResponse response = WebUtils.getResponse(key); id = getSessionId(request, response); } return id; } protected Serializable getSessionId(ServletRequest request, ServletResponse response) { return getReferencedSessionId(request, response); } @Override protected void onExpiration(Session s, ExpiredSessionException ese, SessionKey key) { super.onExpiration(s, ese, key); onInvalidation(key); } @Override protected void onInvalidation(Session session, InvalidSessionException ise, SessionKey key) { super.onInvalidation(session, ise, key); onInvalidation(key); } private void onInvalidation(SessionKey key) { ServletRequest request = WebUtils.getRequest(key); if (request != null) { request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID); } if (WebUtils.isHttp(key)) { log.debug("Referenced session was invalid. Removing session ID cookie."); removeSessionIdCookie(WebUtils.getHttpRequest(key), WebUtils.getHttpResponse(key)); } else { log.debug("SessionKey argument is not HTTP compatible or does not have an HTTP request/response " + "pair. Session ID cookie will not be removed due to invalidated session."); } } @Override protected void onStop(Session session, SessionKey key) { super.onStop(session, key); if (WebUtils.isHttp(key)) { HttpServletRequest request = WebUtils.getHttpRequest(key); HttpServletResponse response = WebUtils.getHttpResponse(key); log.debug("Session has been stopped (subject logout or explicit stop). Removing session ID cookie."); removeSessionIdCookie(request, response); } else { log.debug("SessionKey argument is not HTTP compatible or does not have an HTTP request/response " + "pair. Session ID cookie will not be removed due to stopped session."); } } /** * This is a native session manager implementation, so this method returns {@code false} always. * * @return {@code false} always * @since 1.2 */ public boolean isServletContainerSessions() { return false; } @Override protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException { Serializable sessionId = getSessionId(sessionKey); if (sessionId == null) { log.debug("Unable to resolve session ID from SessionKey [{}]. Returning null to indicate a " + "session could not be found.", sessionKey); return null; } Session s = retrieveSessionFromDataSource(sessionId); if (s == null) { //session ID was provided, meaning one is expected to be found, but we couldn't find one: String msg = "Could not find session with ID [" + sessionId + "]"; System.out.println(msg); } return s; }}
EnterpriseCacheSessionDAO 缓存管理类(Spring.xml 可以配置 )
/** * * @since 1.0 */public class EnterpriseCacheSessionDAO extends CachingSessionDAO { public EnterpriseCacheSessionDAO() { setCacheManager(new AbstractCacheManager() { @Override protected Cache<Serializable, Session> createCache(String name) throws CacheException { return new MapCache<Serializable, Session>(name, new ConcurrentHashMap<Serializable, Session>()); } }); } protected Serializable doCreate(Session session) { Serializable sessionId = generateSessionId(session); assignSessionId(session, sessionId); return sessionId; } @Override public Session readSession(Serializable sessionId) throws UnknownSessionException { Session s = super.getCachedSession(sessionId); if (s == null) { // s = super.readSession(sessionId); System.out.println("There is no session with id [" + sessionId + "]"); } return s; } protected void doUpdate(Session session) { // does nothing - parent class persists to cache. } @Override protected void doDelete(Session session) { Collection<Session> Sessions = super.getActiveSessions(); if (Sessions.contains(session)) { Sessions.remove(session); } } @Override protected Session doReadSession(Serializable sessionId) { Session s = super.getCachedSession(sessionId); if (s == null) { // s = super.readSession(sessionId); System.out.println("There is no session with id [" + sessionId + "]"); } return s; }}
shrio 实现类(必须配置 )
public class MyRealm extends AuthorizingRealm { @Autowired RolePermitMapper rolePermitMapper;//角色与权限对应表 /** * 添加 <sh:hasPermission> jsp 标签 对 or and not操作符的支持,以下为关键字 or and not * */ private static final String OR_OPERATOR = " or "; private static final String AND_OPERATOR = " and "; private static final String NOT_OPERATOR = "not "; /** * 为当前登录的Subject授予角色和权限 * * 该方法的调用时机为需授权资源被访问时 每次访问需授权资源时都会执行该方法中的逻辑,如果用户授权内容被缓存,则在不会重复调用该方法 * */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { List<String> permissionList = new ArrayList<String>(); List<RolePermitKey> roles =null;//角色与权限为一对多关系 if (null != principals) { Integer roleId = new Integer(principals.getPrimaryPrincipal().toString()); if(roleId!=null){ try { roles = rolePermitMapper.selectRoleByUserId(roleId); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { throw new AuthorizationException(); } if(roles!=null){ for(RolePermitKey p:roles){ permissionList.add(p.getPermitId().toString()); } } SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); //simpleAuthorInfo.addRoles(roleList);//角色集合 simpleAuthorInfo.addStringPermissions(permissionList);//权限集合 return simpleAuthorInfo; } /** * 验证当前登录的Subject 在subject.login(AuthenticationToken)时调用该方法 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { // 获取基于用户名和密码的令牌 UsernamePasswordToken token = (UsernamePasswordToken) authcToken; AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName()); return authcInfo; } /** * 支持or and not 关键词 不支持and or混用 * * @param principals * @param permission * @return */ @Override public boolean isPermitted(PrincipalCollection principals, String permission) { if (permission.contains(OR_OPERATOR)) { String[] permissions = permission.split(OR_OPERATOR); for (String orPermission : permissions) { if (isPermittedWithNotOperator(principals, orPermission)) { return true; } } return false; } else if (permission.contains(AND_OPERATOR)) { String[] permissions = permission.split(AND_OPERATOR); for (String orPermission : permissions) { if (!isPermittedWithNotOperator(principals, orPermission)) { return false; } } return true; } else { return isPermittedWithNotOperator(principals, permission); } } private boolean isPermittedWithNotOperator(PrincipalCollection principals, String permission) { if (permission.startsWith(NOT_OPERATOR)) { return !super.isPermitted(principals, permission.substring(NOT_OPERATOR.length())); } else { return super.isPermitted(principals, permission); } } @Override public void clearCachedAuthorizationInfo(PrincipalCollection principals) { super.clearCachedAuthorizationInfo(principals); } @Override public void clearCachedAuthenticationInfo(PrincipalCollection principals) { super.clearCachedAuthenticationInfo(principals); } @Override public void clearCache(PrincipalCollection principals) { super.clearCache(principals); } public void clearAllCachedAuthorizationInfo() { getAuthorizationCache().clear(); } public void clearAllCachedAuthenticationInfo() { getAuthenticationCache().clear(); } public void clearAllCache() { clearAllCachedAuthenticationInfo(); clearAllCachedAuthorizationInfo(); }}
RolePermitMapper
<resultMap id="BaseResultMap" type="com.gcx.iccndrc.model.RolePermitKey" > <id column="ROLE_ID" property="roleId" jdbcType="INTEGER" /> <id column="PERMIT_ID" property="permitId" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List">ROLE_ID,PERMIT_ID</sql> <select id="selectRoleByUserId" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from ROLE_PERMIT p WHERE p.ROLE_ID=(SELECT r.ACCOUNT FROM ICC_USER r WHERE r.ID=#{roleId}) </select>
Cooick 类
public static void rememberMe(HttpServletRequest request, HttpServletResponse response) { String MD5Password = null; // 获得登录名和密码 String name = request.getParameter("userName"); String password = request.getParameter("password"); if (password.length() == 32) { MD5Password = password; } else { MD5Password = MD5.MD5ofStr(password); } String remeberMe = request.getParameter("remeberMe"); // 处理name的编码格式,处理中文 try { name = URLEncoder.encode(name, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Cookie cookieName = new Cookie("userName", name); Cookie cookiePassword = new Cookie("password", MD5Password); // 设置Cookie的有效路径,路径为项目根目录 cookieName.setPath(request.getContextPath() + "/"); cookiePassword.setPath(request.getContextPath() + "/"); if (remeberMe != null && remeberMe.equals("yes")) { cookieName.setMaxAge(7 * 24 * 60 * 60);// 一个星期 cookiePassword.setMaxAge(7 * 24 * 60 * 60); } // 清空Cookie的有效时长 else { cookieName.setMaxAge(0); cookiePassword.setMaxAge(0); } // 将Cookie存放到response对象中 response.addCookie(cookieName); response.addCookie(cookiePassword); }
pagehelper分页类
public class PagedResult<T> implements Serializable { private static final long serialVersionUID = -8703306679470898754L; private List<T> dataList;//数据 private long pageNo;//当前页 private long pageSize;//条数 private long total;//总条数 private long pages;//总页面数目 public List<T> getDataList() { return dataList; } public void setDataList(List<T> dataList) { this.dataList = dataList; } public long getPageNo() { return pageNo; } public void setPageNo(long pageNo) { this.pageNo = pageNo; } public long getPageSize() { return pageSize; } public void setPageSize(long pageSize) { this.pageSize = pageSize; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public long getPages() { return pages; } public void setPages(long pages) { this.pages = pages; }}
pagehelper 集合类
public class BeanUtil { public static <T> PagedResult<T> toPagedResult(List<T> datas) { PagedResult<T> result = new PagedResult<T>(); if (datas instanceof Page) { Page<T> page = (Page<T>) datas; result.setPageNo(page.getPageNum()); result.setPageSize(page.getPageSize()); result.setDataList(page.getResult()); result.setTotal(page.getTotal()); result.setPages(page.getPages()); } else { result.setPageNo(1); result.setPageSize(datas.size()); result.setDataList(datas); result.setTotal(datas.size()); } return result; }}
动态验证码类 CaptchaUtil
public class CaptchaUtil { private BufferedImage image;// 图像 private String str;// 验证码 private static char code[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789".toCharArray(); public static final String SESSION_CODE_NAME="code"; private CaptchaUtil() { init();// 初始化属性 } /* * 取得RandomNumUtil实例 */ public static CaptchaUtil Instance() { return new CaptchaUtil(); } /* * 取得验证码图片 */ public BufferedImage getImage() { return this.image; } /* * 取得图片的验证码 */ public String getString() { return this.str; } private void init() { // 在内存中创建图象 int width = 98, height = 40; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); // 生成随机类 Random random = new Random(); // 设定背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设定字体 g.setFont(new Font("Times New Roman", Font.PLAIN, 30)); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } // 取随机产生的认证码(4位数字) String sRand = ""; for (int i = 0; i < 4; i++) { String rand = String.valueOf(code[random.nextInt(code.length)]); sRand += rand; // 将认证码显示到图象中 g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.drawString(rand, 18 * i + 6, 30); } // 赋值验证码 this.str = sRand; // 图象生效 g.dispose(); // ByteArrayInputStream input = null; // ByteArrayOutputStream output = new ByteArrayOutputStream(); // try { // ImageOutputStream imageOut = ImageIO.createImageOutputStream(output); // ImageIO.write(image, "JPEG", imageOut); // imageOut.close(); // input = new ByteArrayInputStream(output.toByteArray()); // } catch (Exception e) { // System.out.println("验证码图片产生出现错误:" + e.toString()); // } // this.image = input this.image = image;/* 赋值图像 */ } /* * 给定范围获得随机颜色 */ private Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } public static void main(String[] args) { System.out.println(Math.random()); }}
登录login_in.jsp关键代码
<!--content s--> <div class="log_b"> <div class="log_main clearFix"> <div class="log_b_l fl"> <img src="<%=basePath%>images/log_left2.png" alt="" title="" /> </div> <div class="log_b_r fr"> <div class="log_tit clearFix"> <span class="fl">账户登录</span> <span class="fr log_t_span">没有账号?<a href="javascript:;">马上注册!</a></span> </div> <ul> <li> <input type="text" class="inp_text" placeholder="账号/用户名/手机/邮箱" id="userName" > <span></span> <!--用户信息输入有误时--> <!--<em>请输入用户名</em>--> </li> <li><input type="password" class="inp_text" placeholder="6-20位字母数字或特殊符号" id="password"><span class="te"></span></li> <li><input type="text" class="inp_text inp_text1 fl" placeholder="请输入验证码" id="authcode" > <a id="checkCode" class="yan"> <img id="imageCode" onclick="checkcode()" src=""/></a> </li> </ul> <div class="log_for clearFix"> <span class="fl"><input type="checkbox" name="remeberMe" value="yes"/><label for="remember">记住密码</label></span> <span class="fr"><a href="javascript:;">忘记登录密码?</a></span> </div> <a href="javascript:;" class="log_sub" onclick="toLogin()" id="loginIn">登录</a> </div> </div> </div> <script type="text/javascript" src="<%=request.getContextPath()%>/plugins/layer/layer.js"></script> <script> //登录 function toLogin(){ var path="<%=basePath%>"; var userName=$("#userName").val(); var password=$("#password").val(); var checkNum=$("#checkNum").val(); var remeberMe=$("input[name='remeberMe']:checked").val(); if(userName==null||userName==undefined||userName==""){ layer.tips('请输入用户名!', '#userName',{tips: 3}); }else if(password==null||password==undefined||password==""){ layer.tips('请输入密码!', '#password',{tips: 3}); }else{ if(check_code()){ $.ajax({ url: '<%=request.getContextPath()%>/userLogin/login/'+userName+"/"+password+"/"+remeberMe, type: "post", dataType: "json", success: function(data) { //请求成功时处理 if(data){ window.location.href="<%=request.getContextPath()%>/userLogin/toLogin"; }else{ layer.alert("用户名或密码有误!",{ icon: 1, skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则,去这里查阅 }) } } }); }else{ layer.tips('验证码有误请重新输入!', '#authcode',{tips: [3, '#c00']}); } } } //验证验证码 function check_code(){ var message = false; var authcode=$.trim($("#authcode").val()); if(authcode==null||authcode==undefined||authcode==""){ layer.tips('请输入验证码!', '#authcode',{tips:3}); }else{ $.ajax({ url:'<%=request.getContextPath()%>/userLogin/checkCode/'+authcode, type:"post", async:false, dataType:"json", success:function(data){ message=data; } }) } return message; }; //回车登录 $(function(){ document.onkeydown=function(event){ var e = event || window.event || arguments.callee.caller.arguments[0]; if(e && e.keyCode==13){ // enter 键 toLogin(); } }; }) </script> <script type="text/javascript"> var basePath = "<%=basePath%>"; $(function(){ checkcode(); }); function checkcode(){ var XMLHttp = null; if (window.XMLHttpRequest) { XMLHttp = new XMLHttpRequest() } else if (window.ActiveXObject) { XMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); } XMLHttp.onreadystatechange = function() { if (XMLHttp.readyState == 4) { document.getElementById("imageCode").src = basePath + "userLogin/getCode?" + new Date();//改变验证码图片 } } //将请求发送出去 //加上new Date()防止浏览器缓存,不重新发送请求 XMLHttp.open("GET", basePath + "userLogin/getCode?" + new Date(), true); XMLHttp.send(null); } </script>
登录效果
2 0
- Spring+SpringMVC+Mybatis+shiro权限登录管理
- spring+springmvc+mybatis shiro权限管理系统demo mysql数据库
- shiro-springmvc-mybatis登录认证 权限控制
- springmvc-spring-mybatis-shiro-easyui权限系统
- Spring+SpringMVC+Shiro+Redis+Maven权限管理
- Spring+Mybatis+Shiro开发权限管理系统
- spring-shiro 实现权限管理,单点登录
- spring,springmvc,mybatis,shiro,redis实现的通用权限管理系统
- 【Shiro】SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- SpringMVC+Shiro权限管理
- 国家法定假日webservice自己写的工具类,需要数据库及tomcat7,jdk1.6环境
- Android获取系统资源的组件id
- react native Image 使用详解
- JavaScript网页小时钟
- 【springmvc 5】---怎么配置springmvc.xml?
- Spring+SpringMVC+Mybatis+shiro权限登录管理
- Redis Sorted Set类型介绍
- jetson tx1 上运行sudo rosdep init失败解决方法
- 微服务架构之spring cloud (前言)
- Java关键字transient和volatile
- Mac OS X mkdir: /home/test: Operation not supported
- android 蓝牙
- 机器人可到达的总格数
- 1027. 打印沙漏(20)