zoukankan      html  css  js  c++  java
  • SpringMVC+Spring+Mybatis整合,使用druid连接池,声明式事务,maven配置

    一直对springmvc和mybatis挺怀念的,最近想自己再搭建下框架,然后写点什么。

    暂时没有整合缓存,druid也没有做ip地址的过滤。Spring的AOP简单配置了下,也还没具体弄,不知道能不能用,log也不知道能不能用,`(*∩_∩*)′哈哈,有点不负责任......

    复制代码
    2014-08-12 23:45补:

    =================开始================= 1、增加quartz :http://www.cnblogs.com/acehalo/p/3902731.html 2、mybatis添加ehcache缓存:http://www.cnblogs.com/acehalo/p/3902883.html 3、spring的aop: http://www.cnblogs.com/acehalo/p/3905718.html

    =================结束================
    复制代码

    直接上代码:

    使用的eclipse和eclipse自带的maven,参考了网上的资料,有些代码是拷贝的,不过都自己测试过了。嗯,可以跑起来...

    先上项目结构:

    新建maven项目,选择web,然后配置pom:

    复制代码
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>ACE</groupId>
        <artifactId>Test</artifactId>
        <packaging>war</packaging>
        <version>0.0.1-SNAPSHOT</version>
        <name>Test Maven Webapp</name>
        <url>http://maven.apache.org</url>
    
        <properties>
            <org.springframework.version>4.0.0.M2</org.springframework.version>
            <org.slf4j.version>1.6.1</org.slf4j.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
    
            <!-- servlet -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
    
            <!--mysql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.26</version>
            </dependency>
    
    
            <!-- spring -->
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${org.springframework.version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>commons-logging</groupId>
                        <artifactId>commons-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-instrument</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-instrument-tomcat</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jms</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-oxm</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc-portlet</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-websocket</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
    
            <!--mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.2.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.2.0</version>
            </dependency>
            <!-- Logging -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${org.slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>${org.slf4j.version}</version>
                <scope>runtime</scope>
            </dependency>
    
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.16</version>
                <scope>runtime</scope>
            </dependency>
    
    
        <!-- druid -->
        <dependency>  
            <groupId>com.alibaba</groupId>  
            <artifactId>druid</artifactId>  
            <version>1.0.7</version>  
    </dependency>
    
        </dependencies>
    
        <!-- 仓库 -->
        <repositories>
            <!-- For Hibernate Validator -->
            <repository>
                <id>org.jboss.repository.release</id>
                <name>JBoss Maven Release Repository</name>
                <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
            <repository>
                <id>org.springsource.maven.snapshot</id>
                <name>SpringSource Maven Central-compatible Snapshot Repository</name>
                <url>http://maven.springframework.org/snapshot</url>
                <snapshots>
                    <updatePolicy>daily</updatePolicy>
                </snapshots>
            </repository>
            <repository>
                <id>spring-milestone</id>
                <name>Spring Maven MILESTONE Repository</name>
                <url>http://maven.springframework.org/milestone</url>
            </repository>
            <repository>
                <id>standard repo</id>
                <url>http://repo1.maven.org/maven2</url>
            </repository>
            <repository>
                <id>mirror repo</id>
                <url>http://mirrors.ibiblio.org/pub/mirrors/maven2</url>
            </repository>
            <repository>
                <id>com.springsource.repository.bundles.release</id>
                <name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
                <url>http://repository.springsource.com/maven/bundles/release</url>
            </repository>
            <repository>
                <id>com.springsource.repository.bundles.external</id>
                <name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
                <url>http://repository.springsource.com/maven/bundles/external</url>
            </repository>
            <repository>
                <id>sqlfire-release</id>
                <url>http://dist.gemstone.com/maven/release</url>
            </repository>
        </repositories>
    
    
        <build>
            <finalName>Test</finalName>
        </build>
    </project>
    复制代码

    web.xml:

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        version="2.5">
    
    
    
    
        <!-- filter -->
        <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>
    
        <!-- listener -->
        <listener>
            <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
        </listener>
    
        <!-- servlet -->
        <servlet>
            <servlet-name>Test</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>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Test</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
        <error-page>
            <error-code>404</error-code>
            <location>/error/404.jsp</location>
        </error-page>
    
        <!-- druid -->
        <servlet>
            <servlet-name>DruidStatView</servlet-name>
            <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>DruidStatView</servlet-name>
            <url-pattern>/druid/*</url-pattern>
        </servlet-mapping>
    
    
    </web-app>
    复制代码

    applicationContext.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
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           ">
    
        <!-- spring 自动扫描组件 -->
        <context:component-scan base-package="com.hi.test"/>
        
        
        
        <import resource="spring-mvc.xml"/>
        <import resource="spring-database.xml"/>
        <import resource="spring-aop.xml"/>
    
    
    
        <bean id="log4jInitialization"
              class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
            <property name="targetClass"
                      value="org.springframework.util.Log4jConfigurer" />
            <property name="targetMethod" value="initLogging" />
            <property name="arguments">
                <list>
                    <value>classpath:log4j.xml</value>
                </list>
            </property>
        </bean>
    
    </beans>
    复制代码

    spring-mvc.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           ">
    
    
        <mvc:annotation-driven />
        <mvc:default-servlet-handler />
       
    
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
            <property name="prefix" value="WEB-INF/views/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
    </beans>
    复制代码

    spring-aop.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"
           xmlns:aop="http://www.springframework.org/schema/aop"
           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-3.2.xsd
           ">
       
        <!-- spring aop -->
        <aop:aspectj-autoproxy />
    
    
    </beans>
    复制代码

    spring-database.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    
        xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.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 
           
           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
           ">
    
    
    
        <!-- 数据源 org.apache.commons.dbcp.BasicDataSource com.alibaba.druid.pool.DruidDataSource -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
            <property name="username" value="root" />
            <property name="password" value="123456" />
    
    
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="0" />
            <!-- 连接池最大使用连接数量 -->
            <property name="maxActive" value="20" />
            <!-- 连接池最小空闲 -->
            <property name="minIdle" value="0" />
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="60000" />
    
    
            <property name="validationQuery"><value>SELECT 1</value></property> 
            <property name="testOnBorrow" value="false" />
            <property name="testOnReturn" value="false" />
            <property name="testWhileIdle" value="true" />
    
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="25200000" />
    
            <!-- 打开removeAbandoned功能 -->
            <property name="removeAbandoned" value="true" />
            <!-- 1800秒,也就是30分钟 -->
            <property name="removeAbandonedTimeout" value="1800" />
            <!-- 关闭abanded连接时输出错误日志 -->
            <property name="logAbandoned" value="true" />
    
            <!-- 监控数据库 -->
            <!-- <property name="filters" value="stat" /> -->
            <property name="filters" value="mergeStat" />
        </bean>
    
        <!-- 配置druid监控spring jdbc -->
        <bean id="druid-stat-interceptor"
            class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
        </bean>
        <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
            scope="prototype">
            <property name="patterns">
                <list>
                    <value>com.hi.test.service.*</value>
                </list>
            </property>
        </bean>
        <aop:config>
            <aop:advisor advice-ref="druid-stat-interceptor"
                pointcut-ref="druid-stat-pointcut" />
        </aop:config>
    
    
    
    
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
    
        <!-- 声明式事务 -->
        <tx:annotation-driven transaction-manager="transactionManager"
            proxy-target-class="true" />
    
    
    
    
    
    
    
    
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:mybatis-config.xml"></property>  
        </bean>
    
    
    
        <!-- 注册Mapper方式二:也可不指定特定mapper,而使用自动扫描包的方式来注册各种Mapper ,配置如下: -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    
            <property name="annotationClass" value="org.springframework.stereotype.Repository" />
            <property name="basePackage" value="com.hi.test.mapper" />
            <property name="sqlSessionFactory" ref="sqlSessionFactory" />
        </bean>
    
    
    
    
    
    </beans>
    复制代码

    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>  
        <mappers>  
            <mapper resource="com/hi/test/mapper/UserMapper.xml"/>  
        </mappers>  
    </configuration>  
    复制代码

    log4j.xml:

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE log4j:configuration PUBLIC "-//LOGGER" "log4j.dtd">
    
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    
        <!-- Appenders -->
        <appender name="console" class="org.apache.log4j.ConsoleAppender">
            <param name="Target" value="System.out" />
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%-5p: %c - %m%n" />
            </layout>
        </appender>
    
        <!-- 3rdparty Loggers -->
        <logger name="org.springframework.core">
            <level value="info" />
        </logger>
    
        <logger name="org.springframework.beans">
            <level value="info" />
        </logger>
        
        <logger name="org.springframework.context">
            <level value="info" />
        </logger>
    
        <logger name="org.springframework.web">
            <level value="info" />
        </logger>
    
        <logger name="org.mybatis">
            <level value="info" />
        </logger>
    
        <logger name="com.hi">
            <level value="info"/>
        </logger>
    
        <!-- Root Logger -->
        <root>
            <priority value="warn" />
            <appender-ref ref="console" />
        </root>
        
    </log4j:configuration>
    复制代码

    commons-logging.properties:

    org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

    IndexController:

    复制代码
    package com.hi.test.controller;
    
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.hi.test.bean.User;
    import com.hi.test.mapper.UserMapper;
    import com.hi.test.service.TxTestService;
    
    
    @Controller
    public class IndexController {
    
        @Autowired
        UserMapper userMapper;
        
        @Autowired
        TxTestService txTestService;
        
        @RequestMapping(value = "/index")
        public String index(HttpServletRequest request,Map model) {
            //String name=request.getParameter("name");
            //model.put("name", name);
     
            User u=new User();  
            u.setUsername("admin");  
            u.setPassword("admin");  
            User user=userMapper.selectUser(u);    
            model.put("user", user);
            return "hi";
        }
        
        @RequestMapping(value = "/text")
        @ResponseBody
        public String text(HttpServletRequest request) {
    
     
            
            return "{"what":"hi"}";
        }
        
        @RequestMapping(value = "/indexList")
        public String indexList(HttpServletRequest request,Map model) {
    
     
            List<User> userList=userMapper.selectUserLsit();
            model.put("userList", userList);
            
             return "hiList";
        }
        
        @RequestMapping(value = "/TxTest")
        @ResponseBody
        public String test(HttpServletRequest request) {
    
     
            txTestService.insert();
            
            return "";
        }
    }
    复制代码

    User:

    复制代码
    package com.hi.test.bean;
    
    public class User {
         private int id;  
            private String username;  
            private String password;  
            public User(){  
                  
            }  
            public int getId() {  
                return id;  
            }  
            public void setId(int id) {  
                this.id = id;  
            }  
            public String getUsername() {  
                return username;  
            }  
            public void setUsername(String username) {  
                this.username = username;  
            }  
            public String getPassword() {  
                return password;  
            }  
            public void setPassword(String password) {  
                this.password = password;  
            }  
            public String toString(){  
                 return "User [id = "+ id +" , username = "+ username +"]" + " , password = "+ password;  
            }  
    }
    复制代码

    UserMapper:

    复制代码
    package com.hi.test.mapper;
    
    import java.util.List;
    
    import org.springframework.stereotype.Repository;
    
    import com.hi.test.bean.User;
    
    @Repository
    public interface  UserMapper {
        public User selectUser(User user);  
        public void insertUser(User user);  
        public void updateUser(User user);  
        public void deleteUser(int userId);
        public List selectUserLsit();
    }
    复制代码

    UserMapper.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.hi.test.mapper.UserMapper">  
    
    <resultMap id="userList" type="com.hi.test.bean.User">  
            <id column="id" property="id" />  
            <result column="username" property="username" />  
            <result column="password" property="password" />  
        </resultMap>  
    
    
    <select id="selectUser" parameterType="com.hi.test.bean.User" resultType="com.hi.test.bean.User">  
        SELECT * FROM user WHERE username=#{username} AND password=#{password}  
    </select>  
    <insert id="insertUser" parameterType="com.hi.test.bean.User" flushCache="true">  
       INSERT INTO user (id,username,password) VALUES (#{id},#{username},#{password})  
    </insert>  
    <update id="updateUser" parameterType="com.hi.test.bean.User">  
        UPDATE user SET password=#{password} WHERE id=#{id}  
    </update>  
    <delete id="deleteUser" parameterType="int">  
        DELETE FROM user WHERE id=#{userId}  
    </delete>  
    
    <select id="selectUserLsit"  resultMap="userList">  
        SELECT * FROM user  
    </select>  
    </mapper>
    复制代码

    TxTestService:

    复制代码
    package com.hi.test.service;
    
    import java.util.UUID;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.hi.test.bean.User;
    import com.hi.test.mapper.UserMapper;
    
    @Transactional
    @Service
    public class TxTestService {
    
        @Autowired
        UserMapper userMapper;
    
        public void insert() {
            for (int i = 0; i < 100; i++) {
                User u = new User();
                u.setUsername(UUID.randomUUID().toString());
                u.setPassword(UUID.randomUUID().toString());
                userMapper.insertUser(u);
            }
            
            
            throw new RuntimeException();
        }
        
        
    }
    复制代码

     sql文件,navicat导出的:

    复制代码
    /*
    Navicat MySQL Data Transfer
    
    Source Server         : MySQL
    Source Server Version : 50704
    Source Host           : localhost:3306
    Source Database       : mydb
    
    Target Server Type    : MYSQL
    Target Server Version : 50704
    File Encoding         : 65001
    
    Date: 2014-08-09 23:52:32
    */
    
    SET FOREIGN_KEY_CHECKS=0;
    
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(255) NOT NULL,
      `password` varchar(255) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=902 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES ('1', 'admin', 'admin');
    复制代码

    index.jsp:

    复制代码
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    hi
    
    </body>
    </html>
    复制代码

    hi.jsp:

    复制代码
    <%@ page isELIgnored="false"%>  
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    this is springmvc,${user.username }
    
    </body>
    </html>
    复制代码

    hiList.jsp:

    复制代码
    <%@ page isELIgnored="false"%>  
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <c:forEach  var="user" items="${userList}">
    
    ${user.username}----${user.password}<br>
    </c:forEach>
    
    </body>
    </html>
    复制代码

    ======================================================================================

    OK,代码贴完了,项目上右键,debug on server应该就能跑起来了。

    几个链接可以查看效果:druid的监控信息:http://localhost:8080/Test/druid/sql.html

    http://localhost:8080/Test/

    http://localhost:8080/Test/text.do

    http://localhost:8080/Test/indexList.do

    http://localhost:8080/Test/TxTest.do

    现在简单讲讲,配置文件里面有注释就不说了:

    一:在配置文件添加事务的时候遇到tx标签没用,在xsi:schemaLocation这里添加两行

    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd 

    就可以了。

    二:还遇到EL表达式不能用,然后

    web.xml修改:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    jsp增加:
    <%@ page isELIgnored="false"%>

    三:还有c:forEach这种标签不能用

    在JSP上增加

     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    就可以了

    四:spring事务这里

    数据库是mysql ,然后表引擎是InnoDB

    用navicat在design table---option--engine可以看到

    访问http://localhost:8080/Test/TxTest.do之后会出现异常,这个异常是手动抛出的,数据库也没有插入数据。

    然后将表的引擎换成MyISAM,保存

    之后再访问http://localhost:8080/Test/TxTest.do,发现数据库被插入数据了。

    说明:Spring的这个声明事务能使用,MyISAM不支持事务。

    五:Controller里的四个方法

    第一个方法是一般的测试。

    第二个方法是想测试返回json的,主要是@ResponseBody标签。

    第三个方法测试LIST。

    第四个是测试事务的。

  • 相关阅读:
    AFN的使用(待整理)
    [转]文件上传进度显示
    图片上传在线预览
    Mysql中文乱码,修改字符集
    struts2 实现自定义标签
    设置HTML和JSP页面不缓存的方法
    Spring framework3.2整合hibernate4.1报错:No Session found for current thread
    Java用SAX解析XML
    js操作Cookie
    php创建缩略图
  • 原文地址:https://www.cnblogs.com/telwanggs/p/7484872.html
Copyright © 2011-2022 走看看