ssm框架配置過程
1.pom.xml配置
1.1<build>標簽中配置<plugins>和<resources>,即插件和資源文件
1.2 <properties>標簽中配置自定義的標簽,可以在<dependency>中取出
1.3<dependencies>中配置各依賴包,統一管理
2.創建項目用到的包
1.1web層一般用到model,dao,controller,service,utils,security
1.2創建webapp下面的靜態資源存放目錄,如images,js,WEB-INF目錄下的views
3.resources下創建資源文件
1.1先創建數據庫的配置文件
##JDBC Global Setting jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=root ##DataSource Global Setting #配置初始化大小、最小、最大 ds.initialSize=1 ds.minIdle=1 ds.maxActive=20 #配置獲取連接等待超時的時間 ds.maxWait=60000 #配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 ds.timeBetweenEvictionRunsMillis=60000 #配置一個連接在池中最小生存的時間,單位是毫秒 ds.minEvictableIdleTimeMillis=300000
1.2log4j日誌的配置文件
# DEBUG,INFO,WARN,ERROR,FATAL LOG_LEVEL=INFO log4j.rootLogger=${LOG_LEVEL},CONSOLE,FILE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.Encoding=utf-8 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout #log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{8}@(%F:%L):%m%n log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{1}@(%F:%L):%m%n log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender log4j.appender.FILE.File=${catalina.base}/logs/ssm.log log4j.appender.FILE.Encoding=utf-8 log4j.appender.FILE.DatePattern=‘.‘yyyy-MM-dd log4j.appender.FILE.layout=org.apache.log4j.PatternLayout #log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout log4j.appender.FILE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} %C{8}@(%F\:%L)\:%m%n
1.3創建applicationContext.xml文件(spring的配置文件)
1.3.1 創建過程:(1)管理包下的註解(2)引入數據庫配置文件(3)配置數據源dataSource(4)mybatis文件配置,掃描所有mapper接口,sqlsessionFactory需要配置屬性dataSource,mybatis配置文件地址,mapper接口地址
(5)spring和mybatis整合,掃描所有dao,需要屬性配置,dao地址,sqlsessionFactory(6)事務管理器,需要dataSource(7)事務通知,對哪些方法進行了哪些事務管理(8)事務的aop管理,需要切點與通知
(9)配置spring的cglib代理(10)開啟事務的註解(11)配置spring的cache註解,需要緩存管理器,緩存管理器引用緩存管理器工廠,工廠指向ehcache.xml文件
1.3.2代碼:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!--自動掃描sj包,將帶有註解的類納入spring管理 在xml配置了這個標簽後,spring可以自動去掃描base-pack下面或者子包下面的java文件, 如果掃描到有@Component @Controller@Service等這些註解的類,則把這些類註冊為bean--> <context:component-scan base-package="com.demo"></context:component-scan> <!--引入配置文件--> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:application.properties</value> </list> </property> </bean> <!--配置數據源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="${ds.initialSize}"/> <property name="minIdle" value="${ds.minIdle}"/> <property name="maxActive" value="${ds.maxActive}"/> <!-- 配置獲取連接等待超時的時間 --> <property name="maxWait" value="${ds.maxWait}"/> <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/> <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/> <property name="validationQuery" value="SELECT ‘x‘"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <!-- 打開PSCache,並且指定每個連接上PSCache的大小 --> <property name="poolPreparedStatements" value="false"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <!-- 配置監控統計攔截的filters --> <property name="filters" value="stat"/> </bean> <!--mybatis掃描mapper接口--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:com/demo/web/dao/*.xml"> </bean> <!--spring與mybatis整合配置,掃描所有dao--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.demo.web.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory"></bean> <!--事務配置--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <!--事務通知--> <tx:advice id="txActive" transaction-manager="transactionManager"> <tx:attributes> <!-- 對insert,update,delete 開頭的方法進行事務管理,只要有異常就回滾 --> <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> <!-- select,count開頭的方法,開啟只讀,提高數據庫訪問性能 --> <tx:method name="select*" read-only="true"/> <tx:method name="count*" read-only="true"/> <!-- 對其他方法 使用默認的事務管理 --> <tx:method name="*"/> </tx:attributes> </tx:advice> <!--aop--> <aop:config> <aop:pointcut id="serviceMethods" expression="execution(* com.demo.web.service..*(..))"/> <aop:advisor advice-ref="txActive" pointcut-ref="serviceMethods"></aop:advisor> </aop:config> <!-- 配置使Spring采用CGLIB代理 --> <aop:aspectj-autoproxy proxy-target-class="true"/> <!--事務的註解支持--> <tx:annotation-driven transaction-manager="transactionManager"/> <!--Cache配置--> <cache:annotation-driven cache-manager="cacheManager"/> <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:ehcache.xml"/> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehCacheManagerFactory"/> </beans>
1.4創建mybatis-config.xml文件,並配置
1.4.1基本需要:與spring整合後只需一個空框架即可,不用加任何配置,也對mybatis有其他配置,如typeAliases別名,settings設置等
1.4.2代碼:
<?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> <properties> <property name="dialectClass" value="com.demo.core.feature.orm.dialect.MySql5Dialect"/> </properties> <!-- 配置mybatis的緩存,延遲加載等等一系列屬性 --> <settings> <!-- 全局映射器啟用緩存 --> <setting name="cacheEnabled" value="true"/> <!-- 查詢時,關閉關聯對象即時加載以提高性能 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 對於未知的SQL查詢,允許返回不同的結果集以達到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- 允許使用列標簽代替列名 --> <setting name="useColumnLabel" value="true"/> <!-- 不允許使用自定義的主鍵值(比如由程序生成的UUID 32位編碼作為鍵值),數據表的PK生成策略將被覆蓋 --> <setting name="useGeneratedKeys" value="false"/> <!-- 給予被嵌套的resultMap以字段-屬性的映射支持 FULL,PARTIAL --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- 對於批量更新操作緩存SQL以提高性能 BATCH,SIMPLE --> <!-- <setting name="defaultExecutorType" value="BATCH" /> --> <!-- 數據庫超過25000秒仍未響應則超時 --> <!-- <setting name="defaultStatementTimeout" value="25000" /> --> <!-- Allows using RowBounds on nested statements --> <setting name="safeRowBoundsEnabled" value="false"/> <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn. --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession. --> <setting name="localCacheScope" value="SESSION"/> <!-- Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values like NULL, VARCHAR or OTHER. --> <setting name="jdbcTypeForNull" value="OTHER"/> <!-- Specifies which Object‘s methods trigger a lazy load --> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> <!-- 設置關聯對象加載的形態,此處為按需加載字段(加載字段由SQL指 定),不會加載關聯表的所有字段,以提高性能 --> <setting name="aggressiveLazyLoading" value="false"/> </settings> <!--寫了別名就可以在mapper.xml文件中直接寫類名--> <typeAliases> <package name="com.demo.web.model"></package> </typeAliases> <plugins> <plugin interceptor="com.demo.core.feature.orm.mybatis.PaginationResultSetHandlerInterceptor"/> <plugin interceptor="com.demo.core.feature.orm.mybatis.PaginationStatementHandlerInterceptor"/> </plugins> </configuration>
1.5配置ehcache.xml文件,緩存管理配置
<?xml version="1.0" encoding="UTF-8"?> <ehcache updateCheck="false" name="txswx-ehcache"> <!-- 磁盤存儲:將緩存中暫時不使用的對象,轉移到硬盤,類似於Windows系統的虛擬內存 path:指定在硬盤上存儲對象的路徑 --> <diskStore path="java.io.tmpdir"/> <!-- defaultCache:默認的緩存配置信息,如果不加特殊說明,則所有對象按照此配置項處理 maxElementsInMemory:設置了緩存的上限,最多存儲多少個記錄對象 eternal:代表對象是否永不過期 timeToIdleSeconds:最大的發呆時間 timeToLiveSeconds:最大的存活時間 overflowToDisk:是否允許對象被寫入到磁盤 --> <defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" maxEntriesLocalDisk="100000"/> </ehcache>
1.6創建springmvc.xml
1.6.1基礎配置創建過程:(1)把controller層的註解納入管理(2)模型視圖前後綴管理(3)springmvc上傳文件配置(4)整合shiro框架配置
1.6.2代碼:(較為復雜的配置,不是基礎配置)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--controller層註入--> <context:component-scan base-package="com.demo.web.controller"/> <!-- 指定自己定義的validator --> <mvc:annotation-driven validator="validator"/> <!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 會 自動註冊 --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!-- 如果不加默認到 使用classpath下的 ValidationMessages.properties --> <property name="validationMessageSource" ref="messageSource"/> </bean> <!-- 國際化的消息資源文件(本系統中主要用於顯示/錯誤消息定制) --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <!-- 在web環境中一定要定位到classpath 否則默認到當前web應用下找 --> <value>classpath:messages</value> <value>classpath:org/hibernate/validator/ValidationMessages</value> </list> </property> <property name="useCodeAsDefaultMessage" value="false"/> <property name="defaultEncoding" value="UTF-8"/> <property name="cacheSeconds" value="60"/> </bean> <!--配置攔截器--> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> </mvc:interceptors> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <property name="defaultLocale" value="zh_CN"/> </bean> <!--支持返回json(避免IE在ajax請求時,返回json出現下載 )--> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter"/> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!--模型視圖增加前後綴--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp"/> <!--springMvc上傳文件--> <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> <!--啟用shiro授權註解方式--> <aop:config proxy-target-class="true"></aop:config> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> </beans>
1.7application_shiro.xml文件配置
1.7.1創建過程:(1)shiro過濾器配置(包括安全管理器,登錄頁面,登錄成功頁面,沒有訪問權限頁面,權限設置)(2)會話DAO(3)會話管理器,需要會話DAO(4)緩存管理器,需要緩存管理配置文件路徑(5)reamls配置,需要自定義的realm類(6)安全管理器,需要reamls配置(7)shiro生命周期處理器
1.7.2代碼:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util" 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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <description>apache shiro配置</description> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!--配置securityManager 安全管理器--> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="/page/login.shtml"/> <property name="successUrl" value="/index.shtml"/> <property name="unauthorizedUrl" value="/page/401.shtml"/> <property name="filterChainDefinitions"> <value> <!-- 靜態資源允許訪問 --> /app/** = anon /assets/** = anon <!-- 登錄頁允許訪問 --> /user/login = anon <!-- 其他資源需要認證 --> /** = authc </value> </property> </bean> <!--緩存管理器--> <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/> </bean> <!--會話DAO--> <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/> <!--會話管理器--> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <property name="sessionDAO" ref="sessionDAO"/> </bean> <!--登錄規則--> <bean id="securityRealm" class="com.cjw.web.security.SecurityRealm"/> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realms"> <list> <ref bean = "securityRealm"/> </list> </property> </bean> <!-- Shiro生命周期處理器 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans>
1.8ehcache-shiro.xml配置
<ehcache updateCheck="false" name="shiroCache"> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache>
1.9 web.xml配置
1.9.1創建過程:(1)spring文件初始化配置(2)spring上下文監聽器配置(3)spring編碼過濾器配置(4)log4j初始化配置(5)log4j監聽器配置(6)shiro過濾器配置(7)前端控制器配置(8)錯誤頁面配置
ssm框架配置過程