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

Spring 同时被 3 个专栏收录
46 篇文章 0 订阅
43 篇文章 0 订阅
15 篇文章 0 订阅

转自:http://shaohan126448.iteye.com/blog/2033563

1.需求说明

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

 

2.数据库表

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

   

字段名称数据类型字段描述
IDint用户编号
USERNAMEVARCHAR用户名
PASSWORDVARCHAR用户登录密码
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日志框架    

 

[html]  view plain copy print ?
  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>  
Html代码   收藏代码
  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>  

 

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

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

 

[html]  view plain copy print ?
  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>  
Html代码   收藏代码
  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>  

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

 

 

[html]  view plain copy print ?
  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>  
Html代码   收藏代码
  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>  

 

 

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

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

 

[html]  view plain copy print ?
  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>  
Html代码   收藏代码
  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>  

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

 

log4j日志属性配置文件

[html]  view plain copy print ?
  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>  
Html代码   收藏代码
  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>  

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

 

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

 

[html]  view plain copy print ?
  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>  
Html代码   收藏代码
  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>  

6.Java代码编写

 

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

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

   User.java代码

 

[java]  view plain copy print ?
  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>  
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>  
   User.xml代码(model层对象的sql映射文件,被dao层调用,本质是sql语句集合,所有相关的sql均于此)

 

 

[html]  view plain copy print ?
  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>  
Html代码   收藏代码
  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>  

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

 

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

 

[java]  view plain copy print ?
  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>  
Java代码   收藏代码
  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>  

   UserDao.java(user数据服务层)

 

 

[java]  view plain copy print ?
  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>  
Java代码   收藏代码
  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>  

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

 

   UserService.java代码如下

 

[java]  view plain copy print ?
  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>  
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>  

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

 

   UserController.java

 

[java]  view plain copy print ?
  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);         }     }

}

 
[java]  view plain copy print ?
  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>  
[java]  view plain copy print ?
  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>  
[java]  view plain copy print ?
  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>  

 

Java代码   收藏代码
  1. <strong><span style="font-size: 18px;">(5)test层(Java环境下测试)  
  2. </span></strong>  

   TestUserController.java

 

[java]  view plain copy print ?
  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>  
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>  

  • 0
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页