Maven+Spring+SpringMVC+Hibernate+Mysql的簡單整合(入門級),實現數據庫的增刪查改。Maven管理項目,統一開發規範和工具、統一管理Jar包。Spring輕量級的Java開發框架、控制反轉IOC和依賴注入DI來管理對象依賴關係.、面向切面編程AOP來管理事物等。SpringMVC輕量級Web框架,使用MVC架構思想對web層進行解耦,簡化開發。Mybatis半自動ORM(對象關係映射)框架,是支持定製化 SQL、存儲過程以及高級映射的優秀的持久層框架。Mysql關係型數據庫。javascript
前端使用Bootstrap 框架,用於開發響應式佈局,界面風格簡潔美觀。css
<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。html
##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
<?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> <!--一、 註解方式配置事務 --> <!-- <tx:annotation-driven transaction-manager="transactionManager"/> --> <!--二、 攔截方式配置事務 --> <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層使用。前端
<?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返回支持解決先後臺交互出現問題。java
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); } }
註解解釋:mysql
application/x-www-form-urlencoded
編碼的內容,例如application/json, application/xml等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; } }
<?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>
<%@ 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的使用。jquery
注意:引入js時,注意js文件的順序,必須先引入jquery.js。不然會出現$().bootstrapTable不是一個function的錯誤。git
一、建立數據庫mssm;github
二、建立表user,建表SQL語句web
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 麻煩關注收藏一下哦!!!