实现用户通过数据库验证登录需求,采用Myeclipse+Tomcat 6.0+Mysql 5.0+JDK 1.6
2.数据库表
开发所用是Mysql数据库,只建立单张用户表T_USER,表结构如下:
字段名称 | 数据类型 | 字段描述 |
ID | int | 用户编号 |
USERNAME | VARCHAR | 用户名 |
PASSWORD | VARCHAR | 用户登录密码 |
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.构建源代码目录
4.用到的jar包(见附件Archive.rar)
5.各项Xml配置文件详解
(1)web.xml文件(Tomcat使用)
服务器根据配置内容初始化spring框架,springmvc框架和log4j日志框架
- <STRONG><SPAN style="FONT-SIZE: 18px"><?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><SPAN>/WEB-INF/classes/log4j.properties</SPAN></param-value>
- </context-param>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value><SPAN>/WEB-INF/classes/applicationContext.xml</SPAN></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><SPAN>org.springframework.web.util.Log4jConfigListener</SPAN></listener-class>
- </listener>
- <listener>
- <listener-class><SPAN>org.springframework.web.context.ContextLoaderListener</SPAN></listener-class>
- </listener>
- <!-- Servlet初始化参数,配置springmvc模块 -->
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class><SPAN>org.springframework.web.servlet.DispatcherServlet</SPAN></servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value><SPAN>/WEB-INF/classes/springmvc-servlet.xml</SPAN></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>
- </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框架配置文件,也是它的核心文件
- <STRONG><SPAN style="FONT-SIZE: 18px"><?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></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框架配置文件)
- <STRONG><SPAN style="FONT-SIZE: 18px"><?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></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
- <STRONG><SPAN style="FONT-SIZE: 18px"># 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
- </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日志属性配置文件
- <STRONG><SPAN style="FONT-SIZE: 18px"># 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
- </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层对象对应的映射文件
- <STRONG><SPAN style="FONT-SIZE: 18px"><?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></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代码
- <STRONG><SPAN style="FONT-SIZE: 18px">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;
- }
- }
- </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均于此)
- <STRONG><SPAN style="FONT-SIZE: 18px"><?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></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均继承它)
- <STRONG><SPAN style="FONT-SIZE: 18px">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);
- }
- }
- </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数据服务层)
- <STRONG><SPAN style="FONT-SIZE: 18px">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;
- }
- }
- </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代码如下
- <STRONG><SPAN style="FONT-SIZE: 18px">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);
- }
- }
- }
- </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
- <STRONG><SPAN style="FONT-SIZE: 18px"></SPAN></STRONG><P>package com.archie.web;</P><P>import javax.annotation.Resource;
- import javax.servlet.http.HttpSession;
- import javax.validation.Valid;</P><P>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;</P><P>import com.archie.model.User;
- import com.archie.service.UserService;</P><P>@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);
- }
- }</P><P>}
- </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">
- </SPAN></STRONG></P><STRONG><SPAN style="FONT-SIZE: 18px">(5)test层(Java环境下测试)
- </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;
- 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());
- }
- } </SPAN></STRONG></PRE>
- <PRE></PRE>
- <PRE></PRE>
- <PRE></PRE>
- <PRE></PRE>
- </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); } }
}
- <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">
- </SPAN></STRONG></P><STRONG><SPAN style="FONT-SIZE: 18px">(5)test层(Java环境下测试)
- </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;
- 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());
- }
- } </SPAN></STRONG></PRE>
- <PRE></PRE>
- <PRE></PRE>
- <PRE></PRE>
- <PRE></PRE>
- </PRE></PRE>
- <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">
- </SPAN></STRONG></P><STRONG><SPAN style="FONT-SIZE: 18px">(5)test层(Java环境下测试)
- </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;
- 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());
- }
- } </SPAN></STRONG></PRE>
- <PRE></PRE>
- <PRE></PRE>
- <PRE></PRE>
- <PRE></PRE>
- </PRE>
- <P style="PADDING-BOTTOM: 2px; MARGIN: 4px 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 2px"><STRONG><SPAN style="FONT-SIZE: 18px">
- </SPAN></STRONG></P><STRONG><SPAN style="FONT-SIZE: 18px">(5)test层(Java环境下测试)
- </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;
- 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());
- }
- } </SPAN></STRONG></PRE>
- <PRE></PRE>
- <PRE></PRE>
- <PRE></PRE>
- <PRE></PRE>
(5)test层(Java环境下测试)
TestUserController.java
- <STRONG><SPAN style="FONT-SIZE: 18px">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());
- }
- } </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());
}
}
相关推荐
。。spring11+springmvc+ibatis整合注解方式实例.docx
。。spring11+springmvc+ibatis整合注解方式实例.pdf
Spring、SpringMVC和iBatis是Java开发中常见的三个框架,它们的整合使用能构建出功能强大的Web应用。这个"spring+springmvc+ibatis整合小案例"旨在为初学者提供一个清晰的实践指导,帮助理解这三者如何协同工作。 ...
《Spring+Ibatis+SpringMVC简单集成案例详解》 在现代Java Web开发中,Spring框架因其强大的功能和灵活性而备受青睐。它不仅提供了依赖注入(DI)和面向切面编程(AOP)的核心特性,还通过SpringMVC扩展了对Web应用...
接下来,我们将详细探讨这三个框架及其整合方式,以及Spring MVC的数据接口封装。 1. **Spring框架**:Spring是一个开源的Java平台,它为构建企业级应用程序提供了全面的框架支持。Spring的核心特性包括依赖注入...
在这个"SpringMVC+Velocity+iBATIS的整合小demo"中,可能包含了这些配置文件、Controller类、Service接口及其实现、Mapper接口及其XML配置、Velocity模板文件等。通过这些文件,我们可以看到一个完整的Java Web应用...
SpringMVC作为Spring框架的一部分,主要用于构建Web应用程序的Model-View-Controller(MVC)架构,而iBatis则是一个轻量级的持久层框架,它将SQL查询与Java代码解耦,提供了灵活的数据库操作方式。 SpringMVC的核心...
本实例"mybatis+springmvc自己整合封装的实例"是作者花费时间精心整合的一个半成品,尽管未能实现全部计划的功能,如自定义注解映射,但仍然具有很高的学习价值。以下将详细介绍这个整合过程中的关键知识点。 1. ...
本项目整合了Spring MVC、iBatis和Oracle数据库,这三个组件都是企业级应用开发中的重要工具。接下来,我们将深入探讨这三个技术以及它们如何协同工作。 **Spring MVC框架** Spring MVC是Spring框架的一部分,是一...
SpringMVC作为Spring框架的一部分,主要用于构建Web应用程序的模型-视图-控制器(MVC)架构,而iBatis则是一个轻量级的持久层框架,它将SQL与Java代码分离,提供灵活的数据访问。下面将详细讲解如何整合这两个框架...
SpringMVC作为Spring框架的一部分,主要用于处理HTTP请求和响应,而iBatis则是一个优秀的持久层框架,它简化了数据库操作,使得开发者可以更加专注于业务逻辑。 SpringMVC是一个基于模型-视图-控制器(MVC)设计...
springmvc+ibatis实例,只要修改一下数据配置文件,并创建相应的数据库,表,表只有一个tab_User,很好用的,实例是我花了好久才弄出来,各种包齐全,包绝对不多,也不少,就是刚刚好的感觉,懂吗?就是不会出现多余...
在本文中,我们将深入探讨如何将SpringMVC与iBatis进行整合,以便构建一个高效、灵活的Web应用程序。SpringMVC是Spring框架的一部分,它提供了强大的MVC(Model-View-Controller)架构来处理HTTP请求,而iBatis则是...
整合 SpringMVC 和 iBatis 可以使业务逻辑和数据访问层分离,提高代码的可读性和可维护性,同时利用 Spring 的依赖注入特性,实现 iBatis SqlSession 和 Mapper 接口的自动管理。 4. **配置步骤** - **pom.xml**...
本实例" Maven2项目集成springmvc, spring3, ibatis和freemarker"提供了一个完整的解决方案,旨在帮助开发者快速搭建基于这些技术的Web应用程序。以下是这些技术的详细说明和集成过程。 **Maven2**: Maven是一款...
下面将详细讨论如何使用 Maven 整合 Spring MVC 和 iBatis。 **1. Maven 介绍** Maven 是一个项目管理和综合工具,它通过读取项目的配置文件(pom.xml)来管理项目的构建、报告和文档生成。Maven 可以自动下载依赖...
在"springMvc_ibatis_mybatis"这个项目中,开发者可以学习如何在Spring MVC环境中集成iBatis或MyBatis,以及如何使用JDBC进行基本的数据操作。 通过这个项目,初学者可以掌握Spring MVC的基本架构,理解iBatis或...
标题 "springmvc_web_ibatis" 暗示了我们即将探讨的是一个关于Spring MVC、Web开发以及MyBatis集成的项目或教程。这个项目可能是为了展示如何在Java Web应用程序中有效地利用这三个技术来构建数据驱动的Web应用。...
8. 实例化SqlSession:在Service层,使用Spring的`@Autowired`注解注入DAO接口,Spring会自动创建SqlSession并调用相应的方法。 通过这种整合,我们可以在Spring MVC的环境中,利用MyBatis进行数据库操作,同时享受...
SSM 三大框架的整合是指 Spring、SpringMVC 和 MyBatis 三大框架的整合,目的是为了实现一个完整的 Java_web 应用程序。下面将从根本概念、整合步骤、配置实例演示三个方面对 SSM 的整合进行详细的介绍。 一、根本...