天天看点

ssm整合 的配置文件

目录

一、web.xml

        1、配置监听器,用来扫描classpath:applicationContext-*.xml下面的各类配置文件

        2、配置SPringMVC的核心处理器 DispatcherServlet

        3、SPring解决POST请求乱码

        4、form表单只支持 Get和POST  如果想支持rest风格  得配置该过滤器  然后该过滤器会帮我们实现

       5、rest请求的过滤器

二、spring-mvc.xml中的配置

三、applicationContext-service.xml中的配置

四、applicationContext-dao.xml的配置

     java自己的连接池

    c3p0连接池配置

    DBCP连接池

     jdbc.properties文件

五、log4j.properties测试文件,需要引入相关jar包

 六、service层

七、mapper包

    UserMapper.xml映射文件:

     别名:

    若要使用分页需要在pom中引入依赖:

七、控制器层测试

一、web.xml

1、配置监听器,用来扫描classpath:applicationContext-*.xml下面的各类配置文件

<!-- 配置Spring的配置文件 去加载spring的配置文件 -->
        <listener>
        <!-- 默认是去WEB-INF下找 applicationContext.xml配置文件-->
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        
        </listener>  
        
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-*.xml</param-value>
        </context-param>
           

2、配置SPringMVC的核心处理器 DispatcherServlet

url-patten标签说明:

    1./* 拦截所有请求 css img js jsp html action
    2.*.action/*.do *.action 可以拦截以.action结尾的请求
    3./ 拦截css js image action请求 不拦截jsp(推荐)

    <servlet>
            <servlet-name>DispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <!-- contextConfigLocation固定 -->
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-mvc.xml</param-value>
            </init-param>
            <!-- 启动服务器就实例化 -->
            <load-on-startup>1</load-on-startup>
     
        </servlet>
     
        <servlet-mapping>
            <servlet-name>DispatcherServlet</servlet-name>
            <!-- 1./* 拦截所有请求 css img js jsp html action 2.*.action/*.do *.action 可以拦截以.action结尾的请求
                3./ 拦截css js image action请求 不拦截jsp(推荐) -->
            <url-pattern>/</url-pattern>
     
        </servlet-mapping>
           

3、SPring解决POST请求乱码

<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>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
           

4、form表单只支持 Get和POST  如果想支持rest风格  得配置该过滤器  然后该过滤器会帮我们实现

<filter>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <filter-class>
                org.springframework.web.filter.HiddenHttpMethodFilter
            </filter-class>
        </filter>
        <filter-mapping>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
           

5、rest请求的过滤器

<filter>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <filter-class>
                org.springframework.web.filter.HiddenHttpMethodFilter
            </filter-class>
        </filter>
        <filter-mapping>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
           

二、spring-mvc.xml中的配置

静态资源static文件夹放在webapp文件夹下面

<?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:p="http://www.springframework.org/schema/p"
            xmlns:context="http://www.springframework.org/schema/context"
            xmlns:aop="http://www.springframework.org/schema/aop"
            xmlns:tx="http://www.springframework.org/schema/tx"
            xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="
           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/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
           
           <!-- 开发SpringMvc的配置文件 -->
          
           <context:component-scan base-package="com.ssm.controller"></context:component-scan>
            <!-- 开启组件扫描 -->
             <mvc:annotation-driven></mvc:annotation-driven>
             
           <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                   
                   <property name="prefix" value="/WEB-INF/jsp/"></property>
                   <property name="suffix" value=".jsp" ></property>
                   
           </bean>
           
           <!-- 用来过滤静态资源法 -->
           <mvc:resources location="/static/" mapping="/static/**"></mvc:resources>
           
           <!-- 配置文件上传相关 -->
               <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
               p:defaultEncoding="utf-8"
               p:maxUploadSize="1048576"
               p:uploadTempDir="file:D:\temp"
               >
               </bean>
           </beans>
           

三、applicationContext-service.xml中的配置

 开启事务注解驱动的情况下需要要在service层加@Transactional注解,不然就用如下注释中的<tx:advice id="txAdvice" transaction-manager="transactionManager">的方式

<?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:p="http://www.springframework.org/schema/p"
            xmlns:context="http://www.springframework.org/schema/context"
            xmlns:aop="http://www.springframework.org/schema/aop"
            xmlns:tx="http://www.springframework.org/schema/tx"
            xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="
           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/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
           
           <!-- 开发SpringMvc的配置文件 -->
           <!-- 开启组件扫描 -->
           <context:component-scan base-package="com.ssm.service"></context:component-scan>
           
               <!-- 配置事务 -->
               <!-- 配置平台事务管理器 -->
               <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                   <!-- 现在注入dataSource -->
                   <property name="dataSource" ref="dataSource"></property>
               </bean>
               <!-- 事务注解驱动 -->
           <tx:annotation-driven transaction-manager="transactionManager"/>
               
               <!-- 配置事务通知 -->
               <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager">
                   <tx:attributes>
                       <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
                       <tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
                       <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
                       <tx:method name="search*" propagation="SUPPORTS" read-only="true"/>
                       <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
                       
                       
                       <tx:method name="add*" propagation="REQUIRED" />
                       <tx:method name="save*" propagation="REQUIRED" />
                       <tx:method name="insert*" propagation="REQUIRED" />
                       <tx:method name="delete*" propagation="REQUIRED" />
                       <tx:method name="update*" propagation="REQUIRED" />
                       <tx:method name="modify*" propagation="REQUIRED" />
                       <tx:method name="remove*" propagation="REQUIRED" />
                       
                       <tx:method name="*" propagation="REQUIRED" />
                   
                   </tx:attributes>
               
               </tx:advice> -->
               
               <!-- 配置aop -->
               
               <!-- <aop:config proxy-target-class="true">
                   <aop:pointcut expression="execution( public * com.ssm.service.impl.*.*(..))" id="cut"/>
                   <aop:advisor advice-ref="txAdvice" pointcut-ref="cut"/>
               </aop:config> -->
          
           
           </beans>
           

四、applicationContext-dao.xml的配置

此处省去了头文件,使用了druid连接池,c3p0,dbcp,连接池单独放下面

<!-- 开启组件扫描 -->
           <context:component-scan base-package="com.ssm.mapper"></context:component-scan>
           
            <context:property-placeholder location="classpath:*.properties"/>
           
            <!-- 配置数据源 -->
            <!-- 配置druid连接池 -->
           <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
            init-method="init" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <!-- 配置初始化大小、最小、最大 -->
            <property name="initialSize" value="20" />
            <property name="minIdle" value="3" />
            <property name="maxActive" value="100" />
     
            <!-- 配置获取连接等待超时的时间 -->
            <property name="maxWait" value="10000" />
     
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
     
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="300000" />
     
            <property name="testWhileIdle" value="true" />
     
            <!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
            <property name="testOnBorrow" value="true" />
            <property name="testOnReturn" value="false" />
     
            <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
            <property name="poolPreparedStatements" value="true" />
            <property name="maxPoolPreparedStatementPerConnectionSize"
                value="20" />
     
            <!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
     
            <property name="defaultAutoCommit" value="true" />
     
            <!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
            <property name="validationQuery" value="select 1 " />
            <property name="filters" value="stat" />
        </bean>
      
           <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
               <property name="dataSource" ref="dataSource"></property>
               <!-- 配置别名,类名不区分大小写 -->
               <property name="typeAliasesPackage" value="com.ssm.model"></property>
           
               <!-- 引入sql映射文件 -->
               <property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
               
               <!-- 配置分页 -->
            <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <!-- 配置参数 -->
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>
               
           </bean>
           
          <!--  <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
               注入接口 模拟类
               <property name="mapperInterface" value="com.ssm.mapper.userMapper"></property>
               注入sqlsossionfactory
               <property name="sqlSessionFact" value="sqlSessionFactory"></property>
           </bean> -->
           
           <!-- id默认是接口名小写 -->
           <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
               <property name="basePackage" value="com.ssm.mapper"></property>
               <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
           
           </bean>
           </beans>
           

java自己的连接池

<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="username" value="root"></property>
            <property name="password" value="123"></property>
            <property name="url" value="jdbc:mysql:///hibernate?useUnicode=true&amp;characterEncoding=utf8"></property>
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        </bean>
           

c3p0连接池配置

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="user" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
            <property name="jdbcUrl" value="${jdbc.url}"></property>
            <property name="driverClass" value="${jdbc.driverClassName}"></property>
            <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
            <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
        </bean>
           

DBCP连接池

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        </bean>
           

 jdbc.properties文件

jdbc.username=root
    jdbc.password=123
    jdbc.url=jdbc:mysql:///hibernate?useUnicode=true&amp;characterEncoding=utf8
    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.maxPoolSize=200
    jdbc.initialPoolSize=20
           

五、log4j.properties测试文件,需要引入相关jar包

# Global logging configuration
    log4j.rootLogger=INFO, stdout
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.err
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
           

 六、service层

在service实现类中直接注入mybatis的UserMapper接口类,前提是在applicationContext-dao.xml中配置了如下内容,以实现接口的实现类

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
               <property name="basePackage" value="com.ssm.mapper"></property>
               <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
         </bean>
           
@Service
    @Transactional
    public class UserServiceImpl implements UserService{
        @Autowired
        private UserMapper userMapper;
        @Override
        public List<User> queryAllUser() {
            List<User> list = userMapper.queryAllUser();
            //System.out.println("service");
            return list;
        }
     
    }
           

七、mapper包

UserMapper接口

public interface UserMapper {
     
        List<User> queryAllUser();
        
    }
           

UserMapper.xml映射文件:

resultType="user"前提是在applicationContext-dao.xml中配置了别名

<?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     
    <mapper namespace="com.ssm.mapper.UserMapper">
     
        <select id="queryAllUser"  resultType="user">
            select * from tb_user
        </select>
    </mapper>
           

 别名:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
               <property name="dataSource" ref="dataSource"></property>
               <!-- 配置别名,类名不区分大小写 -->
               <property name="typeAliasesPackage" value="com.ssm.model"></property>
           
               <!-- 引入sql映射文件 -->
               <property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
          
           </bean>
           

若要使用分页需要在pom中引入依赖:

<dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>${mybatis.pagehelper.version}</version>
            </dependency>
           

七、控制器层测试

@Controller
    public class UserController {
        @Autowired
        private UserService userService;
            
        @RequestMapping("/showUser")
        public String showUser(Model model,@RequestParam(defaultValue="4")Integer pageSize,
                @RequestParam(defaultValue="1")Integer currentPage) {
            Page<Object> page = PageHelper.startPage(currentPage, pageSize);//
            
            List<User> list = userService.queryAllUser();
            
            PageInfo<User> pageInfo = new PageInfo<>(list, 4);
            model.addAttribute("list", list);
            model.addAttribute("NavigatepageNums", pageInfo.getNavigatepageNums());
            
            model.addAttribute("page",pageInfo);
            
            return "allusers";
            //return "allUser";
        }
    }
           

继续阅读