Spring + SpringMVC + MyBatis
1.需求说明
实现用户通过数据库验证登录需求,采用Myeclipse+Tomcat 6.0+Mysql 5.0+JDK 1.6
2.数据库表
开发所用是Mysql数据库,只建立单张用户表T_USER,表结构如下:
字段名称 数据类型 字段描述
ID int 用户编号
USERNAME VARCHAR 用户名
PASSWORD VARCHAR 用户登录密码
sql语句如下:
CREATE TABLE `t_user` (
`ID` int(11) NOT NULL auto_increment,
`USERNAME` varchar(255) default NULL,
`PASSWORD` varchar(255) default NULL,
PRIMARY KEY (`ID`)
);
3.构建源代码目录
4.用到的jar包(见附件Archive.rar)
5.各项Xml配置文件详解
(1)web.xml文件(Tomcat使用)
服务器根据配置内容初始化spring框架,springmvc框架和log4j日志框架
<?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框架配置文件,也是它的核心文件
<?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框架配置文件)
<?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
# 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日志属性配置文件
# 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层对象对应的映射文件
<?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代码
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均于此)
<?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均继承它)
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数据服务层)
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代码如下
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
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);
}
}
}
(5)test层(Java环境下测试)
TestUserController.java
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());
}
}
Spring + SpringMVC + MyBatis的更多相关文章
- 基于Spring+SpringMVC+Mybatis的Web系统搭建
系统搭建的配置大同小异,本文在前人的基础上做了些许的改动,重写数据库,增加依据权限的动态菜单的实现,也增加了后台返回json格式数据的配置,详细参见完整源码. 主要的后端架构:Spring+Sprin ...
- IDEA中maven搭建Spring+SpringMVC+mybatis项目
一.介绍 使用IDEA搭建maven web项目,整合框架Spring+SpringMVC+mybatis 项目结构图:
- 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(三)
Spring+SpringMVC MVC呢,现在似乎越来越流行使用SpringMVC框架,我自己用的感觉,是非常好,确实很舒服,配置一开始是麻烦了一点点,但是后续的开发真的是很清爽! SpringMV ...
- Spring+SpringMvc+Mybatis框架集成搭建教程
一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼 ...
- Spring+SpringMVC+MyBatis+LogBack+C3P0+Maven+Git小结(转)
摘要 出于兴趣,想要搭建一个自己的小站点,目前正在积极的准备环境,利用Spring+SpringMVC+MyBatis+LogBack+C3P0+Maven+Git,这里总结下最近遇到的一些问题及解决 ...
- [JSP]Maven+SSM框架(Spring+SpringMVC+MyBatis) - Hello World
来源:http://blog.csdn.net/zhshulin/article/details/37956105?utm_source=tuicool&utm_medium=referral ...
- Spring+springmvc+Mybatis整合案例 annotation版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:annotation版 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version=&qu ...
- Spring+springmvc+Mybatis整合案例 xml配置版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:xml版(myeclipse) 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version ...
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)【转载】
最近在学习Spring+SpringMVC+MyBatis的整合.以下是参考网上的资料自己实践操作的详细步骤. 1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于20 ...
- 详细整合教程(Spring+SpringMVC+MyBatis)
详细整合教程(Spring+SpringMVC+MyBatis) http://blog.csdn.net/gebitan505/article/details/44455235/
随机推荐
- linux 配合仅主机模式
- plain framework 1 版本更新 1.0.2 增加打包插件
由于个别因素,该框架的文档没有及时的更新到博客上,但是离线的文档已经完成.本次更新对框架来说显得比较重要,因为在文档的编写过程中经过再次的阅读代码修复了不少错误,最主要的是统一了整个框架的标准风格.对 ...
- AngularJs学习总结-了解基本特性(-)
现在的前端项目中基本上都会用到angularjs框架,之前并不了解这个框架,也是因为最近接手的项目,所以打算好好的学习下它.之前都是搞pc端,现在接手的是移动端的项目,移动端UI框架用的是ionic+ ...
- CF 672C Recycling Bottles[最优次优 贪心]
C. Recycling Bottles time limit per test 2 seconds memory limit per test 256 megabytes input standar ...
- 第14章 位图和位块传输_14.4 GDI位图对象(3)
14.4.10 非矩形的位图图像 (1)“掩码”位图——单色位图,要显示的像素对应的掩码置1,不显示置0(2)光栅操作(点这里,见此文分析) (3)MaskBlt函数 ①MaskBlt(hdcDest ...
- [转] 如何设置Eclipse的上网代理
from: http://blog.csdn.net/qq635785620/article/details/8191799 不同版本的eclipse有不同的设置方法 方式一: 默认的Eclips ...
- 第六课——UIDynamicAnimator
今天我们要学习UIDynamicAnimator 仿真物理学 . UIKit 力学(Dynamics) 和动态效果(Motion Effects) . 创建力学基本流程: 创建运动管理 创建运动行为( ...
- li标签包含img的问题
我们在制作页面时,经常有可能碰到这样的设计: li 图一 图一的布局代码如下: <ul> <li><img src=”pic1.jpg” />& ...
- ubuntu下crontab编辑方法的设定
在ubuntu下,首次编辑crontab计划任务的时候,会提示让选择编辑器.由于对nano编辑器不是很熟悉,若是选择nova编辑的话,会有些麻烦.可以重置编辑器,方法如下:[root@wang ~]# ...
- 自定义JS常用方法
1,获取表格中的元素,支持IE,chrome,firefox //获取表单元素的某一个值 function getTableColumnValue(tableId, rowNumber, column ...