SSM+Redis+Shiro+Maven框架搭建及集成应用
引文:
本文主要讲述项目框架搭建时的一些简单的使用配置,教你如何快速进行项目框架搭建。
技术: Spring+SpringMVC+Mybatis+Redis+Shiro+Maven mybatis、redis都是使用spring集成
技术介绍就不再讲述了,话不多说,急忙上代码了。
1、新建Web项目使用Maven 进行项目管理
具体步骤不进行讲述。。。。
主要配置 web.xml 文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 version="3.0"> 6 7 <display-name></display-name> 8 9 <welcome-file-list> 10 <welcome-file>index</welcome-file> 11 </welcome-file-list> 12 13 <error-page> 14 <error-code>404</error-code> 15 <location>/WEB-INF/jsp/other/404.jsp</location> 16 </error-page> 17 <error-page> 18 <error-code>500</error-code> 19 <location>/WEB-INF/jsp/other/500.jsp</location> 20 </error-page> 21 22 <context-param> 23 <param-name>contextConfigLocation</param-name> 24 <param-value>classpath:applicationContext.xml</param-value> 25 </context-param> 26 27 <listener> 28 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 29 </listener> 30 <listener> 31 <listener-class>com.idbk.eastevs.webapi.ApplicationListener</listener-class> 32 </listener> 33 34 <!-- shiro 过滤器 --> 35 <filter> 36 <filter-name>shiroFilter</filter-name> 37 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 38 <!-- 设置true由servlet容器控制filter的生命周期 --> 39 <init-param> 40 <param-name>targetFilterLifecycle</param-name> 41 <param-value>true</param-value> 42 </init-param> 43 </filter> 44 <filter-mapping> 45 <filter-name>shiroFilter</filter-name> 46 <url-pattern>/*</url-pattern> 47 </filter-mapping> 48 49 <!-- springMVC编码过滤器 --> 50 <filter> 51 <filter-name>CharacterEncodingFilter</filter-name> 52 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 53 <init-param> 54 <param-name>encoding</param-name> 55 <param-value>utf-8</param-value> 56 </init-param> 57 <init-param> 58 <param-name>forceEncoding</param-name> 59 <param-value>true</param-value> 60 </init-param> 61 </filter> 62 <filter-mapping> 63 <filter-name>CharacterEncodingFilter</filter-name> 64 <url-pattern>/*</url-pattern> 65 </filter-mapping> 66 67 <!-- xss攻击防御过滤器 --> 68 <filter> 69 <filter-name>MyXssFilter</filter-name> 70 <filter-class>com.idbk.eastevs.webapi.filter.MyXssFilter</filter-class> 71 </filter> 72 <filter-mapping> 73 <filter-name>MyXssFilter</filter-name> 74 <url-pattern>/*</url-pattern> 75 </filter-mapping> 76 77 <servlet-mapping> 78 <servlet-name>default</servlet-name> 79 <url-pattern>*.htm</url-pattern> 80 <url-pattern>*.html</url-pattern> 81 <url-pattern>*.js</url-pattern> 82 <url-pattern>*.css</url-pattern> 83 <url-pattern>*.json</url-pattern> 84 <url-pattern>*.svg</url-pattern> 85 <url-pattern>*.txt</url-pattern> 86 <url-pattern>*.tiff</url-pattern> 87 <url-pattern>*.gif</url-pattern> 88 <url-pattern>*.ico</url-pattern> 89 <url-pattern>*.jpg</url-pattern> 90 <url-pattern>*.jpeg</url-pattern> 91 <url-pattern>*.png</url-pattern> 92 <url-pattern>*.ttf</url-pattern> 93 <url-pattern>*.woff</url-pattern> 94 <url-pattern>*.woff2</url-pattern> 95 <url-pattern>*.eot</url-pattern> 96 <url-pattern>/include/*</url-pattern> 97 </servlet-mapping> 98 99 <servlet> 100 <servlet-name>springMVC</servlet-name> 101 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 102 <init-param> 103 <param-name>contextConfigLocation</param-name> 104 <param-value>classpath:beans-springmvc.xml</param-value> 105 </init-param> 106 <load-on-startup>1</load-on-startup> 107 </servlet> 108 <servlet-mapping> 109 <servlet-name>springMVC</servlet-name> 110 <url-pattern>/</url-pattern> 111 </servlet-mapping> 112 </web-app>
2、Spring 配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:mvc="http://www.springframework.org/schema/mvc" 7 xmlns:task="http://www.springframework.org/schema/task" 8 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 9 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd 10 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 11 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> 12 13 14 <import resource="classpath*:/beans-mybatis.xml" /> 15 16 <import resource="classpath*:/beans-jedis.xml" /> 17 18 <import resource="classpath*:/beans-shiro.xml" /> 19 20 <context:component-scan base-package="com.idbk.eastevs.webapi"></context:component-scan> 21 <context:component-scan base-package="com.idbk.eastevs.webapi.service.impl"></context:component-scan> 22 <context:component-scan base-package="com.idbk.eastevs.webapi.server"></context:component-scan> 23 24 <bean id="app" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 25 <property name="locations"> 26 <array> 27 <value>classpath:app.properties</value> 28 </array> 29 </property> 30 </bean> 31 32 <bean 33 class="com.idbk.eastevs.webapi.App"> 34 </bean> 35 36 <!-- 开启定时任务注解识别 --> 37 <task:annotation-driven/> 38 </beans>
3、SpringMVC配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.0.xsd 9 http://www.springframework.org/schema/mvc 10 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 11 12 13 <!-- 配置自动扫描的包 --> 14 <context:component-scan base-package="com.idbk.eastevs.webapi.controller"></context:component-scan> 15 <context:component-scan base-package="com.idbk.eastevs.webapi.controller.*"></context:component-scan> 16 17 <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 --> 18 <bean 19 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 20 <property name="prefix" value="/WEB-INF/jsp/"></property> 21 <property name="suffix" value=".jsp"></property> 22 </bean> 23 24 <!-- 如果springMVC拦截了根目录,这还需要放行资源目录 <mvc:resources mapping="/include/**" location="/include/" 25 /> --> 26 27 <!-- 配置文件上传 --> 28 <bean id="multipartResolver" 29 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 30 <property name="maxUploadSize" value="104857600" /> 31 <property name="maxInMemorySize" value="4096" /> 32 <property name="defaultEncoding" value="UTF-8"></property> 33 </bean> 34 35 <mvc:annotation-driven> 36 <!-- 消息转换器 --> 37 <mvc:message-converters register-defaults="true"> 38 <bean class="org.springframework.http.converter.StringHttpMessageConverter"> 39 <property name="supportedMediaTypes" value="text/html;charset=UTF-8" /> 40 </bean> 41 </mvc:message-converters> 42 </mvc:annotation-driven> 43 44 <!-- 配置请求拦截器 --> 45 <mvc:interceptors> 46 <!-- 多个拦截器,顺序执行 --> 47 <!-- 中电联、曹操专车拦截器 --> 48 <mvc:interceptor> 49 <!-- /**的意思是所有文件夹及里面的子文件夹 /*是所有文件夹,不含子文件夹 /是web项目的根目录 --> 50 <!-- <mvc:mapping path="/*/caocao/**" /> 51 <mvc:mapping path="/caocao/**" /> --> 52 <mvc:mapping path="/**" /> 53 <!-- 不拦截的地址 --> 54 <mvc:exclude-mapping path="/login" /> 55 <bean id="CoreInterceptor" class="com.idbk.eastevs.webapi.CoreInterceptor" /> 56 </mvc:interceptor> 57 </mvc:interceptors> 58 </beans>
4、Spring-Mybatis配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd 7 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> 8 9 <context:component-scan base-package="com.idbk.eastevs.webapi.pojo" /> 10 <!-- 加载配置文件 --> 11 <context:property-placeholder location="classpath*:jdbc.properties" 12 ignore-unresolvable="true" /> 13 14 <!-- 配置数据源 --> 15 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 16 destroy-method="close"> 17 <property name="driverClassName" value="${jdbc.driverClassName}" /> 18 <property name="url" value="${jdbc.url}" /> 19 <property name="username" value="${jdbc.username}" /> 20 <property name="password" value="${jdbc.password}" /> 21 22 <!-- 可同时连接的最大的连接数 --> 23 <property name="maxActive" value="${jdbc.maxActive}" /> 24 <!-- 最大的空闲的连接数 --> 25 <property name="maxIdle" value="${jdbc.maxIdle}" /> 26 <!-- 最小的空闲的连接数,低于这个数量会被创建新的连接,默认为0 --> 27 <property name="minIdle" value="${jdbc.minIdle}" /> 28 <!-- 连接池启动时创建的初始化连接数量,默认值为0 --> 29 <property name="initialSize" value="${jdbc.initialSize}" /> 30 <!-- 等待连接超时时间,毫秒,默认为无限 --> 31 <property name="maxWait" value="${jdbc.maxWait}" /> 32 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> 33 <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> 34 <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> 35 <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> 36 <!-- 打开removeAbandoned功能 --> 37 <property name="removeAbandoned" value="${jdbc.removeAbandoned}" /> 38 <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" /> 39 <property name="validationQuery" value="SELECT 1" /> 40 </bean> 41 42 <!-- 会话工厂bean sqlSessionFactoryBean --> 43 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 44 <property name="dataSource" ref="dataSource" /> 45 <!-- 扫描mybatis配置文件 --> 46 <property name="configLocation" value="classpath:mybatis-config.xml"></property> 47 <!-- 别名 --> 48 <property name="typeAliasesPackage" value="com.idbk.eastevs.dal.entity"></property> 49 <!-- sql映射文件路径 --> 50 <property name="mapperLocations" 51 value="classpath*:com/idbk/eastevs/dal/entity/mapper/*Mapper.xml"></property> 52 </bean> 53 54 <!-- 自动扫描对象关系映射 --> 55 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 56 <!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去 --> 57 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 58 <!-- 指定要自动扫描接口的基础包,实现接口 --> 59 <property name="basePackage" value="com.idbk.eastevs.dal.entity.mapper" /> 60 </bean> 61 62 <!-- 声明式事务管理 --> 63 <!--定义事物管理器,由spring管理事务 --> 64 <bean id="transactionManager" 65 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 66 <property name="dataSource" ref="dataSource" /> 67 </bean> 68 69 <!--支持注解驱动的事务管理,指定事务管理器 --> 70 <tx:annotation-driven transaction-manager="transactionManager" /> 71 72 <!-- 自定义sqlSessionFactory 工具类 --> 73 <bean id="SqlManager" class="com.idbk.eastevs.dal.SqlManager"> 74 <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 75 </bean> 76 </beans>
5、Mybatis配置文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3 <configuration> 4 <settings> 5 <!-- 打印操作日志 --> 6 <setting name="logImpl" value="LOG4J" /> 7 </settings> 8 9 <!-- 分页插件 --> 10 <plugins> 11 <!-- com.github.pagehelper为PageHelper类所在包名 --> 12 <plugin interceptor="com.github.pagehelper.PageInterceptor"> 13 <!-- 方言 --> 14 <property name="helperDialect" value="mysql" /> 15 <!-- 该参数默认为false,设置为true时,使用RowBounds分页会进行count查询 --> 16 <!-- <property name="rowBoundsWithCount" value="true" /> --> 17 </plugin> 18 </plugins> 19 </configuration>
6、Spring-Redis配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd" 7 default-lazy-init="false"> 8 9 <!-- 加载配置文件 --> 10 <context:property-placeholder location="classpath*:jedis.properties" ignore-unresolvable="true"/> 11 12 <!-- redis数据源 --> 13 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> 14 <!-- 保留空闲连接数 --> 15 <property name="minIdle" value="${redis.minIdle}" /> 16 <!-- 最大空连接数 --> 17 <property name="maxTotal" value="${redis.maxTotal}" /> 18 <!-- 最大等待时间 --> 19 <property name="maxWaitMillis" value="${redis.maxWaitMillis}" /> 20 <!-- 连接超时时是否阻塞,false时报异常,ture阻塞直到超时, 默认true --> 21 <property name="blockWhenExhausted" value="${redis.blockWhenExhausted}" /> 22 <!-- 返回连接时,检测连接是否成功 --> 23 <property name="testOnBorrow" value="${redis.testOnBorrow}" /> 24 </bean> 25 26 <!-- Spring-redis连接池管理工厂 --> 27 <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> 28 <!-- IP地址 --> 29 <property name="hostName" value="${redis.host}" /> 30 <!-- 端口号 --> 31 <property name="port" value="${redis.port}" /> 32 <!-- 密码 --> 33 <property name="password" value="${redis.password}" /> 34 <!-- 超时时间 默认2000--> 35 <property name="timeout" value="${redis.timeout}" /> 36 <!-- 连接池配置引用 --> 37 <property name="poolConfig" ref="poolConfig" /> 38 <!-- usePool:是否使用连接池 --> 39 <property name="usePool" value="true"/> 40 </bean> 41 42 <!-- redis 操作模板,集成序列化和连接管理 --> 43 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> 44 <property name="connectionFactory" ref="jedisConnectionFactory" /> 45 <property name="keySerializer"> 46 <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 47 </property> 48 <property name="valueSerializer"> 49 <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 50 </property> 51 <property name="hashKeySerializer"> 52 <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 53 </property> 54 <property name="hashValueSerializer"> 55 <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 56 </property> 57 <!--开启事务 --> 58 <property name="enableTransactionSupport" value="true"></property> 59 </bean> 60 61 <!--自定义redis工具类,在需要缓存的地方注入此类 --> 62 <bean id="jedis" class="com.idbk.eastevs.dal.jedis.Jedis"> 63 <property name="redisTemplate" ref="redisTemplate" /> 64 </bean> 65 66 </beans>
7、jdbc配置文件
1 #mysql jdbc 2 jdbc.driverClassName=com.mysql.jdbc.Driver 3 jdbc.url=${pom.jdbc.url} 4 jdbc.username=${pom.jdbc.username} 5 jdbc.password=${pom.jdbc.password} 6 7 jdbc.initialSize=1 8 jdbc.maxActive=60 9 jdbc.maxIdle=60 10 jdbc.minIdle=5 11 jdbc.maxWait=30000 12 13 jdbc.removeAbandoned:true 14 jdbc.removeAbandonedTimeout:1800 15 16 jdbc.timeBetweenEvictionRunsMillis:60000 17 jdbc.minEvictableIdleTimeMillis:300000
8、jedis配置文件
1 redis.host=${pom.redis.host} 2 redis.port=${pom.redis.port} 3 redis.password=${pom.redis.password} 4 redis.minIdle=10 5 redis.maxTotal=50 6 redis.maxWaitMillis=3000 7 redis.blockWhenExhausted=true 8 redis.testOnBorrow=true 9 redis.timeout=5000
9、log4j配置文件
1 #INFO WARN ERROR DEBUG 2 log4j.rootLogger=ERROR,console,file 3 4 log4j.appender.console=org.apache.log4j.ConsoleAppender 5 log4j.appender.console.layout=org.apache.log4j.PatternLayout 6 log4j.appender.console.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss,SSS}] [%p] [%t] [%C.%M(%L)] %m%n%n 7 8 log4j.appender.file=org.apache.log4j.DailyRollingFileAppender 9 log4j.appender.file.File=/home/tomcat/logall/WebApi_logs/WebApi.log 10 log4j.appender.file.DatePattern='.'yyyy-MM-dd 11 log4j.appender.file.layout=org.apache.log4j.PatternLayout 12 log4j.appender.file.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss,SSS}] [%p] [%t] [%C.%M(%L)] %m%n%n 13 log4j.appender.file.encoding=utf-8 14 15 log4j.logger.com=ERROR 16 log4j.logger.org=ERROR 17 log4j.logger.freemarker=ERROR 18 log4j.logger.net=ERROR 19 log4j.logger.com.idbk=DEBUG 20 21 log4j.logger.org.springframework=DEBUG 22 log4j.logger.org.apache.ibatis=DEBUG
10、Spring-Shiro配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <!-- 自定义认证和授权管理 --> 7 <bean id="customRealm" class="com.idbk.eastevs.webapi.shiro.CustomRealm"></bean> 8 9 <!-- 会话Cookie模板,maxAge=-1表示浏览器关闭时失效此Cookie --> 10 <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> 11 <constructor-arg value="sid"/> 12 <property name="httpOnly" value="true"/> 13 <property name="maxAge" value="-1"/> 14 </bean> 15 <!-- rememberme相关 --> 16 <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> 17 <constructor-arg value="rememberMe" /> 18 <property name="httpOnly" value="true" /> 19 <property name="maxAge" value="604800" /><!-- 7天 --> 20 </bean> 21 22 <!-- rememberMe管理器 --> 23 <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager"> 24 <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('EASTEVShua1314520rsdag==')}"/> 25 <property name="cookie" ref="rememberMeCookie"/> 26 </bean> 27 28 <!-- 基于Form表单的身份验证过滤器 --> 29 <!-- <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter"> 30 <property name="rememberMeParam" value="rememberMe"/> 31 </bean> --> 32 33 <!-- sessionIdCookie的实现,用于重写覆盖容器默认的JSESSIONID --> 34 <bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> 35 <!-- 设置Cookie名字, 默认为: JSESSIONID 问题: 与SERVLET容器名冲突, 如JETTY, TOMCAT 等默认JSESSIONID, 36 当跳出SHIRO SERVLET时如ERROR-PAGE容器会为JSESSIONID重新分配值导致登录会话丢失! --> 37 <property name="name" value="SHIRO-COOKIE"/> 38 <!-- JSESSIONID的path为/用于多个系统共享JSESSIONID --> 39 <!-- <property name="path" value="/"/> --> 40 <!-- 浏览器中通过document.cookie可以获取cookie属性,设置了HttpOnly=true,在脚本中就不能的到cookie,可以避免cookie被盗用 --> 41 <property name="httpOnly" value="true"/> 42 </bean> 43 44 <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO" /> 45 <!-- 会话管理器 --> 46 <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 47 <property name="sessionDAO" ref="sessionDAO"/> 48 <property name="sessionIdCookie" ref="simpleCookie"/> 49 <!-- 全局的会话信息时间,,单位为毫秒 --> 50 <property name="globalSessionTimeout" value="1800000"/> 51 <!-- 检测扫描信息时间间隔,单位为毫秒--> 52 <property name="sessionValidationInterval" value="60000"/> 53 <!-- 是否开启扫描 --> 54 <property name="sessionValidationSchedulerEnabled" value="false"/> 55 <!-- 去掉URL中的JSESSIONID --> 56 <property name="sessionIdUrlRewritingEnabled" value="true"/> 57 </bean> 58 59 <!-- 安全管理器 --> 60 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 61 <property name="realm" ref="customRealm"></property> 62 <property name="rememberMeManager" ref="rememberMeManager"/> 63 <property name="sessionManager" ref="sessionManager" /> 64 </bean> 65 66 <!-- Shiro生命周期处理器,保证实现了Shiro内部lifecycle函数的bean执行--> 67 <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> 68 69 <!-- 自定义shiro的filter --> 70 <bean id="shiroAjaxFilter" class="com.idbk.eastevs.webapi.shiro.ShiroAjaxFilter" /> 71 72 <!-- 配置ShiroFilter --> 73 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 74 <property name="securityManager" ref="securityManager"></property> 75 <!-- 登入页面 --> 76 <property name="loginUrl" value="/login"></property> 77 <property name="successUrl" value="/index"></property> 78 <!-- 未授权的跳转 --> 79 <property name="unauthorizedUrl" value="other/unauthorized.jsp"/> 80 <property name="filterChainDefinitions"> 81 <value> 82 /caocao/** = anon 83 /evcs/** = anon 84 /resource/** = anon 85 /system/** = anon 86 /pay/** = anon 87 88 /include/** = anon 89 /login = anon 90 /logout = logout 91 /captcha = anon 92 /unauthorized = anon 93 /ajax/login = anon 94 /ajax/register = anon 95 /ajax/** = shiroAjaxFilter 96 /** = user 97 </value> 98 </property> 99 </bean> 100 101 <!-- 开启Shiro Spring AOP 权限注解的支持 --> 102 <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/> 103 <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> 104 <property name="securityManager" ref="securityManager"/> 105 </bean> 106 107 </beans>
11、自定义CustomRealm
1 package com.idbk.eastevs.webapi.shiro; 2 3 import org.apache.log4j.Logger; 4 import org.apache.shiro.authc.AuthenticationException; 5 import org.apache.shiro.authc.AuthenticationInfo; 6 import org.apache.shiro.authc.AuthenticationToken; 7 import org.apache.shiro.authc.SimpleAuthenticationInfo; 8 import org.apache.shiro.authc.UsernamePasswordToken; 9 import org.apache.shiro.authz.AuthorizationInfo; 10 import org.apache.shiro.authz.SimpleAuthorizationInfo; 11 import org.apache.shiro.realm.AuthorizingRealm; 12 import org.apache.shiro.subject.PrincipalCollection; 13 import org.springframework.beans.factory.annotation.Autowired; 14 15 import com.idbk.eastevs.webapi.App; 16 17 /** 18 * @Author Tophua 19 * @Date 2018年12月4日 20 * @Description 自定义shiro认证和授权处理 21 */ 22 public class CustomRealm extends AuthorizingRealm { 23 24 private static final Logger Log = Logger.getLogger(CustomRealm.class); 25 26 @Autowired 27 App app; 28 29 /** 30 * 授权、权限验证 31 */ 32 @Override 33 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 34 // Integer userId = (Integer) principals.getPrimaryPrincipal(); 35 // 数据库获取权限 36 37 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); 38 //加入角色 39 info.addRole("super"); 40 // info.setRoles(roles); 41 // 加入权限 42 info.addStringPermission("*"); 43 // info.setStringPermissions(stringPermissions); 44 return info; 45 } 46 47 /** 48 * 身份认证、登录 49 */ 50 @Override 51 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { 52 UsernamePasswordToken _token = (UsernamePasswordToken) token; 53 String username = _token.getUsername(); 54 String password = String.valueOf(_token.getPassword()); 55 /** 56 * 做数据库登录验证,在此只先提供超级用户登录 57 * 58 */ 59 if (password.equals(app.getSuperPassword())) { 60 Log.info("超级用户登录,用户名:" + username); 61 } else { 62 throw new AuthenticationException(); 63 } 64 65 //此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息 66 //说白了就是第一个参数填登录用户名,第二个参数填合法的登录密码(可以是从数据库中取到的) 67 //这样一来,在随后的登录页面上就只有这里指定的用户和密码才能通过验证 68 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName()); 69 return info; 70 } 71 72 }
12、登录模型
1 package com.idbk.eastevs.webapi.controller.inner.ajax; 2 3 import org.apache.shiro.SecurityUtils; 4 import org.apache.shiro.authc.AuthenticationException; 5 import org.apache.shiro.authc.LockedAccountException; 6 import org.apache.shiro.authc.UnknownAccountException; 7 import org.apache.shiro.authc.UsernamePasswordToken; 8 import org.apache.shiro.subject.Subject; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.web.bind.annotation.RequestMapping; 11 import org.springframework.web.bind.annotation.RequestParam; 12 import org.springframework.web.bind.annotation.RestController; 13 14 import com.idbk.eastevs.webapi.App; 15 import com.idbk.eastevs.webapi.json.Result; 16 17 /** 18 * @Author Tophua 19 * @Date 2018年11月30日 20 * @Description 21 */ 22 @RestController 23 @RequestMapping("/ajax") 24 public class LoginMngController { 25 26 @Autowired 27 App app; 28 29 @RequestMapping("/login") 30 private Result login( 31 @RequestParam("loginName") String loginName, 32 @RequestParam("password") String password, 33 @RequestParam(name="rememberMe",required=false,defaultValue="false") boolean rememberMe 34 ) { 35 UsernamePasswordToken token = new UsernamePasswordToken(loginName, password, rememberMe); 36 Subject subject = SecurityUtils.getSubject(); 37 try 38 { 39 subject.login(token); 40 return Result.ok(); 41 } 42 catch (UnknownAccountException e) 43 { 44 return Result.failed("账号不存在"); 45 } 46 catch (LockedAccountException e) 47 { 48 return Result.failed("账号不可用"); 49 } 50 catch (AuthenticationException e) 51 { 52 } 53 return Result.failed("账号或密码错误"); 54 } 55 }
13、全局异常管理
1 package com.idbk.eastevs.webapi; 2 3 import javax.servlet.http.HttpServletRequest; 4 5 import org.apache.log4j.Logger; 6 import org.apache.shiro.SecurityUtils; 7 import org.apache.shiro.authz.UnauthorizedException; 8 import org.apache.shiro.subject.Subject; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.web.bind.annotation.ControllerAdvice; 11 import org.springframework.web.bind.annotation.ExceptionHandler; 12 import org.springframework.web.bind.annotation.ModelAttribute; 13 import org.springframework.web.bind.annotation.ResponseBody; 14 15 import com.idbk.eastevs.webapi.json.Result; 16 17 /** 18 * @Author Tophua 19 * @Date 2018年12月5日 20 * @Description 内部异常处理 21 */ 22 @ControllerAdvice("com.idbk.eastevs.webapi.controller.inner") 23 public class SysInnerExceptionHandle { 24 25 private static final Logger LOG = Logger.getLogger(SysInnerExceptionHandle.class); 26 27 @Autowired 28 App app; 29 30 @ModelAttribute("app") 31 public App getMyAppInfo() { 32 return app; 33 } 34 35 @ModelAttribute("user") 36 public String getUser() { 37 Subject subject = SecurityUtils.getSubject(); 38 return (String) subject.getPrincipal(); 39 } 40 41 @ModelAttribute("menu") 42 public String getMenu(HttpServletRequest request) { 43 return request.getRequestURI(); 44 } 45 46 /** 47 * 权限验证失败时异常 48 * @param e 49 * @return 50 */ 51 @ExceptionHandler(UnauthorizedException.class) 52 String handleUnauthorizedException(UnauthorizedException e) { 53 LOG.error(e.getMessage(), e); 54 return "other/unauthorized.jsp"; 55 } 56 57 @ExceptionHandler(Exception.class) 58 @ResponseBody 59 Result handleException(Exception e) { 60 LOG.error(e.getMessage(), e); 61 return Result.sysBusy(); 62 } 63 }
总结:
现多项目多用此技术,常用配置足以满足项目要求。如需进一步了解,建议看官方文档!
至此结束!
多多关注!
Shiro参考:https://www.iteye.com/blogs/subjects/shiro
热爱生活,热爱代码!
做一个有思想、有灵魂的程序员!