spingmvc相关配置

  • Post author:
  • Post category:其他




一、springmvc相关依赖

		<!--
			1.使用springmvc+mybatis+mysql开发,可以使用这些依赖
			2.有额外的事务spring-tx依赖、用于aop切面的依赖spring-aop、spring-aspects
			3.测试环境junit的依赖(搭配spring-text和javax.servlet-api)
			4.后端接口测试swagger依赖
			5.日志依赖slf4j-log4j12
			6.任务调度框架quartz的依赖			
		-->
		<!--springmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>


        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <!--测试环境需要这个servlet,这个依赖要放在servlet-api上面,不然测试环境引用的可能时下面的依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <!--开发时只需要这个-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!--这个的话springmvc访问有些问题,所以不配置也可以,使用旧的swagger界面-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.3</version>
        </dependency>

        <!--lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>

        <!--日志-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>

        <!--测试环境-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>

        <!--任务调度框架-->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.1</version>
        </dependency>


        <!--提供这个spring-context才有任务调度相关的类-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>



二、springmvc配置



dp.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ruodui_database?serverTimezone=GMT%2B8&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8
user=root
password=123456



lo4j.properties

#############
# 输出到控制台
#############

# log4j.rootLogger日志输出类别和级别:只输出不低于该级别的日志信息DEBUG < INFO < WARN < ERROR < FATAL
# WARN:日志级别     CONSOLE:输出位置自己定义的一个名字       logfile:输出位置自己定义的一个名字
#log4j.rootLogger=DEBUG,CONSOLE,logfile
log4j.rootLogger=INFO,CONSOLE,logfile

# 配置CONSOLE输出到控制台
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 
# 配置CONSOLE设置为自定义布局模式
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 
# 配置CONSOLE日志的输出格式  [frame] 2019-08-22 22:52:12,000  %r耗费毫秒数 %p日志的优先级 %t线程名 %C所属类名通常为全类名 %L代码中的行号 %x线程相关联的NDC %m日志 %n换行
#log4j.appender.CONSOLE.layout.ConversionPattern=[frame] %d{yyyy-MM-dd HH:mm:ss,SSS} - %-4r %-5p [%t] %C:%L %x - %m%n
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} - %-4r %C:%L %x - %m%n

################
# 输出到日志文件中
################

# 配置logfile输出到文件中 文件大小到达指定尺寸的时候产生新的日志文件
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
# 保存编码格式
log4j.appender.logfile.Encoding=UTF-8
# 输出文件位置此为项目根目录下的logs文件夹中
#log4j.appender.logfile.File=logs/root.log
log4j.appender.logfile.File=d:/log4j.log
# 后缀可以是KB,MB,GB达到该大小后创建新的日志文件
log4j.appender.logfile.MaxFileSize=10MB
# 设置滚定文件的最大值3 指可以产生root.log.1、root.log.2、root.log.3和root.log四个日志文件
log4j.appender.logfile.MaxBackupIndex=3  
# 配置logfile为自定义布局模式
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n

##########################
# 对不同的类输出不同的日志文件
##########################

# club.bagedate包下的日志单独输出
log4j.logger.club.bagedate=DEBUG,bagedate
# 设置为false该日志信息就不会加入到rootLogger中了
log4j.additivity.club.bagedate=false
# 下面就和上面配置一样了
log4j.appender.bagedate=org.apache.log4j.RollingFileAppender
log4j.appender.bagedate.Encoding=UTF-8
log4j.appender.bagedate.File=logs/bagedate.log
log4j.appender.bagedate.MaxFileSize=10MB
log4j.appender.bagedate.MaxBackupIndex=3
log4j.appender.bagedate.layout=org.apache.log4j.PatternLayout
log4j.appender.bagedate.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n



#定义根据error获取的logger的属性,用于输出错误信息到错误日志
#private static final Logger error=LoggerFactory.getLogger("error");这种方式获取
log4j.logger.error= ERROR, errorFile
#默认输出位置都是在rootLogger的文件位置
log4j.additivity.error=false

# 配置logfile输出到文件中 文件大小到达指定尺寸的时候产生新的日志文件
log4j.appender.errorFile=org.apache.log4j.RollingFileAppender
# 保存编码格式
log4j.appender.errorFile.Encoding=UTF-8
# 输出文件位置此为项目根目录下的logs文件夹中
#log4j.appender.logfile.File=logs/root.log
log4j.appender.errorFile.File=d:/error.log
# 后缀可以是KB,MB,GB达到该大小后创建新的日志文件
log4j.appender.errorFile.MaxFileSize=10MB
# 设置滚定文件的最大值3 指可以产生root.log.1、root.log.2、root.log.3和root.log四个日志文件
log4j.appender.errorFile.MaxBackupIndex=3  
# 配置logfile为自定义布局模式
log4j.appender.errorFile.layout=org.apache.log4j.PatternLayout
log4j.appender.errorFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n



mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
   		 <!--使用的日志-->
        <setting name="logImpl" value="slf4j"/>
        <!--二级缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

	<!--包扫描别名-->
    <typeAliases>
        <package name="com.xxf.demo.pojo"/>
    </typeAliases>

</configuration>



spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!--加载db配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--配置数据原-->
    <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${driver}"/>
        <property name="jdbcUrl" value="${url}"/>
        <property name="user" value="${user}"/>
        <property name="password" value="${password}"/>

        <!--最小连接数量-->
        <property name="minPoolSize" value="5"/>
        <!--最大连接数量-->
        <property name="maxPoolSize" value="10"/>
        <!--初始连接数量-->
        <property name="initialPoolSize" value="7"/>
        <!--连接的最大存活时间,为0则不清除-->
        <property name="maxIdleTime" value="60"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     	<!--数据源-->
        <property name="dataSource" ref="datasource"/>
 	    <!--mybatis配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--mapper扫描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xxf.demo.mapper"/>
        <!--需要sqlSessionFactory依赖,value对应bean的id-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>


</beans>



spring事务配置:spring-tx.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">


    <!--aop注解开启,未开启不能使用注解的aop-->
    <aop:aspectj-autoproxy/>

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"/>
    </bean>
	
	 <!--开启事务注解-->
   <tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!--事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    		<!--为save、add、update等前缀开头的方法,开启事务,并且指定传播行为等信息-->
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="remove*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" rollback-for="Exception"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" rollback-for="Exception"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>
    
    <!--将通知于切点配置一起,aop切面就完成了-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.xxf.demo.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
    
</beans>



spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd 
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-4.3.xsd">

    <mvc:default-servlet-handler/>

    <!--扫描component-->
    <context:component-scan base-package="com.xxf.demo"/>
    <!--加载处理器映射器与处理器适配器-->
    <mvc:annotation-driven />

	<!--下面的配置,需要相关的类,可以自行删除!!!!-->

    <!--拦截器:登录拦截器、权限拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/**/*.*"/>
            <mvc:exclude-mapping path="/error/**"/>
            <mvc:exclude-mapping path="/login*"/>
            <mvc:exclude-mapping path="/swagger-resources/**"/>
            <mvc:exclude-mapping path="/v2/**"/>
            <bean class="com.xxf.demo.Interceptor.LoginInterceptor"/>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/power/**"/>
            <mvc:exclude-mapping path="/**/*.*"/>
            <bean class="com.xxf.demo.Interceptor.PowerInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

    <!--注解任务调度,先开启注解支持-->
    <task:annotation-driven executor="poolTaskExecutor" scheduler="poolTaskScheduler"/>
    
    <!--任务调度器配置--> 
    <task:scheduled-tasks>
    	<!--配置ref指定Job类,method指定里面的方法,cron为触发器表达式--> 
        <task:scheduled ref="sessionTimeTask" method="clearTimeOutSession" cron="0 45 * * * ?" />
        <!--这样就配置了一个调度器,而下面配置了三个bean跟这里配置是等价的,下面先配置一个job,然后配置jobTrigger,最后才是一个调度器scheduled--> 
    </task:scheduled-tasks>
    <!--调度器scheduled最大数量-->
    <task:scheduler id="poolTaskScheduler" pool-size="2"/>
    <!--调度器scheduled里的线程最大数量-->
    <task:executor id="poolTaskExecutor" pool-size="1"/>

    <!--job任务-->
    <bean id="job" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="sessionTimeTask"/>
        <property name="targetMethod" value="exportUserNumber"/>
        <!--并发设置,为true就支持并发,false就不支持-->
        <!--例如为false,我们有俩个jboTrigger触发器,指向同一个job,那么不支持并发的话,就相当于使用了synchronized同步代码块,一次只能进入一个-->
        <property name="concurrent" value="false"/>
    </bean>

    <!--job触发器-->
    <bean id="jobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="job"/>
        <property name="cronExpression" value="0 30/30 * * * ?"/>
    </bean>


    <!--另一种写法的trigger-->
   <!-- <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="job" />
        <property name="startDelay" value="10000" />
        <property name="repeatInterval" value="60000" />
    </bean>-->

    <bean id="scheduler1" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="jobTrigger"/>
            </list>
        </property>
    </bean>
    
  
</beans>



applicationContext.xml

<!--最后将三个配置文件集中,要按顺序,dao要站在tx上面,因为数据源需要先配置-->

<import resource="classpath:spring-context.xml"/>
 <import resource="classpath:spring-dao.xml"/>
 <import resource="classpath:spring-tx.xml"/>



web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
	<!--会话监听器,实现HttpSessionListener该接口,就可以进行session监听了-->
   <!-- <listener>
        <listener-class>com.xxf.demo.listener.MySessionListener</listener-class>
    </listener>-->

    <!--60分钟-->
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:applicationContext.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


	<!--中文乱码过滤器-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--设置项目中使用的字符编码-->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        <!--强制请求对象(HttpServletRequest)使用encoding编码的值-->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--强制应答对象(HttpServletResponse)使用encoding编码的值-->
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>



版权声明:本文为pzzzzzp原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。