引文:css
本文主要講述項目框架搭建時的一些簡單的使用配置,教你如何快速進行項目框架搭建。html
技術: Spring+SpringMVC+Mybatis+Redis+Shiro+Maven mybatis、redis都是使用spring集成java
技術介紹就再也不講述了,話很少說,急忙上代碼了。mysql
具體步驟不進行講述。。。。git
主要配置 web.xml 文件github
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>
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>
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>
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>
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>
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>
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
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
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
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>
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 }
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 }
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 }
現多項目多用此技術,經常使用配置足以知足項目要求。如需進一步瞭解,建議看官方文檔!web
至此結束!ajax
多多關注!redis
Shiro參考:https://www.iteye.com/blogs/subjects/shirospring