码云项目地址http://git.oschina.net/chronosliu/mssm
前言
Maven+Spring+SpringMVC+Hibernate+Mysql的简单整合(入门级),实现数据库的增删查改。Maven管理项目,统一开发规范和工具、统一管理Jar包。Spring轻量级的Java开发框架、控制反转IOC和依赖注入DI来管理对象依赖关系.、面向切面编程AOP来管理事物等。SpringMVC轻量级Web框架,使用MVC架构思想对web层进行解耦,简化开发。Mybatis半自动ORM(对象关系映射)框架,是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。Mysql关系型数据库。
前端使用Bootstrap 框架,用于开发响应式布局,界面风格简洁美观。
效果图
开发环境
- JDK1.7
- Tomcat7
- Spring 4.3.7
- SpringMVC 4.3.7
- Maven 3.3
- Mybatis3.2.6
项目结构
Maven配置 pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.chronos</groupId>
<artifactId>mssm</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>mssm Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- 测试相关 start -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- 测试相关 end -->
<!-- spring 相关 -->
<dependency> <!-- spring核心工具包 -->
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency> <!-- springIOC基础实现 -->
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency> <!-- spring web相关核心 -->
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency> <!-- aop 面向切面编程 -->
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency> <!-- 事务 -->
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency> <!-- orm 整合第三方orm实现 -->
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency> <!-- 对JDBC 的简单封装 -->
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency> <!-- spring 表达式语言-->
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency> <!-- 测试框架-->
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- spring 相关 -->
<dependency> <!-- aop依赖包 -->
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<!-- spring mvc 相关 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- spring mvc 相关 -->
<!-- web相关 start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency> <!-- jstl标签 -->
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- web相关 end -->
<!-- MyBatis相关 start -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- mybatis分页插件依赖 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<!-- MyBatics相关 end -->
<!-- hibernate相关 start-->
<!-- <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.8.Final</version>
</dependency> -->
<!-- ehcache缓存 -->
<!-- <dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.2</version>
</dependency> -->
<!-- hibernate相关 end -->
<!-- 数据库相关 -->
<dependency> <!-- 阿里druid连接池 -->
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<dependency> <!-- mysql驱动 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- 数据库相关 -->
<!-- json相关 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.4</version>
</dependency>
<!-- json相关 -->
<!-- 日志相关 statr -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6</version>
</dependency>
<!-- 日志相关 end -->
</dependencies>
<build>
<finalName>mssm</finalName>
</build>
</project>
和Mybatis框架相关的Jar包有2个,mybatis和mybatis-spring。
数据库配置 config.properties
##mysql数据库
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mssm?useUnicode=true&characterEncoding=UTF-8
user=root
password=root
dbname=mssm
##oracle数据库
#driverClass=oracle.jdbc.OracleDriver
#url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#username=ptest
#password=password
#dbname=orcl
#配置初始化大小、最小、最大 、等待时间
initialSize=1
minIdle=1
maxIdle=20
maxActive=100
maxWait=60000
##hiberate属性
#hibernate.hbm2ddl.auto=update
#hibernate.dialect=org.hibernate.dialect.MySQLDialect
#hibernate.show_sql=true
#hibernate.format_sql=true
Spring 配置 Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 加载config资源文件 其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载 -->
<context:property-placeholder location="classpath:config.properties"/>
<!-- 自动扫描dao和service包(自动注入) 排除过滤@Controller-->
<context:component-scan base-package="com.chronos.mssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置数据源 阿里druid -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!-- 数据库驱动 -->
<property name="driverClassName" value="${driverClass}" />
<!-- 基本属性 url、user、password -->
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${initialSize}" />
<property name="minIdle" value="${minIdle}" />
<property name="maxActive" value="${maxActive}" />
<!-- 配置获取连接等待超时的时间 6000-->
<property name="maxWait" value="${maxWait}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters -->
<!-- <property name="filters" value="stat" /> -->
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<!-- <property name="configLocation" value="classpath:mybatis-config.xml"/> mybatis配置文件 -->
<property name="mapperLocations"> <!-- 自动扫描 mapper文件 -->
<list>
<value >classpath*:/com/chronos/mssm/mapper/*Mapper.xml</value>
</list>
</property>
</bean>
<!-- sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" >
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!-- 事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--1、 注解方式配置事务 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager"/> -->
<!--2、 拦截方式配置事务 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <!-- 事务通知定义 -->
<tx:attributes> <!-- 指定拦截的方法 -->
<tx:method name="save*" propagation="REQUIRED"/><!-- propagation传播行为 -->
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/> <!-- 拦截其它所有* -->
</tx:attributes>
</tx:advice>
<aop:config> <!-- aop相关配置 -->
<aop:pointcut id="aopPointcut" expression="execution(* com.chronos.mssm.service..*Impl.*(..))" /> <!-- 切入点定义 -->
<aop:advisor pointcut-ref="aopPointcut" advice-ref="transactionAdvice"/> <!-- 通知Advisor定义 -->
</aop:config>
<!-- aop 开启代理 --> <!--expose-proxy:true 表示将当前代理对象暴露出去. proxy-target-class : false,使用jdk动态代理织入增强;true,使用CGLib动态代理技术织入增强; -->
<aop:aspectj-autoproxy expose-proxy="false" proxy-target-class="true"/>
</beans>
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。SqlSessionFactory有一些属性,包括数据源、映射文件、mybatis其它相关配置。从SqlSessionFactory中获取sqlSession,SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。把SqlSession注入dao层使用。
SpringMVC 配置 spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 扫描Controll -->
<context:component-scan base-package="com.chronos.mssm.controller"></context:component-scan>
<!-- 开启自动扫描 -->
<mvc:annotation-driven/>
<!-- 支持视图解析-->
<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/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理 -->
<!-- <mvc:default-servlet-handler/> -->
<mvc:resources location="/image/" mapping="/image/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/fonts/" mapping="/fonts/**"></mvc:resources>
<mvc:resources location="/" mapping="**.jsp"></mvc:resources>
<mvc:resources location="/" mapping="**.html"></mvc:resources>
<!-- 支持json返回 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</beans>
注意:配置静态资源访问,不被DispatcherServlet处理。配置JSON返回支持解决前后台交互出现问题。
Controller层 UserController
package com.chronos.mssm.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.chronos.mssm.model.ReturnResult;
import com.chronos.mssm.model.User;
import com.chronos.mssm.service.IUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
/**
* 用户Controller
*
* @author chronos
* @date 2017年5月12日 下午1:57:58
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
public IUserService getUserService() {
return userService;
}
public void setUserService(IUserService userService) {
this.userService = userService;
}
/**
* 新增用户
* produces="text/html;charset=UTF-8 解决返回结果中文乱码
* @param user
* @return
*/
@ResponseBody
@RequestMapping(value="/add",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
public String addUser(User user) {
int i = this.userService.addUser(user);
ReturnResult result = new ReturnResult();
if(i > 0) {
result.setStatus(ReturnResult.STATUS_SUCCESS);
result.setMessage("新增成功!");
} else {
result.setStatus(ReturnResult.STATUS_ERROR);
result.setMessage("新增失败!");
}
return JSONObject.toJSONString(result);
}
@RequestMapping("/query")
public String queryUser(){
String username = "chronos";
this.userService.queryUserByName(username);
return null;
}
/**
* 查询用户列表
*
* @param pageindex
* @param pageSize
* @param nickName
* @return
*/
@ResponseBody
@RequestMapping(value="/queryList",produces="text/html;charset=UTF-8")
public String queryUserList(Integer pageindex,Integer pageSize,String nickName){
List<User> list = this.userService.queryUserList(nickName);
//简单分页
long total = list.size();
int startIndex =(pageindex-1)*pageSize; //开始下标
int endIndex = (int) (total < (pageindex*pageSize) ? total:(pageindex*pageSize)); //结束下标
List<User> subUser = list.subList(startIndex,endIndex);//获取子list,左闭右开
JSONObject result = new JSONObject();
result.put("rows", subUser);
result.put("total", total);
System.out.println(result.toJSONString());
return result.toJSONString();
}
/**
* 更新用户
*
* @param user
* @return
*/
@ResponseBody
@RequestMapping(value="/update",produces="text/html;charset=UTF-8")
public String updateUser(User user){
int count = this.userService.updateUser(user);
ReturnResult result = new ReturnResult();
if(count > 0) {
result.setStatus(ReturnResult.STATUS_SUCCESS);
result.setMessage("修改成功!");
} else {
result.setStatus(ReturnResult.STATUS_ERROR);
result.setMessage("修改失败!");
}
return JSONObject.toJSONString(result);
}
/**
* 删除用户
*
* @param user
* @return
*/
@ResponseBody
@RequestMapping(value="/delete",produces="text/html;charset=UTF-8")
public String deleteUser(@RequestBody User user){
int count = this.userService.deleteUser(user);
ReturnResult result = new ReturnResult();
if(count > 0) {
result.setStatus(ReturnResult.STATUS_SUCCESS);
result.setMessage("删除成功!");
} else {
result.setStatus(ReturnResult.STATUS_ERROR);
result.setMessage("删除失败!");
}
return JSONObject.toJSONString(result);
}
}
注解解释:
- @Controller 定义一个控制器类
- @RequestMapping 处理请求地址映射,六个属性
- value 指定请求的实际地址
- method 指定请求的method类型,GET、POST等
- consumes 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html
- produces 指定返回的内容类型Content-Type,仅当request请求头中的(Accept)类型中包含该指定类型才返回, 字符编码charset=UTF-8 解决返回中文乱码。
- params 指定request中必须包含某些参数值
- headers 指定request中必须包含某些指定的header值
- @ReqeustBody 用来处理Content-Type: 不是
application/x-www-form-urlencoded
编码的内容,例如application/json, application/xml等 - @ResponseBody 用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区,返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用
Dao层UserDaoImpl
package com.chronos.mssm.dao.impl;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.chronos.mssm.dao.IUserDao;
import com.chronos.mssm.model.User;
/**
* 用户dao层实现
*
* @author chronos
* @date 2017年5月12日 下午4:19:16
*/
@Repository
public class UserDaoImpl implements IUserDao{
@Autowired
private SqlSession sqlSession;
//mapper文件的namespace
private String mapperNamespace = "com.chronos.mssm.mapper.user";
public SqlSession getSqlSession() {
return sqlSession;
}
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
/**
* 添加一个用户
*/
@Override
public int addUser(User user) {
int i =this.sqlSession.insert(mapperNamespace+".insertUser",user);
return i;
}
/**
* 查询用户
*/
@Override
public void queryUserByName(String username) {
User user = this.sqlSession.selectOne(mapperNamespace+".selectUser", username);
}
@Override
public int deleteUser(User user) {
// TODO Auto-generated method stub
int i = this.sqlSession.delete(mapperNamespace+".deleteUser", user);
return i;
}
@Override
public int updateUser(User user) {
// TODO Auto-generated method stub
int i = this.sqlSession.update(mapperNamespace+".updateUser", user);
return i;
}
@Override
public List queryUserList(String nickName) {
// TODO Auto-generated method stub
List list = this.sqlSession.selectList(this.mapperNamespace+".selectUserList",nickName);
return list;
}
}
Mapper文件 UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chronos.mssm.mapper.user">
<!-- cache – 给定命名空间的缓存配置。
cache-ref – 其他命名空间缓存配置的引用。
resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。
parameterMap – 已废弃!老式风格的参数映射。内联参数是首选,这个元素可能在将来被移除,这里不会记录。
sql – 可被其他语句引用的可重用语句块。
insert – 映射插入语句
update – 映射更新语句
delete – 映射删除语句
select – 映射查询语句-->
<!-- <resultMap type="com.chronos.mssm.model.User" id="user">
</resultMap> -->
<!-- 插入insert -->
<insert id="insertUser" parameterType="com.chronos.mssm.model.User">
insert into user (username,password,nickname,age,sex,signature)
values (#{userName},#{password},#{nickName},#{age},#{sex},#{signature})
</insert>
<!-- 查询select -->
<select id="selectUser" parameterType="string" resultType="com.chronos.mssm.model.User">
select * from user where username = #{username}
</select>
<!-- 查询用户列表 -->
<select id="selectUserList" parameterType="String" resultType="com.chronos.mssm.model.User">
select * from user where 1=1
<if test="_parameter != null and _parameter != ''">
and nickName = #{nickName}
</if>
order by id
</select>
<!-- 更新update -->
<update id="updateUser" parameterType="com.chronos.mssm.model.User">
update user set password = #{password},userName = #{userName},
nickName = #{nickName},age = #{age},sex = #{sex},signature = #{signature}
where id = #{id}
</update>
<!-- 删除delete -->
<delete id="deleteUser" parameterType="com.chronos.mssm.model.User">
delete from user where id = #{id}
</delete>
</mapper>
前台页面 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>MyBatis测试</title>
<!-- Bootstrap -->
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/bootstrap-table/bootstrap-table.css" >
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading" >用户列表</div>
<div class="panel-body">
<div id="toolbar" >
<form class="form-inline" style="width:100%">
<div class="form-group">
<input type="button" value="新增用户" id="addBtn" data-toggle="modal" data-target="#addUserModal" class="btn btn-primary" >
</div>
<div class="form-group">
<input type="button" value="删除用户" id="deleteBtn" class="btn btn-primary" onclick="deleteUser()">
</div>
<div class="form-group">
<input type="button" value="修改用户" id="editBtn" class="btn btn-primary" onclick="editUser()">
</div>
<div class="form-group">
<label for="nickname">昵称</label>
<input type="text" id="nickname" class="form-control">
<input type="button" class="btn btn-primary" id="queryBtn" value="查询" onclick="queryUser()">
</div>
</form>
</div>
<div class="container" style="width:100%">
<table id="userList" >
</table>
</div>
</div>
</div>
<!-- 新增用户模态窗体 -->
<div class="modal fade" id="addUserModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header ">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="resetForm()"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">用户信息</h4>
</div>
<div class="modal-body">
<form id="addUserForm" class="form-horizontal" action="user/add" method="post">
<input type="hidden" name ="id" id="userId">
<div class="form-group">
<label for="userName" class="col-sm-2 control-label">用户名称:</label>
<div class="col-sm-10">
<input type="text" name="userName" id="userName" class="form-control">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">密码:</label>
<div class="col-sm-10">
<input type="password" name="password" id="password" class="form-control">
</div>
</div>
<div class="form-group">
<label for="nickName" class="col-sm-2 control-label">昵称:</label>
<div class="col-sm-10">
<input type="text" name="nickName" id="nickName" class="form-control">
</div>
</div>
<div class="form-group">
<label for="age" class="col-sm-2 control-label">年龄:</label>
<div class="col-sm-10">
<input type="text" name="age" id="age" class="form-control">
</div>
</div>
<div class="form-group">
<label for="sex" class="col-sm-2 control-label">性别:</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="sex" id="sex1" value="true"> 男
</label>
<label class="radio-inline">
<input type="radio" name="sex" id="sex2" value="false"> 女
</label>
</div>
</div>
<div class="form-group">
<label for="signature" class="col-sm-2 control-label">个性签名:</label>
<div class="col-sm-10">
<input type="text" name="signature" id="signature" class="form-control">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="resetForm()">取消</button>
<button type="button" class="btn btn-primary" onclick="addUser()">确定</button>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<script src="js/bootstrap-table/bootstrap-table.js"></script>
<script src="js/bootstrap-table/bootstrap-table-zh-CN.js"></script>
<script type="text/javascript">
$(function(){
initTable();
});
function initTable(){
$("#userList").bootstrapTable({
method:"POST",
contentType : "application/x-www-form-urlencoded",
dataType:"json",
url:"user/queryList",
queryParams:queryParam,
striped: true,
pagination:true,
pageNumber:1, //初始化加载第一页,默认第一页
pageSize: 5, //每页的记录行数(*)
pageList: [10, 25, 50, 100], //可供选择的每页的行数(*)
uniqueId: "id",
sidePagination: "server", //server表示服务端分页,client客户端分页
singleSelect:true,
clickToSelect:true,
showRefresh:true,
showToggle:true,
toolbar:"#toolbar",
columns:[{
field:"state",
checkbox:"true"
},{
field:"id",
title:"ID"
},{
field:"userName",
title:"用户名称"
},{
field:"password",
title:"密码"
},{
field:"nickName",
title:"昵称"
},{
field:"age",
title:"年龄"
},{
field:"sex",
title:"性别",
formatter:function(value){
if(value == true) {
return '男';
} else {
return '女';
}
}
},{
field:"signature",
title:"个性签名"
}],
});
}
function queryParam(params){
var param = {
nickName:$("#nickname").val(),
limit : this.limit, // 页面大小
offset : this.offset, // 页码
pageindex : this.pageNumber,
pageSize : this.pageSize
};
return param;
}
//新增用户
function addUser(){
var param = $("#addUserForm").serializeArray();
var id = $("#userId").val();
var url = "user/add";
if ( id != '') {
url = "user/update"
}
$.ajax({
url:url,
method:"post",
data:param,
dataType:"json",
success:function(data){
if (data.status = "success") {
$("#userList").bootstrapTable("refresh");
$("#addUserModal").modal("hide");
resetForm();
}
alert(data.message);
},
error:function(data){
alert("服务器异常!");
}
});
}
//清空表单数据
function resetForm(){
document.getElementById("addUserForm").reset();
}
//删除用户
function deleteUser(){
var rows = $("#userList").bootstrapTable('getSelections');
var id = rows[0].id;
var data = {"id":id,"userName":"aaa"};
if (rows.length<=0 ) {
alert("请选择一条记录!");
return;
}
$.ajax({
url:"user/delete",
method:"post",
dataType:"json",
contentType:"application/json;charset=UTF-8",
data:JSON.stringify(data),
success:function(data){
alert(data.message);
$("#userList").bootstrapTable("refresh");
},
error:function(data){
alert("服务器异常!!");
}
});
}
//修改用户
function editUser(){
var rows = $("#userList").bootstrapTable('getSelections');
if (rows.length<=0 ) {
alert("请选择一条记录!");
return;
}
var row = rows[0];
$("#userId").val(row.id);
$("#userName").val(row.userName);
$("#password").val(row.password);
$("#nickName").val(row.nickName);
$("#age").val(row.age);
if(row.sex == true) {
$("#sex1").attr('checked', 'checked');
} else {
$('#sex2').attr('checked', 'checked');
}
$("#signature").val(row.signature);
$("#addUserModal").modal("show");
}
//查询用户
function queryUser(){
$("#userList").bootstrapTable("refresh");
}
</script>
</body>
</html>
使用bootstrap+bootstrapTable+Ajax开发,注意bootstrap模态框modal的使用。
注意:引入js时,注意js文件的顺序,必须先引入jquery.js。否则会出现$().bootstrapTable不是一个function的错误。
数据库
1、创建数据库mssm;
2、创建表user,建表SQL语句
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`nickname` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
`signature` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
运行效果图
总结
主要使用Mybatis实现数据库的增删查改操作,同时前台使用bootstrap框架开发页面。
码云项目地址http://git.oschina.net/chronosliu/mssm
麻烦关注收藏一下哦!!!