• springmvc.xml,context.xml和web.xml


    1:springmvc.xml配置要点

    一般它主要配置Controller的组件扫描器和视图解析器

    下为:springmvc.xml文件

     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="
     9         http://www.springframework.org/schema/beans 
    10         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
    11         http://www.springframework.org/schema/context 
    12         http://www.springframework.org/schema/context/spring-context-4.2.xsd 
    13         http://www.springframework.org/schema/mvc 
    14         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
    15         http://www.springframework.org/schema/task 
    16         http://www.springframework.org/schema/task/spring-task-4.2.xsd">    
    17       <!--spring.xml文件:一般它主要配置Controller的组件扫描器和视图解析器  -->
    18         <!-- 使用注解开发,不用配置controller,需要配置一个组件扫描器 -->  
    19         <context:component-scan base-package="com.edu.test.controller"/>
    20         
    21         <!--*************** 支持aop **************** -->
    22         <aop:aspectj-autoproxy proxy-target-class="true" />
    23          
    24         <mvc:resources location="/img/" mapping="/img/**" />
    25         <!-- /js/文件夹下的文件不需要拦截 -->
    26         <mvc:resources location="/js/" mapping="/js/**" />
    27         <!-- /css/文件夹下的文件不需要拦截 -->
    28         <mvc:resources location="/css/" mapping="/css/**" />
    29     
    30         <!-- 支持用注解的方式验证参数格式正确性 -->  
    31         <mvc:annotation-driven validator="validator" conversion-service="conversion-service" />
    32         <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    33         <!-- <property name="providerClass"  value="org.hibernate.validator.HibernateValidator"/> -->
    34         <!--不设置则默认为classpath下的 ValidationMessages.properties
    35         <property name="validationMessageSource" ref="validatemessageSource"/> -->
    36         </bean>
    37         <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
    38         <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
    39             <property name="basename" value="classpath:validatemessages"/>  
    40             <property name="fileEncodings" value="utf-8"/>  
    41             <property name="cacheSeconds" value="120"/>
    42         </bean>
    43         
    44         <!-- 拦截器 -->
    45         <mvc:interceptors>
    46             <mvc:interceptor>
    47                 <mvc:mapping path="/api/*"/>
    48                 <bean class="com.parry.test.interceptor.SignatureCheckInterceptor"></bean>
    49             </mvc:interceptor>
    50             <mvc:interceptor>
    51                 <mvc:mapping path="/web/*"/>
    52                 <bean class="com.parry.test.interceptor.AccessCheckInterceptor"></bean>
    53             </mvc:interceptor>
    54         </mvc:interceptors>
    55         <mvc:annotation-driven>
    56         </mvc:annotation-driven>
    57     
    58         <!-- 视图解析器 -->                
    59         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    60             <!-- 配置从项目根目录到指定目录一端路径 ,建议指定浅一点的目录-->
    61             <property name="prefix" value="/WEB-INF/jsp/"></property>
    62             <!-- 文件的后缀名 -->
    63             <property name="suffix" value=".jsp"></property>
    64         </bean>
    65         
    66           <!-- 文件上传配置 -->
    67         <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    68              <!-- 设置上传文件的最大尺寸为1MB -->
    69              <property name="maxUploadSize">  
    70                 <value>1048576</value>  
    71             </property>
    72             <property name="defaultEncoding">
    73                 <value>UTF-8</value>
    74             </property> 
    75         </bean>
    76 </beans>

    2:applicationContext.xml配置要点(在web.xml文件需要加<listener>)

    下为:applicationContext.xml文件

      1 <beans xmlns="http://www.springframework.org/schema/beans"
      2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      3     xmlns:context="http://www.springframework.org/schema/context"
      4     xmlns:aop="http://www.springframework.org/schema/aop"
      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-4.2.xsd
      8         http://www.springframework.org/schema/context
      9        http://www.springframework.org/schema/context/spring-context-4.2.xsd
     10        http://www.springframework.org/schema/aop
     11        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
     12        http://www.springframework.org/schema/tx
     13        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
     14      <!-- 配置组件扫描器,使用注解方式开发,不用配置dao和service -->      <!-- 在springmvc.xml文件中也可以配置这个属性 -->  
     15      <context:component-scan base-package="com.edu.test"/>
     16       
     17     <!-- 数据库配置 -->
     18     <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
     19         destroy-method="close">
     20         <property name="driverClass" value="com.mysql.jdbc.Driver" />
     21          <!-- 测试数据库 -->
     22         <property name="jdbcUrl"  value="jdbc:mysql://127.0.0.1:3066/TESTDB?useUnicode=true&amp;characterEncoding=UTF-8&amp;allowMultiQueries=true" />
     23         <property name="username" value="root" />
     24         <property name="password" value="root" />
     25         
     26         <!-- 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 -->
     27         <property name="idleConnectionTestPeriod" value="240" />
     28         <!-- 连接池中未使用的链接最大存活时间,单位是分,默认值:30,如果要永远存活设置为0 -->
     29         <!-- 数据库连接池过期时间应小于等于mysql的过期时间和mycat的过期时间 -->
     30         <property name="idleMaxAge" value="20" />
     31         <!-- 每个分区最大的连接数 -->
     32         <property name="maxConnectionsPerPartition" value="100" />
     33         <!-- 每个分区最小的连接数 -->
     34         <property name="minConnectionsPerPartition" value="20" />
     35         <!-- 分区数 ,默认值2,最小1,推荐3-4,视应用而定 -->
     36         <property name="partitionCount" value="1" />
     37         <!-- 每次去拿数据库连接的时候一次性要拿几个,默认值:2 -->
     38         <property name="acquireIncrement" value="2" />
     39         <!-- 缓存prepared statements的大小,默认值:0 -->
     40         <property name="statementsCacheSize" value="0" />
     41         <property name="connectionTimeoutInMs" value="100" />
     42         <!-- 每个分区释放链接助理进程的数量,默认值:3,除非你的一个数据库连接的时间内做了很多工作,不然过多的助理进程会影响你的性能 -->
     43         <property name="releaseHelperThreads" value="3" />
     44     </bean>
     45     <!-- 配置SqlSessionFactoryBean -->
     46     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     47         <property name="dataSource" ref="dataSource" />
     48         <property name="configLocation" value="classpath:mybatis.xml" />
     49         <!-- mapper和resultmap配置路径 -->
     50         <property name="mapperLocations">
     51             <list>
     52                 <!-- 表示在com.sfpay.mapper包或以下所有目录中,以-resultmap.xml结尾所有文件 -->
     53                 <value>classpath:com/parry/test/dao/config/*.xml</value>
     54             </list>
     55         </property>
     56     </bean>
     57     <!-- 使用接口类实现mybatis mapper接口 https://blog.csdn.net/Edison_03/article/details/72796691 -->
     58     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     59         <property name="basePackage" value="com.cn21.calendar.dao" />
     60         <!--下面这个省略掉的话也不会出错,建议保留它-->
     61         <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
     62         <!--下面这个省略掉的话也不会出错,建议保留它-->
     63         <property name="annotationClass" value="framework.database.annotation.Dao"/>
     64         <!-- -->
     65     </bean>
     66     <!--使用模板类实现mybatis -->
     67     <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
     68         <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
     69         <constructor-arg name="executorType" value="BATCH"></constructor-arg>
     70         <constructor-arg name="exceptionTranslator" ref="myBatisExceptionTranslator"></constructor-arg>
     71     </bean>
     72    
     73     <!-- 事务配置 -->
     74     <bean id="transactionManager"
     75         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     76         <property name="dataSource" ref="dataSource" />
     77     </bean>
     78     <!-- 用于持有ApplicationContext,可以使用SpringContextHolder.getBean('xxxx')的静态方法得到spring 
     79         bean对象 -->
     80     <bean class="com.parry.test.springcontext.SpringContextHolder" lazy-init="false" />
     81 
     82     
     83     <!-- 配置AOP通知 -->
     84     <tx:advice id="txAdvice" transaction-manager="transactionManager">
     85          <!-- 配置事务属性 -->
     86          <tx:attributes>
     87              <!-- 添加事务管理的方法 -->
     88              <tx:method name="save*" propagation="REQUIRED"/>
     89              <tx:method name="delete*" propagation="REQUIRED"/>
     90              <tx:method name="update*" propagation="REQUIRED"/>
     91              <tx:method name="select*" read-only="true"/>
     92          </tx:attributes>
     93      </tx:advice>
     94      
     95      <!-- 配置AOP,为添加事务管理的操作配置AOP -->
     96     <aop:config>
     97         <!-- 引入的Spring定义的事务通知,需要使用aop:advisor -->
     98         <!-- 下面难 -->
     99         <aop:advisor advice-ref="txAdvice"
    100             pointcut="execution(* com.edu.test.service.*.*(..))"
    101         />
    102     </aop:config>
    103     <!-- 服务器启动,初始化项目配置参数 -->
    104     <bean name="InitalizeBean" class="com.parry.test.configure.impl.InitalizeBean" />
    105       <!-- 定时器 begin -->
    106     <!-- 赛程 调度业务对象 -->
    107     <bean id="deletePastOrderJob" class="com.parry.test.function.PublicTypeFunction" />
    108     <!-- 赛程 调度业务 -->
    109     <bean id="deletePastOrderTask"
    110         class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    111         <property name="targetObject" ref="deletePastOrderJob" />
    112         <property name="targetMethod" value="deletePastOrder" />
    113     </bean>
    114     <!-- 赛程 调度器触发器 每天早上07:00执行一次 -->
    115     <bean id="deletePastOrderTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    116         <property name="jobDetail" ref="deletePastOrderTask" />
    117         <property name="cronExpression" value="0 13 09 * * ? *" />
    118     </bean>
    119     <!-- 设置调度 -->
    120     <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    121         <property name="triggers">
    122             <list>
    123                 <!-- <ref bean="deletePastOrderTaskTrigger" /> -->
    124             </list>
    125         </property>
    126     </bean>
    127     <!-- 定时器 end -->
    128 </beans>

    这里简单介绍一下spring的配置文件applicationContext.xml中的一些配置的作用。

    <context:component-scan base-package=""/>

    表示启动spring的组件扫描功能(从spring2.5版本开始)。即扫描base-package包或者子包下面的Java文件,如果扫描到有@controller、@Service、@Repository、@Component等注解的java类,就会将这些bean注册到工厂中。还可以使用分号来分隔多个扫描包。 

    如果在配置文件中配置了<context:component-scan />,就不用在配置<context:annotation-config/>,因为前者已经包含了后者。<context:annotation-config/>的作用是向spring容器注入AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 及RequiredAnnotationBeanPostProcessor 四个beanPostProcessor。从而使得@Autowired等注解生效。

    <mvc:annotation-driven />

    <mvc:annotation-driven />是告知Spring,我们启用注解驱动。然后Spring会自动为我们注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter等几个Bean到工厂中,此时我们可以使用@RequestMapping、@Valid注解来处理请求,也可以使用@ResponseBody来处理返回结果。

    复制代码
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
       <list>
        <value>/WEB-INF/mail.properties</value>  
        <value>classpath: conf/sqlmap/jdbc.properties</value></list>
      </property>
    </bean>
    复制代码

    PropertyPlaceholderConfigurer可以将上下文(配置文件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进 行修改,而不用对xml配置文件进行修改。

    上面有两种value的写法,其中classpath是引用src目录下的文件写法。

    <bean scope="singleton" id="dataSource"    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />        
    </bean>

    DriverManager类的主要作用是管理注册到DriverManager中的JDBC驱动程序,并根据需要使用JDBC驱动程序建立与数据服务器的网络连接。

    DriverManagerDataSource在每个连接请求时都新建一个连接,但是建立与数据库的连接是一项较耗资源的工作,频繁的进行数据库连接建立操作会产生较大的系统开销,为了解决上述问题,可以采用数据库连接池技术,例如dbcp、c3p0、druid(spring配置数据库连接池druid)。

    复制代码
    <!-- 配置mybatis的SessionFactory -->
        <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="configLocation" value="classpath:conf/mybatis-config.xml" />
            <property name="mapperLocations">
                <array>
                    <value>classpath:com/wdcloud/fayu/mapper/*Mapper.xml</value>
                </array>
            </property>
            <!-- 配置此项则在mapper中可以直接使用实体类名,而不需要使用全路径名 -->
            <property name="typeAliasesPackage" value="com.wdcloud.fayu.entity" />
        </bean>
    
        <!-- 自动扫描注册mapper接口类(接口类实现mybatis) -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.wdcloud.fayu.mapper" />
        </bean>
    
       <!-- sqlSessionTemplate配置(模板类实现mybatis) -->
       <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    复制代码

    上面为mybatis在spring中的配置,其中有两种实现方式:接口类实现和模板类实现。

    接口类实现: mybatis-spring效仿spring的风格提供了一个模板类SqlSessionTemplate,可以通过模板类轻松访问数据库,但是这种方法使用字符串指定映射项,容易引起错误,因为字符串本身没有语义性,如果存在编写错误,编译器无法识别,只能在运行期发现。

    模板类实现:接口的名称和映射命名空间相同,接口方法和映射基的id相同,MapperScannerConfigurer将扫描basePackage所指定的包下的所有的接口类(包括子包),如果它们在sql映射文件中定义过,则将它们动态定义为Spring Bean,这样我们就可以在Service中直接注入映射接口的bean了。

    SqlSessionFactoryBean是mybatis的核心管理类,通过dataSource指定数据源,configLocation指定mybatis的配置文件,mapperLocations指定mapper的xml文件。

    MapperScannerConfigurer的作用是自动扫描注册mapper接口类到spring工厂中,当你的mapper接口类存在于多个目录下时,basePackage的值可以配置成多个目录,中间用英文逗号隔开即可。

    SqlSessionTemplate的作用是基于持久化模板类实现Mybatis(具体实现步骤)。

    3:在web.xml文件中,将springmvc.xml和applicationContext.xml一起引入

    下为:web.xm文件

     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     id="WebApp_ID" version="3.0">
     6     <!-- 配置监听器 -->
     7     <listener>
     8         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     9     </listener>
    10     <context-param>
    11         <param-name>contextConfigLocation</param-name>
    12         <param-value>classpath:applicationContext.xml</param-value>
    13     </context-param>
    14     
    15     <!-- 中央控制器 -->
    16     <servlet>
    17         <servlet-name>springmvc</servlet-name>
    18         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    19         <init-param>
    20             <param-name>contextConfigLocation</param-name>
    21             <param-value>classpath:springmvc.xml</param-value>
    22         </init-param>
    23     </servlet>
    24     <servlet-mapping>
    25         <servlet-name>springmvc</servlet-name>
    26         <url-pattern>*.do</url-pattern>
    27     </servlet-mapping>
    28     
    29     
    30     <!-- 配置Spring提供的字符编码过滤器 -->
    31     <filter>
    32         <filter-name>SpringCharacterEncodingFilter</filter-name>
    33         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    34         <init-param>
    35             <param-name>encoding</param-name>
    36             <param-value>UTF-8</param-value>
    37         </init-param>
    38     </filter>
    39     <filter-mapping>
    40         <filter-name>SpringCharacterEncodingFilter</filter-name>
    41         <url-pattern>*.do</url-pattern>
    42     </filter-mapping>
    43 </web-app>

    原文链接:http://www.cnblogs.com/kaiwen1/p/6864458.html

    https://www.cnblogs.com/Jason-Xiang/p/6544188.html

  • 相关阅读:
    自己实现一个hash类的vue-router插件/vue-router底层原理实现
    XSS攻击和防护
    浏览器缓存机制介绍之http缓存-强缓存-协商缓存
    chrome控制台查看网络性能指标-TTFB_Content Download_window.performance
    vscode创建vue快捷键
    移动端布局适配方案
    node生成token
    vue组件的讨论&容易忽略的知识点
    函数防抖
    webpack-搭建项目的代码
  • 原文地址:https://www.cnblogs.com/alice-cj/p/10424133.html
Copyright © 2020-2023  润新知