(1)SSM配置:html
1 <!-- 加密後配置本身寫的解析文件 --> 2 <bean class="com.swpu.o2o.util.EncryptPropertyPlaceholderConfigurer"> 3 <property name="locations"> 4 <list> 5 <!-- 須要解密的文件 --> 6 <value>classpath:jdbc.properties</value> 7 <value>classpath:redis.properties</value> 8 </list> 9 </property> 10 <!-- 設置編碼爲UTF-8 --> 11 <property name="fileEncoding" value="UTF-8"></property> 12 </bean>
1 <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource"> 2 <!-- 配置鏈接池屬性 --> 3 <property name="driverClass" value="${jdbc.driver}" /> 4 <property name="jdbcUrl" value="${jdbc.url}" /> 5 <property name="user" value="${jdbc.username}" /> 6 <property name="password" value="${jdbc.password}" /> 7 <!-- c3p0鏈接池的私有屬性 --> 8 <property name="maxPoolSize" value="30" /> 9 <property name="minPoolSize" value="10" /> 10 <!-- 關閉鏈接後不自動commit --> 11 <property name="autoCommitOnClose" value="false" /> 12 <!-- 獲取鏈接超時時間 --> 13 <property name="checkoutTimeout" value="10000" /> 14 <!-- 當獲取鏈接失敗重試次數 --> 15 <property name="acquireRetryAttempts" value="2" /> 16 </bean>
(2)Spring Boot配置(寫入Bean)java
1 package com.swpu.o2o.config.dao; 2 3 import com.mchange.v2.c3p0.ComboPooledDataSource; 4 import com.swpu.o2o.util.DESUtils; 5 import org.mybatis.spring.annotation.MapperScan; 6 import org.springframework.beans.factory.annotation.Value; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.Configuration; 9 10 import java.beans.PropertyVetoException; 11 12 /** 13 * 配置dataSource到ioc容器裏 14 */ 15 @Configuration 16 //配置mybatis mapper掃描路徑 17 @MapperScan("com.swpu.o2o.dao") 18 public class DataSourceConfiguration { 19 //經過@Value標籤獲取application.properties中的配置信息 20 @Value("${jdbc.driver}") 21 private String jdbcDriver; 22 @Value("${jdbc.url}") 23 private String jdbcUrl; 24 @Value("${jdbc.username}") 25 private String jdbcUser; 26 @Value("${jdbc.password}") 27 private String jdbcPassword; 28 /** 29 * 生成與與spring-dao.xml對應的bean dataSource 30 */ 31 @Bean(name="dataSource") 32 public ComboPooledDataSource createDataSource() throws PropertyVetoException { 33 //生成dataSource實例 34 ComboPooledDataSource dataSource=new ComboPooledDataSource(); 35 //配置相關信息(和配置文件同樣) 36 //驅動(強制異常處理,拋出去) 37 dataSource.setDriverClass(jdbcDriver); 38 //數據庫鏈接url 39 dataSource.setJdbcUrl(jdbcUrl); 40 //用戶名(解密) 41 dataSource.setUser(DESUtils.getDecryptString(jdbcUser)); 42 //密碼 43 dataSource.setPassword(DESUtils.getDecryptString(jdbcPassword)); 44 return dataSource; 45 } 46 }
(1)SSM配置:web
1 <!-- 3.配置SqlSessionFactory對象 --> 2 <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> 3 <!-- 注入數據庫鏈接池 --> 4 <property name="dataSource" ref="dataSource" /> 5 <!-- 配置MyBaties全局配置文件:mybatis-config.xml --> 6 <property name="configLocation" value="classpath:mybatis-config.xml" /> 7 <!-- 掃描entity包 使用別名 --> 8 <property name="typeAliasesPackage" value="com.swpu.o2o.entity" /> 9 <!-- 掃描sql配置文件:mapper須要的xml文件 --> 10 <property name="mapperLocations" value="classpath:mapper/*.xml" /> 11 </bean> 12 <!-- 4.配置掃描Dao接口包,動態實現Dao接口,注入到spring容器中 --> 13 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 14 <!-- 注入sqlSessionFactory --> 15 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 16 17 <!-- 給出須要掃描Dao接口包 --> 18 <property name="basePackage" value="com.swpu.o2o.dao" /> 19 </bean>
(2)Spring Boot配置:redis
1 package com.swpu.o2o.config.dao; 2 3 import org.mybatis.spring.SqlSessionFactoryBean; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.beans.factory.annotation.Value; 6 import org.springframework.context.annotation.Bean; 7 import org.springframework.context.annotation.Configuration; 8 import org.springframework.core.io.ClassPathResource; 9 import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 10 import org.springframework.core.io.support.ResourcePatternResolver; 11 12 import javax.sql.DataSource; 13 import java.io.IOException; 14 15 @Configuration 16 public class SessionFactoryConfiguration { 17 //mybatis-config.xml配置文件路徑 18 //注意:靜態(static)的變量不能直接經過@Value獲取,能夠經過set方法 19 private static String mybatisConfigFile; 20 //mybatis mapper文件所在路徑 21 private static String mapperPath; 22 23 @Value("${mybatis_config_file}") 24 public void setMybatisConfigFile(String mybatisConfigFile) { 25 SessionFactoryConfiguration.mybatisConfigFile = mybatisConfigFile; 26 } 27 28 @Value("${mapper_path}") 29 public void setMapperPath(String mapperPath) { 30 SessionFactoryConfiguration.mapperPath = mapperPath; 31 } 32 33 //實體類所在package 34 @Value("${type_alias_package}") 35 private String typeAliasPackage; 36 @Autowired 37 private DataSource dataSource; 38 /** 39 * 建立SqlSessionFactoryBean實例,而且設置mapper映射路徑 40 * 設置dataSource數據源 41 */ 42 @Bean(name = "sqlSessionFactory") 43 public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException { 44 SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 45 //設置mybatis configuration掃描路徑 46 sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFile)); 47 //設置mapper 掃描路徑 48 PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(); 49 String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath; 50 sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath)); 51 //設置dataSource 52 sqlSessionFactoryBean.setDataSource(dataSource); 53 //設置typeAlias包掃描路徑 54 sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage); 55 return sqlSessionFactoryBean; 56 } 57 }
(3)Mybatis配置文件:spring
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <!-- 配置全局屬性 --> 7 <settings> 8 <!-- 使用jdbc的getGeneratedKeys獲取數據庫自增主鍵值 --> 9 <setting value="true" name="useGeneratedKeys" /> 10 <!-- 使用列別名替換列名 默認:true --> 11 <setting value="true" name="useColumnLabel" /> 12 <!-- 開啓駝峯命名轉換:Table{create_time} -> Entity{createTime} --> 13 <setting value="true" name="mapUnderscoreToCamelCase" /> 14 <!-- 打印查詢語句 --> 15 </settings> 16 17 </configuration>
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 3 xsi:schemaLocation="http://www.springframework.org/schema/beans 4 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 5 http://www.springframework.org/schema/context 6 http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 7 <!-- Redis鏈接池配置 --> 8 <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 9 <!-- 控制一個pool能分配多少個jedis實例 --> 10 <property name="maxTotal" value="${redis.pool.maxActive}" /> 11 <!-- 鏈接池中最多空閒多少個maxIdle個鏈接,這裏爲20,表示即便沒有數據庫鏈接時依然能夠保持20空閒的鏈接,而不被清除,處於待命狀態,隨時鏈接 --> 12 <property name="maxIdle" value="${redis.pool.maxIdle}" /> 13 <!-- 最大等待時間,當沒有可用鏈接時,鏈接池等待鏈接被歸還的最大時間(以毫秒計數),超過期間即拋出異常 --> 14 <property name="maxWaitMillis" value="${redis.pool.maxWait}" /> 15 <!-- 在獲取鏈接時,檢查有效性 --> 16 <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /> 17 </bean> 18 <!-- 建立Redis鏈接池,並作相關配置 --> 19 <bean id="jedisWritePool" class="com.swpu.o2o.cache.JedisPoolWriper" 20 depends-on="jedisPoolConfig"> 21 <constructor-arg index="0" ref="jedisPoolConfig" /> 22 <constructor-arg index="1" value="${redis.hostname}" /> 23 <constructor-arg index="2" value="${redis.port}" type="int" /> 24 </bean> 25 <!-- 建立Redis工具類,封裝好Redis的鏈接以進行相關操做 --> 26 <bean id="jedisUtil" class="com.swpu.o2o.cache.JedisUtil" 27 scope="singleton"> 28 <property name="jedisPool"> 29 <ref bean="jedisWritePool" /> 30 </property> 31 </bean> 32 <bean id="jedisKeys" class="com.swpu.o2o.cache.JedisUtil$Keys" 33 scope="singleton"> 34 <constructor-arg ref="jedisUtil"></constructor-arg> 35 </bean> 36 <bean id="jedisStrings" class="com.swpu.o2o.cache.JedisUtil$Strings" 37 scope="singleton"> 38 <constructor-arg ref="jedisUtil"></constructor-arg> 39 </bean> 40 <bean id="jedisLists" class="com.swpu.o2o.cache.JedisUtil$Lists" 41 scope="singleton"> 42 <constructor-arg ref="jedisUtil"></constructor-arg> 43 </bean> 44 <bean id="jedisSets" class="com.swpu.o2o.cache.JedisUtil$Sets" 45 scope="singleton"> 46 <constructor-arg ref="jedisUtil"></constructor-arg> 47 </bean> 48 <bean id="jedisHash" class="com.swpu.o2o.cache.JedisUtil$Hash" 49 scope="singleton"> 50 <constructor-arg ref="jedisUtil"></constructor-arg> 51 </bean> 52 53 </beans>
1 package com.swpu.o2o.config.redis; 2 3 import com.swpu.o2o.cache.JedisPoolWriper; 4 import com.swpu.o2o.cache.JedisUtil; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.beans.factory.annotation.Value; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.Configuration; 9 import redis.clients.jedis.JedisPoolConfig; 10 11 /** 12 * 對應spring-redis.xml裏的配置 13 */ 14 @Configuration 15 public class RedisConfiguration { 16 @Value("${redis.hostname}") 17 private String hostName; 18 @Value("${redis.port}") 19 private int port; 20 @Value("${redis.pool.maxActive}") 21 private int maxTotal; 22 @Value("${redis.pool.maxIdle}") 23 private int maxIdle; 24 @Value("${redis.pool.maxWait}") 25 private long maxWaitMillis; 26 @Value("${redis.pool.testOnBorrow}") 27 private boolean testOnBrrow; 28 29 @Autowired 30 private JedisPoolConfig jedisPoolConfig; 31 @Autowired 32 private JedisPoolWriper jedisWritePool; 33 @Autowired 34 private JedisUtil jedisUtil; 35 36 /** 37 * 建立redis鏈接池設置 38 */ 39 @Bean(name = "jedisPoolConfig") 40 public JedisPoolConfig createJedisPoolConfig() { 41 JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); 42 //控制一個pool可分配給多個jedis實例 43 jedisPoolConfig.setMaxTotal(maxTotal); 44 //鏈接池中最多空閒maxIdle個鏈接,這裏取值20 45 //表示即便沒有數據庫鏈接時依然能夠保持20空閒的鏈接,而不清除,隨時處於待命的狀態 46 jedisPoolConfig.setMaxIdle(maxIdle); 47 //最大等待時間:當沒有可用鏈接時 48 //鏈接池等待鏈接被歸還的最大時間(以毫秒計數),超過期間則拋出異常 49 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); 50 //在獲取鏈接的時候檢查有效性 51 jedisPoolConfig.setTestOnBorrow(testOnBrrow); 52 return jedisPoolConfig; 53 } 54 55 /** 56 * 建立Redis鏈接池,並作相關配置 57 */ 58 @Bean(name = "jedisWritePool") 59 public JedisPoolWriper createJedisPoolWripper() { 60 JedisPoolWriper jedisWritePool = new JedisPoolWriper(jedisPoolConfig, hostName, port); 61 return jedisWritePool; 62 } 63 64 /** 65 * 建立Redis工具類,封裝好Redis的鏈接以進行相關的操做 66 */ 67 @Bean(name = "jedisUtil") 68 public JedisUtil createJedisUtil() { 69 JedisUtil jedisUtil = new JedisUtil(); 70 jedisUtil.setJedisPool(jedisWritePool); 71 return jedisUtil; 72 } 73 74 /** 75 * Redis的key操做 76 */ 77 @Bean(name = "jedisKeys") 78 public JedisUtil.Keys createJedisKeys() { 79 //實例化內部類 80 JedisUtil.Keys jedisKeys = jedisUtil.new Keys(); 81 return jedisKeys; 82 } 83 84 /** 85 * Redis的String操做 86 */ 87 @Bean(name = "jedisStrings") 88 public JedisUtil.Strings createJedisStrings() { 89 //實例化內部類 90 JedisUtil.Strings jedisStrings = jedisUtil.new Strings(); 91 return jedisStrings; 92 } 93 94 /** 95 * Redis的List操做 96 */ 97 @Bean(name = "jedisLists") 98 public JedisUtil.Lists createJedisLists() { 99 //實例化內部類 100 JedisUtil.Lists jedisLists = jedisUtil.new Lists(); 101 return jedisLists; 102 } 103 104 /** 105 * Redis的Hash操做 106 */ 107 @Bean(name = "jedisHash") 108 public JedisUtil.Hash createJedisHash() { 109 //實例化內部類 110 JedisUtil.Hash jedisHash = jedisUtil.new Hash(); 111 return jedisHash; 112 } 113 114 /** 115 * Redis的sets操做 116 */ 117 @Bean(name = "jedisSets") 118 public JedisUtil.Sets createJedisSets() { 119 //實例化內部類 120 JedisUtil.Sets jedisSets = jedisUtil.new Sets(); 121 return jedisSets; 122 } 123 124 125 126 }
1 package com.swpu.o2o.cache; 2 3 import redis.clients.jedis.JedisPool; 4 import redis.clients.jedis.JedisPoolConfig; 5 6 /** 7 * 強指定redis的JedisPool接口構造函數,這樣才能在centos成功建立jedispool 8 * 9 * @author xiangze 10 * 11 */ 12 public class JedisPoolWriper { 13 //鏈接池對象 14 private JedisPool jedisPool; 15 16 public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host, 17 final int port) { 18 try { 19 //經過鏈接池配置信息,IP,端口構造鏈接池對象 20 jedisPool = new JedisPool(poolConfig, host, port); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 } 25 //獲取redis鏈接池對象 26 public JedisPool getJedisPool() { 27 return jedisPool; 28 } 29 //注入redis鏈接池對象 30 public void setJedisPool(JedisPool jedisPool) { 31 this.jedisPool = jedisPool; 32 } 33 34 }
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 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx.xsd"> 12 <!-- 掃描service包下全部使用註解的類型 --> 13 <context:component-scan base-package="com.swpu.o2o.service" /> 14 15 <!-- 配置事務管理器 --> 16 <bean id="transactionManager" 17 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 18 <!-- 注入數據庫鏈接池 --> 19 <property name="dataSource" ref="dataSource" /> 20 </bean> 21 22 <!-- 配置基於註解的聲明式事務 --> 23 <tx:annotation-driven transaction-manager="transactionManager" /> 24 </beans>
1 package com.swpu.o2o.config.service; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 6 import org.springframework.transaction.PlatformTransactionManager; 7 import org.springframework.transaction.annotation.EnableTransactionManagement; 8 import org.springframework.transaction.annotation.TransactionManagementConfigurer; 9 10 import javax.sql.DataSource; 11 12 /** 13 * 對應spring-service.xml裏面的transactionManager 14 * 繼承transactionManagementConfigurer:不能直接加入Bean,由於開啓了annotation-driven 15 */ 16 @Configuration 17 //首先使用註解@EnableTransactionManagement開啓事務後 18 //在Service方法上添加註解@Transactional 19 @EnableTransactionManagement 20 public class TransactionManageConfiguration implements TransactionManagementConfigurer { 21 @Autowired 22 //注入DataSourceConfiguration裏面的dataSource,經過createDataSource()獲取 23 private DataSource dataSource; 24 25 @Override 26 /** 27 * 關於事務處理,須要返回PlatformTransactionManager的實現 28 */ 29 public PlatformTransactionManager annotationDrivenTransactionManager() { 30 return new DataSourceTransactionManager(dataSource); 31 } 32 }
1.開啓SpringMVC註解模式;2.靜態資源默認servlet配置;3.定義視圖解析器;4.掃描web相關的bean;5.權限攔截器sql
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.xsd 9 http://www.springframework.org/schema/mvc 10 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> 11 <!-- 配置SpringMVC --> 12 <!-- 1.開啓SpringMVC註解模式 --> 13 <!-- 簡化配置: (1)自動註冊DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 14 (2)提供一些列:數據綁定,數字和日期的format @NumberFormat, @DateTimeFormat, xml,json默認讀寫支持 --> 15 <mvc:annotation-driven /> 16 17 <!-- 2.靜態資源默認servlet配置 (1)加入對靜態資源的處理:js,gif,png (2)容許使用"/"作總體映射 --> 18 <mvc:resources mapping="/resources/**" location="/resources/" /> 19 <mvc:default-servlet-handler /> 20 21 <!-- 3.定義視圖解析器 --> 22 <!-- 定製請求加頭加尾 --> 23 <bean id="viewResolver" 24 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 25 <property name="prefix" value="/WEB-INF/html/"></property> 26 <property name="suffix" value=".html"></property> 27 </bean> 28 <bean id="multipartResolver" 29 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 30 <!-- 默認編碼 --> 31 <property name="defaultEncoding" value="utf-8"></property> 32 <!-- 上傳文件的最大 尺寸(單位是字節) --> 33 <!-- 1024*1024*20=20971520 --> 34 <property name="maxUploadSize" value="20971520"></property> 35 <!-- 容許寫在內存中的最大值 --> 36 <property name="maxInMemorySize" value="20971520"></property> 37 </bean> 38 <!-- 4.掃描web相關的bean --> 39 <context:component-scan base-package="com.swpu.o2o.web" /> 40 <!-- 5.權限攔截器 --> 41 <mvc:interceptors> 42 <!-- 校驗是否登陸了該管理系統的攔截器 --> 43 <mvc:interceptor> 44 <!-- 定義攔截的路由,shopadmin包下的全部Controller --> 45 <mvc:mapping path="/shopadmin/**" /> 46 <!-- 攔截方法 --> 47 <bean class="com.swpu.o2o.interceptor.shopadmin.ShopLoginInterceptor" 48 id="ShopInterceptor" /> 49 </mvc:interceptor> 50 <!-- 校驗是否對該店鋪有操做權限的攔截器 --> 51 <mvc:interceptor> 52 <!-- 須要攔截的接口 --> 53 <mvc:mapping path="/shopadmin/**" /> 54 <!-- shoplist page --> 55 <!-- 排除該包下的某些接口不攔截 --> 56 <mvc:exclude-mapping path="/shopadmin/shoplist" /> 57 <mvc:exclude-mapping path="/shopadmin/getshoplist" /> 58 <!-- shopmanage page --> 59 <mvc:exclude-mapping path="/shopadmin/shopmanagement" /> 60 <mvc:exclude-mapping path="/shopadmin/getshopmanagementinfo" /> 61 <!-- shopregister page --> 62 <mvc:exclude-mapping path="/shopadmin/getshopinitinfo" /> 63 <mvc:exclude-mapping path="/shopadmin/shopoperation" /> 64 <mvc:exclude-mapping path="/shop/registershop" /> 65 <bean class="com.swpu.o2o.interceptor.shopadmin.ShopPermissionInterceptor" 66 id="ShopPermissionInterceptor" /> 67 </mvc:interceptor> 68 </mvc:interceptors> 69 </beans>
1 package com.swpu.o2o.config.web; 2 3 import com.google.code.kaptcha.servlet.KaptchaServlet; 4 import com.swpu.o2o.interceptor.ShopLoginInterceptor; 5 import com.swpu.o2o.interceptor.ShopPermissionInterceptor; 6 import org.springframework.beans.BeansException; 7 import org.springframework.beans.factory.annotation.Value; 8 import org.springframework.boot.web.servlet.ServletRegistrationBean; 9 import org.springframework.context.ApplicationContext; 10 import org.springframework.context.ApplicationContextAware; 11 import org.springframework.context.annotation.Bean; 12 import org.springframework.context.annotation.Configuration; 13 import org.springframework.web.multipart.commons.CommonsMultipartResolver; 14 import org.springframework.web.servlet.ViewResolver; 15 import org.springframework.web.servlet.config.annotation.*; 16 import org.springframework.web.servlet.view.InternalResourceViewResolver; 17 18 import javax.servlet.ServletException; 19 20 /** 21 * 開啓Mvc,自動注入spring容器中 22 * WebMvcConfigurer:配置視圖解析器 23 * 當一個類實現了接口WebMvcConfigurer,這個類就能方便的獲取裏面全部的bean 24 */ 25 @Configuration 26 //等價於<mvc:annotation-driven/>,使用Java 註解快捷配置Spring Webmvc 27 @EnableWebMvc 28 //實現ApplicationContextAware該接口獲取Spring容器 29 // extends WebMvcConfigurationSupport implements ApplicationContextAware 30 public class MvcConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware { 31 //Spring容器 32 private ApplicationContext applicationContext; 33 34 @Override 35 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 36 this.applicationContext = applicationContext; 37 } 38 39 /** 40 * 靜態資源配置(docBase) 41 * 42 * 43 * @param registry 44 */ 45 @Override 46 public void addResourceHandlers(ResourceHandlerRegistry registry) { 47 //攔截/resources下的請求解析到目標路徑classpath:/resources 48 //classpath表示在項目工程中找,file表示在服務器中找 49 registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/Project/image/upload/"); 50 } 51 52 /** 53 * 定義默認的請求處理器 54 * 55 * @param configurer 56 */ 57 @Override 58 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 59 configurer.enable(); 60 } 61 62 /** 63 * 建立viewResolver 64 * @return 65 */ 66 @Bean(name = "viewResolver") 67 public ViewResolver createViewResolver() { 68 InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 69 //設置spring容器 70 //viewResolver.setApplicationContext(this.applicationContext); 71 //取消緩存 72 viewResolver.setCache(false); 73 //設置解析的前綴 74 viewResolver.setPrefix("/WEB-INF/html/"); 75 //設置視圖解析的後綴 76 viewResolver.setSuffix(".html"); 77 return viewResolver; 78 } 79 80 /** 81 * 文件上傳解析器 82 * 83 * @return 84 */ 85 @Bean(name = "multipartResolver") 86 public CommonsMultipartResolver commonsMultipartResolver() { 87 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); 88 multipartResolver.setDefaultEncoding("utf-8"); 89 //文件大小1024*1024*20 90 multipartResolver.setMaxUploadSize(20971520); 91 multipartResolver.setMaxInMemorySize(20971520); 92 return multipartResolver; 93 } 94 //引入驗證碼kaptcha相關信息 95 @Value("${kaptcha.border}") 96 private String border; 97 @Value("${kaptcha.textproducer.font.color}") 98 private String fcolor; 99 @Value("${kaptcha.image.width}") 100 private String width; 101 @Value("${kaptcha.textProducer.char.string}") 102 private String cString; 103 @Value("${kaptcha.image.height}") 104 private String height; 105 @Value("${kaptcha.textproducer.font.size}") 106 private String fsize; 107 @Value("${kaptcha.noise.color}") 108 private String nColor; 109 @Value("${kaptcha.textproducer.char.length}") 110 private String clength; 111 @Value("${kaptcha.textproducer.font.names}") 112 private String fnames; 113 114 /** 115 * web.xml不生效了,在這裏配置Kaptcha驗證碼Servlet 116 * @return 117 */ 118 @Bean 119 public ServletRegistrationBean servletRegistrationBean() throws ServletException { 120 ServletRegistrationBean servlet=new ServletRegistrationBean(new KaptchaServlet(),"/Kaptcha"); 121 servlet.addInitParameter("kaptcha.border",border);//無邊框 122 servlet.addInitParameter("kaptcha.textproducer.font.color",fcolor);//字體顏色 123 servlet.addInitParameter("kaptcha.image.width",width);//圖片寬度 124 servlet.addInitParameter("kaptcha.textProducer.char.string",cString);//使用哪些字體 125 servlet.addInitParameter("kaptcha.image.height",height);//圖片高度 126 servlet.addInitParameter("kaptcha.textproducer.font.size",fsize);//字體大小 127 servlet.addInitParameter("kaptcha.noise.color",nColor);//干擾線顏色 128 servlet.addInitParameter("kaptcha.textproducer.char.length",clength);//字符個數 129 servlet.addInitParameter("kaptcha.textproducer.font.names",fnames);//字體 130 return servlet; 131 132 } 133 134 /** 135 * 攔截器 136 * @param registry 137 */ 138 @Override 139 public void addInterceptors(InterceptorRegistry registry) { 140 String interceptPath="/shopadmin/**"; 141 //註冊攔截器(驗證是否登陸) 142 InterceptorRegistration loginIR=registry.addInterceptor(new ShopLoginInterceptor()); 143 //配置攔截器路徑 144 loginIR.addPathPatterns(interceptPath); 145 //註冊攔截器(驗證是否具備權限) 146 InterceptorRegistration permissionIR=registry.addInterceptor(new ShopPermissionInterceptor()); 147 //配置攔截器路徑 148 permissionIR.addPathPatterns(interceptPath); 149 //配置不攔截的路徑 150 permissionIR.excludePathPatterns("/shopadmin/shoplist"); 151 permissionIR.excludePathPatterns("/shopadmin/getshoplist"); 152 permissionIR.excludePathPatterns("/shopadmin/registershop"); 153 permissionIR.excludePathPatterns("/shopadmin/shopoperation"); 154 permissionIR.excludePathPatterns("/shopadmin/shopmanagement"); 155 permissionIR.excludePathPatterns("/shopadmin/getshopmanagementinfo"); 156 } 157 }
注:WebMvcConfigurerAdapter在Spring Boot2.0就已通過時,不推薦使用,能夠繼承WebMvcConfigurationSupport。該類包含了WebMvcConfigurerAdapter的全部方法。數據庫