`
shaohan126448
  • 浏览: 116637 次
  • 来自: 北京
社区版块
存档分类
最新评论

spring+springmvc+ibatis整合注解方式实例

 
阅读更多
1.需求说明

实现用户通过数据库验证登录需求,采用Myeclipse+Tomcat 6.0+Mysql 5.0+JDK 1.6

 

2.数据库表

开发所用Mysql数据库,只建立单张用户表T_USER,表结构如下:

   

字段名称 数据类型 字段描述
ID int 用户编号
USERNAME VARCHAR 用户名
PASSWORD VARCHAR 用户登录密码
sql语句如下:   

 

    CREATE TABLE `t_user` (
    `ID` int(11) NOT NULL auto_increment,
    `USERNAME` varchar(255) default NULL,
    `PASSWORD` varchar(255) default NULL,
    PRIMARY KEY  (`ID`)
    );

 

3.构建源代码目录

 content

    

4.用到的jar包(见附件Archive.rar)

  

5.各项Xml配置文件详解

(1)web.xml文件(Tomcat使用)

服务器根据配置内容初始化spring框架,springmvc框架和log4j日志框架    

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px"><?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.     
  8.   <!-- 应用程序名称 -->  
  9.   <display-name>ISS</display-name>  
  10.     
  11.   <!-- 应用程序描述说明性文字 -->  
  12.   <description>Spring,SpringMvc,Ibatis</description>  
  13.     
  14.   <!-- ServletContext初始化参数 -->  
  15.   <context-param>  
  16.     <param-name>webAppRootKey</param-name>  
  17.     <param-value>spring_springmvc_ibatis.root</param-value>  
  18.   </context-param>  
  19.   <context-param>  
  20.     <param-name>log4jConfigLocation</param-name>  
  21.     <param-value><SPAN>/WEB-INF/classes/log4j.properties</SPAN></param-value>  
  22.   </context-param>  
  23.   <context-param>  
  24.     <param-name>contextConfigLocation</param-name>  
  25.     <param-value><SPAN>/WEB-INF/classes/applicationContext.xml</SPAN></param-value>  
  26.   </context-param>  
  27.       
  28.   <!-- 字符过滤,防止添加到数据库的数据为乱码 -->  
  29.   <filter>  
  30.     <filter-name>characterEncodingFilter</filter-name>  
  31.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  32.     <init-param>  
  33.       <param-name>encoding</param-name>  
  34.       <param-value>UTF-8</param-value>  
  35.     </init-param>  
  36.     <init-param>  
  37.       <param-name>forceEncoding</param-name>  
  38.       <param-value>true</param-value>  
  39.     </init-param>  
  40.   </filter>  
  41.   <filter-mapping>  
  42.     <filter-name>characterEncodingFilter</filter-name>  
  43.     <url-pattern>/*</url-pattern>  
  44.   </filter-mapping>  
  45.     
  46.   <!-- web权限配置 -->  
  47.   <filter>  
  48.     <filter-name>springSecurityFilterChain</filter-name>  
  49.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  50.   </filter>  
  51.   <filter-mapping>  
  52.     <filter-name>springSecurityFilterChain</filter-name>  
  53.     <url-pattern>/*</url-pattern>  
  54.   </filter-mapping>  
  55.     
  56.   <!-- 配置监听器,用于初始化 -->  
  57.   <listener>  
  58.     <listener-class><SPAN>org.springframework.web.util.Log4jConfigListener</SPAN></listener-class>  
  59.   </listener>  
  60.   <listener>  
  61.     <listener-class><SPAN>org.springframework.web.context.ContextLoaderListener</SPAN></listener-class>  
  62.   </listener>  
  63.     
  64.   <!-- Servlet初始化参数,配置springmvc模块 -->  
  65.   <servlet>  
  66.     <servlet-name>springmvc</servlet-name>  
  67.     <servlet-class><SPAN>org.springframework.web.servlet.DispatcherServlet</SPAN></servlet-class>  
  68.     <init-param>  
  69.       <param-name>contextConfigLocation</param-name>  
  70.       <param-value><SPAN>/WEB-INF/classes/springmvc-servlet.xml</SPAN></param-value>  
  71.     </init-param>  
  72.     <load-on-startup>2</load-on-startup>  
  73.   </servlet>  
  74.   <servlet-mapping>  
  75.     <servlet-name>springmvc</servlet-name>  
  76.     <url-pattern>/</url-pattern>  
  77.   </servlet-mapping>  
  78.     
  79.   <!-- 配置session存在时间 -->  
  80.   <session-config>  
  81.     <session-timeout>60</session-timeout>  
  82.   </session-config>  
  83.     
  84.   <!-- 默认起始页面 -->  
  85.   <welcome-file-list>  
  86.     <welcome-file>index.jsp</welcome-file>  
  87.   </welcome-file-list>  
  88.     
  89.   <!-- 异常跳转页面 -->  
  90.   <error-page>  
  91.     <exception-type>java.lang.Exception</exception-type>  
  92.     <location>/WEB-INF/jsp/exception.jsp</location>  
  93.   </error-page>  
  94. </web-app>  
  95. </SPAN></STRONG>  
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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">
  
  <!-- 应用程序名称 -->
  <display-name>ISS</display-name>
  
  <!-- 应用程序描述说明性文字 -->
  <description>Spring,SpringMvc,Ibatis</description>
  
  <!-- ServletContext初始化参数 -->
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>spring_springmvc_ibatis.root</param-value>
  </context-param>
  <context-param>
	<param-name>log4jConfigLocation</param-name>
	<param-value>/WEB-INF/classes/log4j.properties</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
  </context-param>
	
  <!-- 字符过滤,防止添加到数据库的数据为乱码 -->
  <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>
  
  <!-- web权限配置 -->
  <filter>
	<filter-name>springSecurityFilterChain</filter-name>
	<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 配置监听器,用于初始化 -->
  <listener>
	<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- Servlet初始化参数,配置springmvc模块 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/classes/springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 配置session存在时间 -->
  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>
  
  <!-- 默认起始页面 -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 异常跳转页面 -->
  <error-page>
	<exception-type>java.lang.Exception</exception-type>
	<location>/WEB-INF/jsp/exception.jsp</location>
  </error-page>
</web-app>

 

(2)springmvc-servlet.xml(Springmvc框架配置文件)

该文件是springmvc框架配置文件,也是它的核心文件

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px"><?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:mvc="http://www.springframework.org/schema/mvc"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans   
  8.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.         http://www.springframework.org/schema/mvc  
  10.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  11.         http://www.springframework.org/schema/context   
  12.         http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  13.     
  14.   <!-- 自动扫描,完成bean创建和依赖注入 -->  
  15.   <context:component-scan base-package="com.archie"/>  
  16.     
  17.   <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  
  18.   <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>  
  19.     
  20.   <!-- 视图解析器 -->  
  21.   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  22.     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>  
  23.     <property name="prefix" value="/WEB-INF/views/"/>  
  24.     <property name="suffix" value=".jsp"/>  
  25.   </bean>  
  26.     
  27.   <!-- 异常解析器 -->  
  28.   <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  29.     <property name="exceptionMappings">  
  30.       <props>  
  31.         <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">common/fileerror</prop>  
  32.       </props>  
  33.     </property>  
  34.   </bean>  
  35. </beans></SPAN></STRONG>  
<?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-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
  <!-- 自动扫描,完成bean创建和依赖注入 -->
  <context:component-scan base-package="com.archie"/>
  
  <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
  <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
  
  <!-- 视图解析器 -->
  <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>
  
  <!-- 异常解析器 -->
  <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
      <props>
        <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">common/fileerror</prop>
      </props>
    </property>
  </bean>
</beans>

(3)applicationContext.xml(Spring框架配置文件)

 

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px"><?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:mvc="http://www.springframework.org/schema/mvc"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"   
  7.     xmlns:tx="http://www.springframework.org/schema/tx"  
  8.     xsi:schemaLocation="  
  9.         http://www.springframework.org/schema/beans   
  10.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  11.         http://www.springframework.org/schema/mvc   
  12.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  13.         http://www.springframework.org/schema/context   
  14.         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  15.         http://www.springframework.org/schema/tx  
  16.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  17.       http://www.springframework.org/schema/aop  
  18.       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"  default-autowire="byName">  
  19.   
  20.   <!-- 自动扫描 -->  
  21.   <context:component-scan base-package="com.archie"/>  
  22.     
  23.   <!-- 启动spring注解,当自动扫描启动后,该配置可以去掉   
  24.   <context:annotation-config /> -->  
  25.       
  26.   <!-- 启动spring注解,等同于 context:annotation-config  
  27.   <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>  
  28.   <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>  
  29.   <bean class="org.springframework.beans.factory.annotation.PersistenceAnnotationBeanPostProcessor"/>  
  30.   <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> -->   
  31.     
  32.   <!-- 配置数据源属性文件 -->  
  33.   <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  34.     <property name="locations">      
  35.       <list>       
  36.         <value>jdbc.properties</value>      
  37.       </list>     
  38.     </property>    
  39.   </bean>  
  40.     
  41.   <!-- 配置数据源 -->  
  42.   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">    
  43.     <property name="driverClassName" value="${driver}"/>    
  44.     <property name="url" value="${url}"/>    
  45.     <property name="username" value="${username}"/>    
  46.     <property name="password" value="${password}"/>  
  47.   </bean>  
  48.     
  49.   <!-- 配置SqlMapClient对象 -->  
  50.   <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">    
  51.     <property name="configLocation" value="sqlMapConfig.xml"/>  
  52.     <property name="dataSource" ref="dataSource"/>    
  53.   </bean>  
  54.     
  55.   <!--根据sqlMapClien创建一个SqlMapClient模版类-->  
  56.   <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">  
  57.     <property name="sqlMapClient" ref="sqlMapClient"/>  
  58.   </bean>  
  59.     
  60.   <!-- 配置事务管理器 -->  
  61.   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    
  62.     <property name="dataSource" ref="dataSource"/>    
  63.   </bean>  
  64.     
  65.   <!-- 启动spring事务注解,事务注解尽在此 -->  
  66.   <tx:annotation-driven transaction-manager="transactionManager"/>  
  67.     
  68.   <!-- 配置事务特性   
  69.   <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  70.     <tx:attributes>  
  71.         <tx:method name="select*" read-only="true" propagation="REQUIRED"/>  
  72.         <tx:method name="find*" read-only="true" propagation="REQUIRED"/>  
  73.         <tx:method name="save*" propagation="REQUIRED" isolation="REPEATABLE_READ"/>  
  74.         <tx:method name="update*" propagation="REQUIRED" isolation="REPEATABLE_READ"/>  
  75.         <tx:method name="add*" propagation="REQUIRED" isolation="REPEATABLE_READ"/>  
  76.         <tx:method name="delete*" propagation="REQUIRED" isolation="REPEATABLE_READ"/>  
  77.         <tx:method name="*" read-only="true"/>  
  78.     </tx:attributes>  
  79.   </tx:advice> -->  
  80.     
  81.   <!-- 配置事务代理拦截器     
  82.   <bean id="baseTransactionProxy" abstract="true"   
  83.     class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">  
  84.     <property name="transactionManager">  
  85.       <ref bean="transactionManager"/>  
  86.     </property>  
  87.     <property name="transactionAttributes">  
  88.       <props>  
  89.         <prop key="insert*">PROPAGATION_REQUIRED</prop>  
  90.         <prop key="update*">PROPAGATION_REQUIRED</prop>  
  91.         <prop key="delete*">PROPAGATION_REQUIRED</prop>  
  92.         <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>      
  93.       </props>     
  94.     </property>  
  95.   </bean> -->  
  96.     
  97.   <!-- 配置哪些类的方法需要进行事务管理   
  98.   <aop:config>  
  99.     <aop:pointcut id="baseServiceMethods" expression="execution(* com.archie.service.*.*(..))"/>  
  100.       <aop:advisor advice-ref="txAdvice" pointcut-ref="baseServiceMethods"/>  
  101.     </aop:config>  
  102.   <aop:aspectj-autoproxy /> -->  
  103.     
  104.   <!-- 配置Dao实例   
  105.   <bean id="userDao" class="com.archie.dao.UserDao">  
  106.     <property name="sqlMapClient" ref="sqlMapClient"/>     
  107.   </bean> -->  
  108.     
  109.   <!-- 配置Service实例   
  110.   <bean id="userService" class="com.archie.service.UserService">  
  111.     <property name="userDao" ref="userDao"/>  
  112.   </bean> -->  
  113.     
  114.   <!-- 添加了事务的管理类    
  115.   <bean id="userManager" parent="baseTransactionProxy">     
  116.     <property name="target">      
  117.       <bean class="com.archie.service.UserService"/>  
  118.     </property>    
  119.   </bean> -->   
  120.     
  121. </beans></SPAN></STRONG>  
<?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-3.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"  default-autowire="byName">

  <!-- 自动扫描 -->
  <context:component-scan base-package="com.archie"/>
  
  <!-- 启动spring注解,当自动扫描启动后,该配置可以去掉 
  <context:annotation-config /> -->
    
  <!-- 启动spring注解,等同于 context:annotation-config
  <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
  <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
  <bean class="org.springframework.beans.factory.annotation.PersistenceAnnotationBeanPostProcessor"/>
  <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> --> 
  
  <!-- 配置数据源属性文件 -->
  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">    
      <list>     
	    <value>jdbc.properties</value>    
	  </list>   
	</property>  
  </bean>
  
  <!-- 配置数据源 -->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
    <property name="driverClassName" value="${driver}"/>  
    <property name="url" value="${url}"/>  
    <property name="username" value="${username}"/>  
    <property name="password" value="${password}"/>
  </bean>
  
  <!-- 配置SqlMapClient对象 -->
  <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">  
    <property name="configLocation" value="sqlMapConfig.xml"/>
    <property name="dataSource" ref="dataSource"/>  
  </bean>
  
  <!--根据sqlMapClien创建一个SqlMapClient模版类-->
  <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
    <property name="sqlMapClient" ref="sqlMapClient"/>
  </bean>
  
  <!-- 配置事务管理器 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
    <property name="dataSource" ref="dataSource"/>  
  </bean>
  
  <!-- 启动spring事务注解,事务注解尽在此 -->
  <tx:annotation-driven transaction-manager="transactionManager"/>
  
  <!-- 配置事务特性 
  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="select*" read-only="true" propagation="REQUIRED"/>
        <tx:method name="find*" read-only="true" propagation="REQUIRED"/>
        <tx:method name="save*" propagation="REQUIRED" isolation="REPEATABLE_READ"/>
        <tx:method name="update*" propagation="REQUIRED" isolation="REPEATABLE_READ"/>
        <tx:method name="add*" propagation="REQUIRED" isolation="REPEATABLE_READ"/>
        <tx:method name="delete*" propagation="REQUIRED" isolation="REPEATABLE_READ"/>
        <tx:method name="*" read-only="true"/>
    </tx:attributes>
  </tx:advice> -->
  
  <!-- 配置事务代理拦截器   
  <bean id="baseTransactionProxy" abstract="true" 
	class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
	<property name="transactionManager">
	  <ref bean="transactionManager"/>
	</property>
	<property name="transactionAttributes">
	  <props>
		<prop key="insert*">PROPAGATION_REQUIRED</prop>
		<prop key="update*">PROPAGATION_REQUIRED</prop>
		<prop key="delete*">PROPAGATION_REQUIRED</prop>
		<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>    
	  </props>   
 	</property>
  </bean> -->
  
  <!-- 配置哪些类的方法需要进行事务管理 
  <aop:config>
    <aop:pointcut id="baseServiceMethods" expression="execution(* com.archie.service.*.*(..))"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="baseServiceMethods"/>
    </aop:config>
  <aop:aspectj-autoproxy /> -->
  
  <!-- 配置Dao实例 
  <bean id="userDao" class="com.archie.dao.UserDao">
    <property name="sqlMapClient" ref="sqlMapClient"/>   
  </bean> -->
  
  <!-- 配置Service实例 
  <bean id="userService" class="com.archie.service.UserService">
    <property name="userDao" ref="userDao"/>
  </bean> -->
  
  <!-- 添加了事务的管理类  
  <bean id="userManager" parent="baseTransactionProxy">   
	<property name="target">    
	  <bean class="com.archie.service.UserService"/>
	</property>  
  </bean> --> 
  
</beans>

 

 

(4)jdbc.properties(数据源属性文件)

数据源连接信息的源出处,目前配置了三种数据库Oracle,DB2和Mysql

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px"># Database Connectivity  
  2. # Oracle  
  3. #driver = oracle.jdbc.driver.OracleDriver  
  4. #url = jdbc:oracle:thin:@localhost:1521:oracl  
  5. #username = scott  
  6. #password = tiger  
  7.   
  8. # DB2  
  9. #driver = com.ibm.db2.jcc.DB2Driver  
  10. #url = jdbc:db2://10.1.10.162:50000/mydb  
  11. #username = root  
  12. #password = root  
  13.   
  14. # Mysql  
  15. driver = com.mysql.jdbc.Driver  
  16. url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8  
  17. username = root  
  18. password = 1234  
  19. initialPoolSize = 1  
  20. minPoolSize = 1  
  21. maxPoolSize =10  
  22. </SPAN></STRONG>  
# Database Connectivity
# Oracle
#driver = oracle.jdbc.driver.OracleDriver
#url = jdbc:oracle:thin:@localhost:1521:oracl
#username = scott
#password = tiger

# DB2
#driver = com.ibm.db2.jcc.DB2Driver
#url = jdbc:db2://10.1.10.162:50000/mydb
#username = root
#password = root

# Mysql
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8
username = root
password = 1234
initialPoolSize = 1
minPoolSize = 1
maxPoolSize =10

(5)log4j.properties(log4j框架属性文件)

 

log4j日志属性配置文件

  1. <STRONG><SPAN style="FONT-SIZE: 18px"># log4j.properties  
  2. log4j.rootLogger=warn,console  
  3.   
  4. log4j.appender.console=org.apache.log4j.ConsoleAppender  
  5. log4j.appender.console.layout=org.apache.log4j.PatternLayout  
  6. log4j.appender.console.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n  
  7. log4j.appender.console.Encoding=GB18030  
  8.   
  9. log4j.appender.file=org.apache.log4j.RollingFileAppender  
  10. log4j.appender.file.MaxFileSize=10240KB  
  11. log4j.appender.file.MaxBackupIndex=100  
  12. log4j.appender.file.Encoding=GB18030  
  13. log4j.appender.file.layout=org.apache.log4j.PatternLayout  
  14. log4j.appender.file.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n  
  15.   
  16. log4j.appender.ROLLING_FILE_CUSTOMER=org.apache.log4j.RollingFileAppender  
  17. log4j.appender.ROLLING_FILE_CUSTOMER.Threshold=debug  
  18. log4j.appender.ROLLING_FILE_CUSTOMER.Append=true  
  19. log4j.appender.ROLLING_FILE_CUSTOMER.MaxFileSize=1024KB  
  20. log4j.appender.ROLLING_FILE_CUSTOMER.MaxBackupIndex=30  
  21. log4j.appender.ROLLING_FILE_CUSTOMER.layout=org.apache.log4j.PatternLayout  
  22. log4j.appender.ROLLING_FILE_CUSTOMER.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n  
  23.   
  24. log4j.appender.ROLLING_FILE_WORKMANAGER=org.apache.log4j.RollingFileAppender  
  25. log4j.appender.ROLLING_FILE_WORKMANAGER.Threshold=debug  
  26. log4j.appender.ROLLING_FILE_WORKMANAGER.Append=true  
  27. log4j.appender.ROLLING_FILE_WORKMANAGER.MaxFileSize=1024KB  
  28. log4j.appender.ROLLING_FILE_WORKMANAGER.MaxBackupIndex=30  
  29. log4j.appender.ROLLING_FILE_WORKMANAGER.layout=org.apache.log4j.PatternLayout  
  30. log4j.appender.ROLLING_FILE_WORKMANAGER.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n  
  31.   
  32. log4j.appender.ROLLING_FILE_RSS=org.apache.log4j.RollingFileAppender  
  33. log4j.appender.ROLLING_FILE_RSS.Threshold=debug  
  34. log4j.appender.ROLLING_FILE_RSS.Append=true  
  35. log4j.appender.ROLLING_FILE_RSS.MaxFileSize=1024KB  
  36. log4j.appender.ROLLING_FILE_RSS.MaxBackupIndex=30  
  37. log4j.appender.ROLLING_FILE_RSS.layout=org.apache.log4j.PatternLayout  
  38. log4j.appender.ROLLING_FILE_RSS.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n  
  39. </SPAN></STRONG>  
# log4j.properties
log4j.rootLogger=warn,console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n
log4j.appender.console.Encoding=GB18030

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=10240KB
log4j.appender.file.MaxBackupIndex=100
log4j.appender.file.Encoding=GB18030
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n

log4j.appender.ROLLING_FILE_CUSTOMER=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_CUSTOMER.Threshold=debug
log4j.appender.ROLLING_FILE_CUSTOMER.Append=true
log4j.appender.ROLLING_FILE_CUSTOMER.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_CUSTOMER.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_CUSTOMER.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_CUSTOMER.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n

log4j.appender.ROLLING_FILE_WORKMANAGER=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_WORKMANAGER.Threshold=debug
log4j.appender.ROLLING_FILE_WORKMANAGER.Append=true
log4j.appender.ROLLING_FILE_WORKMANAGER.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_WORKMANAGER.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_WORKMANAGER.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_WORKMANAGER.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n

log4j.appender.ROLLING_FILE_RSS=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE_RSS.Threshold=debug
log4j.appender.ROLLING_FILE_RSS.Append=true
log4j.appender.ROLLING_FILE_RSS.MaxFileSize=1024KB
log4j.appender.ROLLING_FILE_RSS.MaxBackupIndex=30
log4j.appender.ROLLING_FILE_RSS.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE_RSS.layout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n

(6)sqlMapConfig.xml(Ibatis框架配置文件)

 

该文件主要负责指定sql映射文件,即与model层对象对应的映射文件

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px"><?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"   
  3. "http://www.ibatis.com/dtd/sql-map-config-2.dtd">  
  4. <sqlMapConfig>  
  5.   <!-- 配置settings -->  
  6.   <settings lazyLoadingEnabled="true" useStatementNamespaces="false"/>  
  7.       
  8.   <!-- 配置sql映射文件 -->  
  9.   <sqlMap resource="com/archie/model/User.xml"/>  
  10. </sqlMapConfig></SPAN></STRONG>  
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" 
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
  <!-- 配置settings -->
  <settings lazyLoadingEnabled="true" useStatementNamespaces="false"/>
	
  <!-- 配置sql映射文件 -->
  <sqlMap resource="com/archie/model/User.xml"/>
</sqlMapConfig>

6.Java代码编写

 

根据包目录,可以看出分成model层,dao层,service层和web层,另外附加test层,用于java环境测试

(1)model层(User.java+User.xml)

   User.java代码

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.model;  
  2.   
  3. public class User {  
  4.   
  5.     private int id;    
  6.     private String username;    
  7.     private String password;   
  8.       
  9.     public User(){  
  10.           
  11.     }  
  12.       
  13.     public User(int id){  
  14.         this.id = id;  
  15.     }  
  16.       
  17.     public User(int id, String username){  
  18.         this.id = id;  
  19.         this.username = username;  
  20.     }  
  21.       
  22.     public User(String username, String password) {  
  23.         this.username = username;  
  24.         this.password = password;  
  25.     }  
  26.       
  27.     public User(int id, String username, String password){  
  28.         this.id = id;  
  29.         this.username = username;  
  30.         this.password = password;  
  31.     }  
  32.         
  33.     public int getId() {    
  34.         return id;    
  35.     }    
  36.     public void setId(int id) {    
  37.         this.id = id;    
  38.     }    
  39.     public String getUsername() {    
  40.         return username;    
  41.     }    
  42.     public void setUsername(String username) {    
  43.         this.username = username;    
  44.     }    
  45.     public String getPassword() {    
  46.         return password;    
  47.     }    
  48.     public void setPassword(String password) {    
  49.         this.password = password;    
  50.     }  
  51. }  
  52. </SPAN></STRONG>  
package com.archie.model;

public class User {

    private int id;  
    private String username;  
    private String password; 
    
    public User(){
    	
    }
    
    public User(int id){
    	this.id = id;
    }
    
    public User(int id, String username){
    	this.id = id;
    	this.username = username;
    }
    
    public User(String username, String password) {
		this.username = username;
		this.password = password;
	}
    
    public User(int id, String username, String password){
    	this.id = id;
    	this.username = username;
    	this.password = password;
    }
      
    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;  
    }
}
   User.xml代码(model层对象的sql映射文件,被dao层调用,本质是sql语句集合,所有相关的sql均于此)

 

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px"><?xml version="1.0" encoding="UTF-8" ?>   
  2. <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"    
  3. "http://ibatis.apache.org/dtd/sql-map-2.dtd">  
  4. <sqlMap namespace="User">  
  5.   
  6.     <typeAlias alias="User" type="com.archie.model.User"/>  
  7.       
  8.     <select id="findAllUser" resultClass="User" >    
  9.         select * from t_user  
  10.     </select>  
  11.     <select id="findUserByID" resultClass="User" parameterClass="int">    
  12.         select * from t_user where id=#id#  
  13.     </select>  
  14.       
  15.     <select id="getTotalCount" resultClass="int">  
  16.         select count(*) from t_user  
  17.     </select>  
  18.       
  19.     <select id="searchUsers" resultClass="User" parameterClass="User">    
  20.         select * from t_user    
  21.         <dynamic prepend="where">    
  22.             <!-- 模糊查询,用$表示文本替换,而用#表示替换PrepareStatement中的?号 -->    
  23.             <isNotEmpty prepend="and" property="username">    
  24.                 (username like '%$username$%')    
  25.             </isNotEmpty>    
  26.             <isNotEmpty prepend="and" property="password">    
  27.                 (password like '%$password$%')    
  28.             </isNotEmpty>    
  29.         </dynamic>    
  30.     </select>  
  31.       
  32.     <select id="findUserByNameAndPassword" resultClass="User" parameterClass="User">    
  33.         select * from t_user where username=#username# and password=#password#  
  34.     </select>  
  35.       
  36.     <insert id="insertUser" parameterClass="User">    
  37.         insert into t_user(id,username,password) values(null,#username#,#password#)  
  38.     </insert>  
  39.       
  40.     <update id="updateUser" parameterClass="User">    
  41.         update t_user   
  42.         set username = #username#,  
  43.             password=#password#   
  44.         where id=#id#  
  45.     </update>  
  46.   
  47.     <delete id="deleteUser" parameterClass="int">    
  48.         delete from t_user where id=#id#  
  49.     </delete>  
  50.       
  51.     <delete id="deleteUserByLike" parameterClass="User">  
  52.         delete from t_user  
  53.         <dynamic prepend="where">    
  54.             <!-- 模糊查询,用$表示文本替换,而用#表示替换PrepareStatement中的?号 -->  
  55.             <isNotEmpty prepend="and" property="username">    
  56.                 (username like '%$username$%')    
  57.             </isNotEmpty>    
  58.             <isNotEmpty prepend="and" property="password">    
  59.                 (password like '%$password$%')    
  60.             </isNotEmpty>    
  61.         </dynamic>  
  62.     </delete>  
  63.       
  64. </sqlMap></SPAN></STRONG>  
<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"  
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="User">

	<typeAlias alias="User" type="com.archie.model.User"/>
	
	<select id="findAllUser" resultClass="User" >  
    	select * from t_user
  	</select>
  	<select id="findUserByID" resultClass="User" parameterClass="int">  
    	select * from t_user where id=#id#
    </select>
    
    <select id="getTotalCount" resultClass="int">
        select count(*) from t_user
    </select>
    
    <select id="searchUsers" resultClass="User" parameterClass="User">  
    	select * from t_user  
    	<dynamic prepend="where">  
        	<!-- 模糊查询,用$表示文本替换,而用#表示替换PrepareStatement中的?号 -->  
        	<isNotEmpty prepend="and" property="username">  
        		(username like '%$username$%')  
        	</isNotEmpty>  
        	<isNotEmpty prepend="and" property="password">  
        		(password like '%$password$%')  
        	</isNotEmpty>  
    	</dynamic>  
  	</select>
  	
  	<select id="findUserByNameAndPassword" resultClass="User" parameterClass="User">  
    	select * from t_user where username=#username# and password=#password#
    </select>
  	
  	<insert id="insertUser" parameterClass="User">  
    	insert into t_user(id,username,password) values(null,#username#,#password#)
  	</insert>
  	
  	<update id="updateUser" parameterClass="User">  
    	update t_user 
    	set username = #username#,
    		password=#password#	
    	where id=#id#
  	</update>

	<delete id="deleteUser" parameterClass="int">  
    	delete from t_user where id=#id#
  	</delete>
  	
  	<delete id="deleteUserByLike" parameterClass="User">
  		delete from t_user
  		<dynamic prepend="where">  
        	<!-- 模糊查询,用$表示文本替换,而用#表示替换PrepareStatement中的?号 -->
        	<isNotEmpty prepend="and" property="username">  
        		(username like '%$username$%')  
        	</isNotEmpty>  
        	<isNotEmpty prepend="and" property="password">  
        		(password like '%$password$%')  
        	</isNotEmpty>  
    	</dynamic>
  	</delete>
  	
</sqlMap>

(2)dao层(数据服务层,BaseDao.java+UserDao.java)

 

   BaseDao.java(公共Dao,其他Dao均继承它)

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.dao;  
  2.   
  3. import javax.annotation.PostConstruct;  
  4. import javax.annotation.Resource;  
  5.   
  6. import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;  
  7.   
  8. import com.ibatis.sqlmap.client.SqlMapClient;  
  9.   
  10. public class BaseDao extends SqlMapClientDaoSupport {  
  11.       
  12.     @Resource(name="sqlMapClient")  //通过bean名称注入   
  13.     private SqlMapClient sqlMapClient;  
  14.       
  15.     @PostConstruct  //完成sqlMapClient初始化工作   
  16.     public void initSqlMapClient(){  
  17.         super.setSqlMapClient(sqlMapClient);  
  18.     }  
  19. }  
  20. </SPAN></STRONG>  
package com.archie.dao;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapClient;

public class BaseDao extends SqlMapClientDaoSupport {
	
	@Resource(name="sqlMapClient")  //通过bean名称注入
	private SqlMapClient sqlMapClient;
	
	@PostConstruct  //完成sqlMapClient初始化工作
	public void initSqlMapClient(){
		super.setSqlMapClient(sqlMapClient);
	}
}

   UserDao.java(user数据服务层)

 

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.stereotype.Component;  
  6. import com.archie.model.User;  
  7.   
  8. @Component  //将UserDao类注入到bean里面   
  9. public class UserDao extends BaseDao {  
  10.   
  11.     public boolean addUser(User user) throws Exception{  
  12.         User bean = (User)getSqlMapClientTemplate().insert("insertUser", user);  
  13.         return bean != null ? true : false;  
  14.     }  
  15.       
  16.     public boolean deleteUser(int id) throws Exception{  
  17.         int result = getSqlMapClientTemplate().delete("deleteUser", id);  
  18.         return result > 0 ? true : false;  
  19.     }  
  20.       
  21.     public User getUserById(int id) throws Exception{  
  22.         return (User)getSqlMapClientTemplate().queryForObject("findUserByID", id);  
  23.     }  
  24.       
  25.     @SuppressWarnings("unchecked")  
  26.     public List getAllUsers() throws Exception{  
  27.         return getSqlMapClientTemplate().queryForList("findAllUser");  
  28.     }  
  29.       
  30.     public boolean updateUser(User user) throws Exception{  
  31.         int result = getSqlMapClientTemplate().update("updateUser", user);  
  32.         return result > 0 ? true : false;  
  33.     }  
  34.       
  35.     public User getUserByNameAndPassword(User user) throws Exception{  
  36.         return (User)getSqlMapClientTemplate().queryForObject("findUserByNameAndPassword", user);  
  37.     }  
  38.       
  39.     public int getTotalCount() throws Exception{  
  40.         return (Integer)getSqlMapClientTemplate().queryForObject("getTotalCount");  
  41.     }  
  42.       
  43.     @SuppressWarnings("unchecked")  
  44.     public List getUsersByLike(User user) throws Exception{  
  45.         return getSqlMapClientTemplate().queryForList("searchUsers", user);  
  46.     }  
  47.       
  48.     public int deleteUserByLike(User user) throws Exception{  
  49.         int result = getSqlMapClientTemplate().delete("deleteUserByLike", user);  
  50.         if (result > 0) {  
  51.             System.out.println("模糊删除成功!");  
  52.         }else {  
  53.             System.out.println("没有匹配的记录1");  
  54.         }  
  55.         return result;  
  56.     }  
  57. }  
  58. </SPAN></STRONG>  
package com.archie.dao;

import java.util.List;

import org.springframework.stereotype.Component;
import com.archie.model.User;

@Component  //将UserDao类注入到bean里面
public class UserDao extends BaseDao {

	public boolean addUser(User user) throws Exception{
		User bean = (User)getSqlMapClientTemplate().insert("insertUser", user);
		return bean != null ? true : false;
	}
	
	public boolean deleteUser(int id) throws Exception{
		int result = getSqlMapClientTemplate().delete("deleteUser", id);
		return result > 0 ? true : false;
	}
	
	public User getUserById(int id) throws Exception{
		return (User)getSqlMapClientTemplate().queryForObject("findUserByID", id);
	}
	
	@SuppressWarnings("unchecked")
	public List getAllUsers() throws Exception{
		return getSqlMapClientTemplate().queryForList("findAllUser");
	}
	
	public boolean updateUser(User user) throws Exception{
		int result = getSqlMapClientTemplate().update("updateUser", user);
		return result > 0 ? true : false;
	}
	
	public User getUserByNameAndPassword(User user) throws Exception{
		return (User)getSqlMapClientTemplate().queryForObject("findUserByNameAndPassword", user);
	}
	
	public int getTotalCount() throws Exception{
		return (Integer)getSqlMapClientTemplate().queryForObject("getTotalCount");
	}
	
	@SuppressWarnings("unchecked")
	public List getUsersByLike(User user) throws Exception{
		return getSqlMapClientTemplate().queryForList("searchUsers", user);
	}
	
	public int deleteUserByLike(User user) throws Exception{
		int result = getSqlMapClientTemplate().delete("deleteUserByLike", user);
		if (result > 0) {
			System.out.println("模糊删除成功!");
		}else {
			System.out.println("没有匹配的记录1");
		}
		return result;
	}
}

(3)service层(业务服务层,UserService.java)

 

   UserService.java代码如下

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.springframework.stereotype.Component;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import com.archie.dao.UserDao;  
  11. import com.archie.model.User;  
  12.   
  13. @Component  //将UserService类注入到bean里面   
  14. @Transactional  //注入事务管理   
  15. public class UserService {  
  16.       
  17.     @Resource(name="userDao")  // 通过名称注入到bean里面   
  18.     private UserDao userDao;  
  19.   
  20.     public User login(User user) throws Exception{  
  21.         return userDao.getUserByNameAndPassword(user);  
  22.     }  
  23.       
  24.     public void addUser(User user) throws Exception{  
  25.         userDao.addUser(user);  
  26.     }  
  27.       
  28.     public void deleteUser(int id) throws Exception{  
  29.         boolean bool = userDao.deleteUser(id);  
  30.         if (!bool) {  
  31.             System.out.println("删除的记录不存在!");  
  32.             throw new RuntimeException();  
  33.         }  
  34.     }  
  35.       
  36.     public User getUserById(int id) throws Exception{  
  37.         User user = userDao.getUserById(id);  
  38.         if (user == null) {  
  39.             return null;  
  40.         }  
  41.         return userDao.getUserById(id);  
  42.     }  
  43.       
  44.     public void updateUser(User user) throws Exception{  
  45.         userDao.updateUser(user);  
  46.     }  
  47.       
  48.     public int getTotalCount() throws Exception{  
  49.         return userDao.getTotalCount();  
  50.     }  
  51.       
  52.     @SuppressWarnings("unchecked")  
  53.     public List getUsersByLike(User user) throws Exception{  
  54.         return userDao.getUsersByLike(user);  
  55.     }  
  56.       
  57.     public int deleteUserByLike(User user) throws Exception{  
  58.         return userDao.deleteUserByLike(user);  
  59.     }  
  60.       
  61.     public void insertUsers(List<User> list) throws Exception{  
  62.         for (int i = 0; i < list.size(); i++) {  
  63.             if (i > 3) {  
  64.                 System.out.println("列表太长,中断事务");  
  65.                 throw new RuntimeException("中断事务异常,当列表长度大于3的时候故意抛出,看看事务是否回滚");  
  66.             }  
  67.             User user = list.get(i);  
  68.             userDao.addUser(user);  
  69.         }  
  70.     }  
  71. }  
  72. </SPAN></STRONG>  
package com.archie.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.archie.dao.UserDao;
import com.archie.model.User;

@Component  //将UserService类注入到bean里面
@Transactional  //注入事务管理
public class UserService {
	
	@Resource(name="userDao")  // 通过名称注入到bean里面
	private UserDao userDao;

	public User login(User user) throws Exception{
		return userDao.getUserByNameAndPassword(user);
	}
	
	public void addUser(User user) throws Exception{
		userDao.addUser(user);
	}
	
	public void deleteUser(int id) throws Exception{
		boolean bool = userDao.deleteUser(id);
		if (!bool) {
			System.out.println("删除的记录不存在!");
			throw new RuntimeException();
		}
	}
	
	public User getUserById(int id) throws Exception{
		User user = userDao.getUserById(id);
		if (user == null) {
			return null;
		}
		return userDao.getUserById(id);
	}
	
	public void updateUser(User user) throws Exception{
		userDao.updateUser(user);
	}
	
	public int getTotalCount() throws Exception{
		return userDao.getTotalCount();
	}
	
	@SuppressWarnings("unchecked")
	public List getUsersByLike(User user) throws Exception{
		return userDao.getUsersByLike(user);
	}
	
	public int deleteUserByLike(User user) throws Exception{
		return userDao.deleteUserByLike(user);
	}
	
	public void insertUsers(List<User> list) throws Exception{
		for (int i = 0; i < list.size(); i++) {
			if (i > 3) {
				System.out.println("列表太长,中断事务");
				throw new RuntimeException("中断事务异常,当列表长度大于3的时候故意抛出,看看事务是否回滚");
			}
			User user = list.get(i);
			userDao.addUser(user);
		}
	}
}

(4)web层(界面控制层,UserController.java)

 

   UserController.java

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px"></SPAN></STRONG><P>package com.archie.web;</P><P>import javax.annotation.Resource;  
  2. import javax.servlet.http.HttpSession;  
  3. import javax.validation.Valid;</P><P>import org.springframework.stereotype.Controller;  
  4. import org.springframework.validation.BindingResult;  
  5. import org.springframework.web.bind.annotation.PathVariable;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8. import org.springframework.web.servlet.ModelAndView;</P><P>import com.archie.model.User;  
  9. import com.archie.service.UserService;</P><P>@Controller  
  10. @RequestMapping("/user/*")  
  11. public class UserController {  
  12.    
  13.  @Resource(name="userService")  
  14.  private UserService userService;  
  15.  private final String LIST="redirect:/detail";  
  16.    
  17.   /**  
  18.      * 登录  
  19.      * @param user  
  20.      * @param session  
  21.      * @return  
  22.      */  
  23.     @RequestMapping("/login")  
  24.     public ModelAndView login(@Valid User user,BindingResult result,HttpSession session) throws Exception{  
  25.       if(!result.hasErrors()){  
  26.         User loginUser=userService.login(user);  
  27.         if(loginUser!=null){  
  28.             session.setAttribute("USER", loginUser);  
  29.             return new ModelAndView(LIST);  
  30.         }else{  
  31.             return new ModelAndView("redirect:/");  
  32.         }  
  33.       }else{  
  34.           ModelAndView view=new ModelAndView();  
  35.           view.setViewName("redirect:/");  
  36.           view.addObject("error", result.getAllErrors());  
  37.           return view;  
  38.       }  
  39.     }  
  40.       
  41.     /** 
  42.      * 跳转至添加页 
  43.      * @return 
  44.      */  
  45.     @RequestMapping(value="/toAdd",method=RequestMethod.GET)  
  46.     public ModelAndView toAdd(){  
  47.         return new ModelAndView("user/add");  
  48.     }  
  49.     /** 
  50.      * 保存 
  51.      * @param user 
  52.      * @return 
  53.      */  
  54.     @RequestMapping(value="/add",method=RequestMethod.POST)  
  55.     public ModelAndView add(@Valid User user,BindingResult result) throws Exception{  
  56.         if(result.hasErrors()){  
  57.             return new ModelAndView("user/add","error", result.getAllErrors());  
  58.         }else{  
  59.             userService.addUser(user);  
  60.             return new ModelAndView(LIST);      
  61.         }  
  62.     }  
  63.     /** 
  64.      * 根据ID删除 
  65.      * @param id 
  66.      * @return 
  67.      */  
  68.     @RequestMapping(value="/delete/{id}")  
  69.     public ModelAndView delete(@PathVariable int id) throws Exception{  
  70.         userService.deleteUser(id);  
  71.         return new ModelAndView(LIST);  
  72.     }  
  73.     /** 
  74.      * 跳转至编辑页面 
  75.      * @param id 
  76.      * @return 
  77.      */  
  78.     @RequestMapping(value="/edit/{id}")  
  79.     public ModelAndView edit(@PathVariable int id) throws Exception{  
  80.         User user=userService.getUserById(id);  
  81.         return new ModelAndView("user/edit","user",user);  
  82.     }  
  83.     /** 
  84.      * 编辑 
  85.      * @param user 
  86.      * @return 
  87.      */  
  88.     @RequestMapping(value="/edit")  
  89.     public ModelAndView update(@Valid User user,BindingResult result)throws Exception{  
  90.         ModelAndView view=new ModelAndView();  
  91.         if(result.hasErrors()){  
  92.             view.addObject("error", result.getAllErrors());  
  93.             view.setViewName("user/edit");  
  94.             return view;  
  95.         }else{  
  96.          userService.updateUser(user);  
  97.          return new ModelAndView(LIST);  
  98.         }  
  99.     }</P><P>}  
  100. </P><PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px"></PRE><PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px" class=java name="code"><PRE style="LINE-HEIGHT: normal; WIDOWS: 2; TEXT-TRANSFORM: none; BACKGROUND-COLOR: rgb(240,240,240); FONT-VARIANT: normal; FONT-STYLE: normal; TEXT-INDENT: 0px; MARGIN: 4px 0px; ORPHANS: 2; LETTER-SPACING: normal; COLOR: rgb(0,0,0); FONT-SIZE: 12px; FONT-WEIGHT: normal; WORD-SPACING: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px" class=java name="code"><PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px" class=java name="code"><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><STRONG><SPAN style="FONT-SIZE: 18px">  
  101. </SPAN></STRONG></P><STRONG><SPAN style="FONT-SIZE: 18px">(5)test层(Java环境下测试)  
  102. </SPAN></STRONG><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><SPAN style="FONT-FAMILY: 'Courier New'"><STRONG><SPAN style="FONT-SIZE: 18px">   TestUserController.java</SPAN></STRONG></SPAN></P><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><SPAN style="FONT-FAMILY: 'Courier New'"><SPAN style="FONT-SIZE: 18px"><STRONG></STRONG></SPAN></SPAN></P><PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px" class=java name="code"><STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.test;  
  103.   
  104. import java.util.ArrayList;  
  105. import java.util.List;  
  106.   
  107. import org.springframework.context.ApplicationContext;  
  108. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  109.   
  110. import com.archie.model.User;  
  111. import com.archie.service.UserService;  
  112.   
  113. public class TestUserController {  
  114.   
  115.     public static void main(String[] args) throws Exception{  
  116.           
  117.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  118.         UserService userService = (UserService)context.getBean("userService");  
  119.         List<User> list = new ArrayList<User>();  
  120.         list.add(new User("wang""wang"));  
  121.         list.add(new User("wang""wang"));  
  122.         list.add(new User("wang""wang"));  
  123.         userService.insertUsers(list);  
  124.         System.out.println("恭喜恭喜,添加成功!");  
  125.         userService.deleteUser(26);  
  126.         System.out.println("恭喜恭喜,删除成功!");  
  127.         User beanUser = userService.getUserById(21);  
  128.         if (beanUser != null) {  
  129.             System.out.println("恭喜恭喜,查找成功!");  
  130.         }else {  
  131.             System.out.println("不好意思,您所查找的用户不存在!");  
  132.         }  
  133.         int totalCount = userService.getTotalCount();  
  134.         System.out.println("TotalCount="+totalCount);  
  135.         int result = userService.deleteUserByLike(new User("wang","wang"));  
  136.         System.out.println("模糊删除的记录条数是:"+result);  
  137.         List users = userService.getUsersByLike(new User("meimei","1234"));  
  138.         if (users == null || users.size() == 0) {  
  139.             System.out.println("没有匹配的记录2");  
  140.         }else {  
  141.             for (int i = 0; i < users.size(); i++) {  
  142.                 User user = (User)users.get(i);  
  143.                 System.out.println("username="+user.getUsername()+",password="+user.getPassword());  
  144.             }  
  145.         }  
  146.         System.out.println("length="+users.size());  
  147.     }  
  148. }                                                                                   </SPAN></STRONG></PRE>  
  149. <PRE></PRE>  
  150. <PRE></PRE>  
  151. <PRE></PRE>  
  152. <PRE></PRE>  
  153.   
  154. </PRE></PRE></PRE>  

package com.archie.web;

import javax.annotation.Resource; import javax.servlet.http.HttpSession; import javax.validation.Valid;

import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;

import com.archie.model.User; import com.archie.service.UserService;

@Controller @RequestMapping("/user/*") public class UserController {    @Resource(name="userService")  private UserService userService;  private final String LIST="redirect:/detail";     /**      * 登录      * @param user      * @param session      * @return      */     @RequestMapping("/login")     public ModelAndView login(@Valid User user,BindingResult result,HttpSession session) throws Exception{       if(!result.hasErrors()){         User loginUser=userService.login(user);         if(loginUser!=null){             session.setAttribute("USER", loginUser);             return new ModelAndView(LIST);         }else{             return new ModelAndView("redirect:/");         }       }else{           ModelAndView view=new ModelAndView();           view.setViewName("redirect:/");           view.addObject("error", result.getAllErrors());           return view;       }     }         /**      * 跳转至添加页      * @return      */     @RequestMapping(value="/toAdd",method=RequestMethod.GET)     public ModelAndView toAdd(){         return new ModelAndView("user/add");     }     /**      * 保存      * @param user      * @return      */     @RequestMapping(value="/add",method=RequestMethod.POST)     public ModelAndView add(@Valid User user,BindingResult result) throws Exception{         if(result.hasErrors()){             return new ModelAndView("user/add","error", result.getAllErrors());         }else{             userService.addUser(user);             return new ModelAndView(LIST);            }     }     /**      * 根据ID删除      * @param id      * @return      */     @RequestMapping(value="/delete/{id}")     public ModelAndView delete(@PathVariable int id) throws Exception{         userService.deleteUser(id);         return new ModelAndView(LIST);     }     /**      * 跳转至编辑页面      * @param id      * @return      */     @RequestMapping(value="/edit/{id}")     public ModelAndView edit(@PathVariable int id) throws Exception{         User user=userService.getUserById(id);         return new ModelAndView("user/edit","user",user);     }     /**      * 编辑      * @param user      * @return      */     @RequestMapping(value="/edit")     public ModelAndView update(@Valid User user,BindingResult result)throws Exception{         ModelAndView view=new ModelAndView();         if(result.hasErrors()){             view.addObject("error", result.getAllErrors());             view.setViewName("user/edit");             return view;         }else{          userService.updateUser(user);          return new ModelAndView(LIST);         }     }

}


  1. <PRE style="LINE-HEIGHT: normal; WIDOWS: 2; TEXT-TRANSFORM: none; BACKGROUND-COLOR: rgb(240,240,240); FONT-VARIANT: normal; FONT-STYLE: normal; TEXT-INDENT: 0px; MARGIN: 4px 0px; ORPHANS: 2; LETTER-SPACING: normal; COLOR: rgb(0,0,0); FONT-SIZE: 12px; FONT-WEIGHT: normal; WORD-SPACING: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px" class=java name="code"><PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px" class=java name="code"><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><STRONG><SPAN style="FONT-SIZE: 18px">  
  2. </SPAN></STRONG></P><STRONG><SPAN style="FONT-SIZE: 18px">(5)test层(Java环境下测试)  
  3. </SPAN></STRONG><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><SPAN style="FONT-FAMILY: 'Courier New'"><STRONG><SPAN style="FONT-SIZE: 18px">   TestUserController.java</SPAN></STRONG></SPAN></P><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><SPAN style="FONT-FAMILY: 'Courier New'"><SPAN style="FONT-SIZE: 18px"><STRONG></STRONG></SPAN></SPAN></P><PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px" class=java name="code"><STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.test;  
  4.   
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import org.springframework.context.ApplicationContext;  
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  10.   
  11. import com.archie.model.User;  
  12. import com.archie.service.UserService;  
  13.   
  14. public class TestUserController {  
  15.   
  16.     public static void main(String[] args) throws Exception{  
  17.           
  18.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  19.         UserService userService = (UserService)context.getBean("userService");  
  20.         List<User> list = new ArrayList<User>();  
  21.         list.add(new User("wang""wang"));  
  22.         list.add(new User("wang""wang"));  
  23.         list.add(new User("wang""wang"));  
  24.         userService.insertUsers(list);  
  25.         System.out.println("恭喜恭喜,添加成功!");  
  26.         userService.deleteUser(26);  
  27.         System.out.println("恭喜恭喜,删除成功!");  
  28.         User beanUser = userService.getUserById(21);  
  29.         if (beanUser != null) {  
  30.             System.out.println("恭喜恭喜,查找成功!");  
  31.         }else {  
  32.             System.out.println("不好意思,您所查找的用户不存在!");  
  33.         }  
  34.         int totalCount = userService.getTotalCount();  
  35.         System.out.println("TotalCount="+totalCount);  
  36.         int result = userService.deleteUserByLike(new User("wang","wang"));  
  37.         System.out.println("模糊删除的记录条数是:"+result);  
  38.         List users = userService.getUsersByLike(new User("meimei","1234"));  
  39.         if (users == null || users.size() == 0) {  
  40.             System.out.println("没有匹配的记录2");  
  41.         }else {  
  42.             for (int i = 0; i < users.size(); i++) {  
  43.                 User user = (User)users.get(i);  
  44.                 System.out.println("username="+user.getUsername()+",password="+user.getPassword());  
  45.             }  
  46.         }  
  47.         System.out.println("length="+users.size());  
  48.     }  
  49. }                                                                                   </SPAN></STRONG></PRE>  
  50. <PRE></PRE>  
  51. <PRE></PRE>  
  52. <PRE></PRE>  
  53. <PRE></PRE>  
  54.   
  55. </PRE></PRE>  
  1. <PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px" class=java name="code"><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><STRONG><SPAN style="FONT-SIZE: 18px">  
  2. </SPAN></STRONG></P><STRONG><SPAN style="FONT-SIZE: 18px">(5)test层(Java环境下测试)  
  3. </SPAN></STRONG><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><SPAN style="FONT-FAMILY: 'Courier New'"><STRONG><SPAN style="FONT-SIZE: 18px">   TestUserController.java</SPAN></STRONG></SPAN></P><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><SPAN style="FONT-FAMILY: 'Courier New'"><SPAN style="FONT-SIZE: 18px"><STRONG></STRONG></SPAN></SPAN></P><PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px" class=java name="code"><STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.test;  
  4.   
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import org.springframework.context.ApplicationContext;  
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  10.   
  11. import com.archie.model.User;  
  12. import com.archie.service.UserService;  
  13.   
  14. public class TestUserController {  
  15.   
  16.     public static void main(String[] args) throws Exception{  
  17.           
  18.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  19.         UserService userService = (UserService)context.getBean("userService");  
  20.         List<User> list = new ArrayList<User>();  
  21.         list.add(new User("wang""wang"));  
  22.         list.add(new User("wang""wang"));  
  23.         list.add(new User("wang""wang"));  
  24.         userService.insertUsers(list);  
  25.         System.out.println("恭喜恭喜,添加成功!");  
  26.         userService.deleteUser(26);  
  27.         System.out.println("恭喜恭喜,删除成功!");  
  28.         User beanUser = userService.getUserById(21);  
  29.         if (beanUser != null) {  
  30.             System.out.println("恭喜恭喜,查找成功!");  
  31.         }else {  
  32.             System.out.println("不好意思,您所查找的用户不存在!");  
  33.         }  
  34.         int totalCount = userService.getTotalCount();  
  35.         System.out.println("TotalCount="+totalCount);  
  36.         int result = userService.deleteUserByLike(new User("wang","wang"));  
  37.         System.out.println("模糊删除的记录条数是:"+result);  
  38.         List users = userService.getUsersByLike(new User("meimei","1234"));  
  39.         if (users == null || users.size() == 0) {  
  40.             System.out.println("没有匹配的记录2");  
  41.         }else {  
  42.             for (int i = 0; i < users.size(); i++) {  
  43.                 User user = (User)users.get(i);  
  44.                 System.out.println("username="+user.getUsername()+",password="+user.getPassword());  
  45.             }  
  46.         }  
  47.         System.out.println("length="+users.size());  
  48.     }  
  49. }                                                                                   </SPAN></STRONG></PRE>  
  50. <PRE></PRE>  
  51. <PRE></PRE>  
  52. <PRE></PRE>  
  53. <PRE></PRE>  
  54.   
  55. </PRE>  
  1. <P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><STRONG><SPAN style="FONT-SIZE: 18px">  
  2. </SPAN></STRONG></P><STRONG><SPAN style="FONT-SIZE: 18px">(5)test层(Java环境下测试)  
  3. </SPAN></STRONG><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><SPAN style="FONT-FAMILY: 'Courier New'"><STRONG><SPAN style="FONT-SIZE: 18px">   TestUserController.java</SPAN></STRONG></SPAN></P><P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><SPAN style="FONT-FAMILY: 'Courier New'"><SPAN style="FONT-SIZE: 18px"><STRONG></STRONG></SPAN></SPAN></P><PRE style="BACKGROUND-COLOR: rgb(240,240,240); MARGIN: 4px 0px" class=java name="code"><STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.test;  
  4.   
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import org.springframework.context.ApplicationContext;  
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  10.   
  11. import com.archie.model.User;  
  12. import com.archie.service.UserService;  
  13.   
  14. public class TestUserController {  
  15.   
  16.     public static void main(String[] args) throws Exception{  
  17.           
  18.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  19.         UserService userService = (UserService)context.getBean("userService");  
  20.         List<User> list = new ArrayList<User>();  
  21.         list.add(new User("wang""wang"));  
  22.         list.add(new User("wang""wang"));  
  23.         list.add(new User("wang""wang"));  
  24.         userService.insertUsers(list);  
  25.         System.out.println("恭喜恭喜,添加成功!");  
  26.         userService.deleteUser(26);  
  27.         System.out.println("恭喜恭喜,删除成功!");  
  28.         User beanUser = userService.getUserById(21);  
  29.         if (beanUser != null) {  
  30.             System.out.println("恭喜恭喜,查找成功!");  
  31.         }else {  
  32.             System.out.println("不好意思,您所查找的用户不存在!");  
  33.         }  
  34.         int totalCount = userService.getTotalCount();  
  35.         System.out.println("TotalCount="+totalCount);  
  36.         int result = userService.deleteUserByLike(new User("wang","wang"));  
  37.         System.out.println("模糊删除的记录条数是:"+result);  
  38.         List users = userService.getUsersByLike(new User("meimei","1234"));  
  39.         if (users == null || users.size() == 0) {  
  40.             System.out.println("没有匹配的记录2");  
  41.         }else {  
  42.             for (int i = 0; i < users.size(); i++) {  
  43.                 User user = (User)users.get(i);  
  44.                 System.out.println("username="+user.getUsername()+",password="+user.getPassword());  
  45.             }  
  46.         }  
  47.         System.out.println("length="+users.size());  
  48.     }  
  49. }                                                                                   </SPAN></STRONG></PRE>  
  50. <PRE></PRE>  
  51. <PRE></PRE>  
  52. <PRE></PRE>  
  53. <PRE></PRE>  

 

(5)test层(Java环境下测试)

   TestUserController.java

 

  1. <STRONG><SPAN style="FONT-SIZE: 18px">package com.archie.test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8.   
  9. import com.archie.model.User;  
  10. import com.archie.service.UserService;  
  11.   
  12. public class TestUserController {  
  13.   
  14.     public static void main(String[] args) throws Exception{  
  15.           
  16.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  17.         UserService userService = (UserService)context.getBean("userService");  
  18.         List<User> list = new ArrayList<User>();  
  19.         list.add(new User("wang""wang"));  
  20.         list.add(new User("wang""wang"));  
  21.         list.add(new User("wang""wang"));  
  22.         userService.insertUsers(list);  
  23.         System.out.println("恭喜恭喜,添加成功!");  
  24.         userService.deleteUser(26);  
  25.         System.out.println("恭喜恭喜,删除成功!");  
  26.         User beanUser = userService.getUserById(21);  
  27.         if (beanUser != null) {  
  28.             System.out.println("恭喜恭喜,查找成功!");  
  29.         }else {  
  30.             System.out.println("不好意思,您所查找的用户不存在!");  
  31.         }  
  32.         int totalCount = userService.getTotalCount();  
  33.         System.out.println("TotalCount="+totalCount);  
  34.         int result = userService.deleteUserByLike(new User("wang","wang"));  
  35.         System.out.println("模糊删除的记录条数是:"+result);  
  36.         List users = userService.getUsersByLike(new User("meimei","1234"));  
  37.         if (users == null || users.size() == 0) {  
  38.             System.out.println("没有匹配的记录2");  
  39.         }else {  
  40.             for (int i = 0; i < users.size(); i++) {  
  41.                 User user = (User)users.get(i);  
  42.                 System.out.println("username="+user.getUsername()+",password="+user.getPassword());  
  43.             }  
  44.         }  
  45.         System.out.println("length="+users.size());  
  46.     }  
  47. }                                                                                   </SPAN></STRONG>  
package com.archie.test;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.archie.model.User;
import com.archie.service.UserService;

public class TestUserController {

	public static void main(String[] args) throws Exception{
		
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService)context.getBean("userService");
		List<User> list = new ArrayList<User>();
		list.add(new User("wang", "wang"));
		list.add(new User("wang", "wang"));
		list.add(new User("wang", "wang"));
		userService.insertUsers(list);
		System.out.println("恭喜恭喜,添加成功!");
		userService.deleteUser(26);
		System.out.println("恭喜恭喜,删除成功!");
		User beanUser = userService.getUserById(21);
		if (beanUser != null) {
			System.out.println("恭喜恭喜,查找成功!");
		}else {
			System.out.println("不好意思,您所查找的用户不存在!");
		}
		int totalCount = userService.getTotalCount();
		System.out.println("TotalCount="+totalCount);
		int result = userService.deleteUserByLike(new User("wang","wang"));
		System.out.println("模糊删除的记录条数是:"+result);
		List users = userService.getUsersByLike(new User("meimei","1234"));
		if (users == null || users.size() == 0) {
			System.out.println("没有匹配的记录2");
		}else {
			for (int i = 0; i < users.size(); i++) {
				User user = (User)users.get(i);
				System.out.println("username="+user.getUsername()+",password="+user.getPassword());
			}
		}
		System.out.println("length="+users.size());
	}
}                                                                                   
<!-- Baidu Button BEGIN -->
分享到:
评论
6 楼 hww_1030 2015-12-13  
  
5 楼 jackclchan 2015-11-10  
你好,能将demo源码发我下吗?jackclchan@qq.com。非常感谢
4 楼 amwiqplhui 2015-10-01  
你好,能将demo源码发我下吗?772851689@qq.com。非常感谢
3 楼 jiangshenyi 2015-09-02  
你好,上面的demo 能发我一份了  deshanjiang86@126.com  
1 楼 lvgang_214 2014-11-10  
我想研究一下这个 上面的demo 能发我一份了  14589782373@qq.com   

相关推荐

    spring11+springmvc+ibatis整合注解方式实例.docx

    。。spring11+springmvc+ibatis整合注解方式实例.docx

    spring11+springmvc+ibatis整合注解方式实例.pdf

    。。spring11+springmvc+ibatis整合注解方式实例.pdf

    spring+springmvc+ibatis整合小案例

    Spring、SpringMVC和iBatis是Java开发中常见的三个框架,它们的整合使用能构建出功能强大的Web应用。这个"spring+springmvc+ibatis整合小案例"旨在为初学者提供一个清晰的实践指导,帮助理解这三者如何协同工作。 ...

    Spring+ibatis+SpringMVC简单集体demo案例

    《Spring+Ibatis+SpringMVC简单集成案例详解》 在现代Java Web开发中,Spring框架因其强大的功能和灵活性而备受青睐。它不仅提供了依赖注入(DI)和面向切面编程(AOP)的核心特性,还通过SpringMVC扩展了对Web应用...

    Spring+ibatis+struts框架整合+springmvc数据接口封装含数据表可直接运行

    接下来,我们将详细探讨这三个框架及其整合方式,以及Spring MVC的数据接口封装。 1. **Spring框架**:Spring是一个开源的Java平台,它为构建企业级应用程序提供了全面的框架支持。Spring的核心特性包括依赖注入...

    springMVC+Velocity+iBATIS整合

    在这个"SpringMVC+Velocity+iBATIS的整合小demo"中,可能包含了这些配置文件、Controller类、Service接口及其实现、Mapper接口及其XML配置、Velocity模板文件等。通过这些文件,我们可以看到一个完整的Java Web应用...

    springMVC+ibatis整合实例

    SpringMVC作为Spring框架的一部分,主要用于构建Web应用程序的Model-View-Controller(MVC)架构,而iBatis则是一个轻量级的持久层框架,它将SQL查询与Java代码解耦,提供了灵活的数据库操作方式。 SpringMVC的核心...

    mybatis+springmvc自己整合封装的实例

    本实例"mybatis+springmvc自己整合封装的实例"是作者花费时间精心整合的一个半成品,尽管未能实现全部计划的功能,如自定义注解映射,但仍然具有很高的学习价值。以下将详细介绍这个整合过程中的关键知识点。 1. ...

    Spring MVC+ibatis+oracle框架整合

    本项目整合了Spring MVC、iBatis和Oracle数据库,这三个组件都是企业级应用开发中的重要工具。接下来,我们将深入探讨这三个技术以及它们如何协同工作。 **Spring MVC框架** Spring MVC是Spring框架的一部分,是一...

    springMVC整合ibatis 配置详细

    SpringMVC作为Spring框架的一部分,主要用于构建Web应用程序的模型-视图-控制器(MVC)架构,而iBatis则是一个轻量级的持久层框架,它将SQL与Java代码分离,提供灵活的数据访问。下面将详细讲解如何整合这两个框架...

    springMVC+ibatis案例

    SpringMVC作为Spring框架的一部分,主要用于处理HTTP请求和响应,而iBatis则是一个优秀的持久层框架,它简化了数据库操作,使得开发者可以更加专注于业务逻辑。 SpringMVC是一个基于模型-视图-控制器(MVC)设计...

    springmvc+ibatis

    springmvc+ibatis实例,只要修改一下数据配置文件,并创建相应的数据库,表,表只有一个tab_User,很好用的,实例是我花了好久才弄出来,各种包齐全,包绝对不多,也不少,就是刚刚好的感觉,懂吗?就是不会出现多余...

    SpringMVC整合ibatis的小例子

    在本文中,我们将深入探讨如何将SpringMVC与iBatis进行整合,以便构建一个高效、灵活的Web应用程序。SpringMVC是Spring框架的一部分,它提供了强大的MVC(Model-View-Controller)架构来处理HTTP请求,而iBatis则是...

    springmvc整合ibatis

    整合 SpringMVC 和 iBatis 可以使业务逻辑和数据访问层分离,提高代码的可读性和可维护性,同时利用 Spring 的依赖注入特性,实现 iBatis SqlSession 和 Mapper 接口的自动管理。 4. **配置步骤** - **pom.xml**...

    Maven2项目集成springmvc,spring3,ibatis和freemarker实例

    本实例" Maven2项目集成springmvc, spring3, ibatis和freemarker"提供了一个完整的解决方案,旨在帮助开发者快速搭建基于这些技术的Web应用程序。以下是这些技术的详细说明和集成过程。 **Maven2**: Maven是一款...

    spring-mvc+iBatis:maven

    下面将详细讨论如何使用 Maven 整合 Spring MVC 和 iBatis。 **1. Maven 介绍** Maven 是一个项目管理和综合工具,它通过读取项目的配置文件(pom.xml)来管理项目的构建、报告和文档生成。Maven 可以自动下载依赖...

    springMvc_ibatis_mybatis

    在"springMvc_ibatis_mybatis"这个项目中,开发者可以学习如何在Spring MVC环境中集成iBatis或MyBatis,以及如何使用JDBC进行基本的数据操作。 通过这个项目,初学者可以掌握Spring MVC的基本架构,理解iBatis或...

    springmvc_web_ibatis

    标题 "springmvc_web_ibatis" 暗示了我们即将探讨的是一个关于Spring MVC、Web开发以及MyBatis集成的项目或教程。这个项目可能是为了展示如何在Java Web应用程序中有效地利用这三个技术来构建数据驱动的Web应用。...

    Spring+mybatis

    8. 实例化SqlSession:在Service层,使用Spring的`@Autowired`注解注入DAO接口,Spring会自动创建SqlSession并调用相应的方法。 通过这种整合,我们可以在Spring MVC的环境中,利用MyBatis进行数据库操作,同时享受...

    SSM三大框架的整合.pdf

    SSM 三大框架的整合是指 Spring、SpringMVC 和 MyBatis 三大框架的整合,目的是为了实现一个完整的 Java_web 应用程序。下面将从根本概念、整合步骤、配置实例演示三个方面对 SSM 的整合进行详细的介绍。 一、根本...

Global site tag (gtag.js) - Google Analytics