这个SSM(Spring+SpringMVC+MyBatis,基于Maven)实现的 CRUD 测试是之前写的,一直留着想等有空再使用点 BootStrap / EasyUI / ElementUI 对界面(现在纯 HTML)进行优化,却一直没有时间。不过后来想了想,这样代码更加注重后台业务逻辑,更加简单易读。
这里页面虽然使用了 JSP,并没有使用 JSP 的 EL、JSTL 库,全程使用 jQuery 的 Ajax 以 JSON 的数据格式进行交互
后面有时间会实现 vue+ssm 的整合来替代简陋的 JSP 页面,并前后端分离
①编译器:eclipse
②服务器:Tomcat7
③JDK:1.7
④数据库:MySQL
①前端: jQuery
②后台:Spring、SpringMVC、MyBatis、Maven
相当简单,以后的 CRUD 都在这个页面上
在上述页面中,例如点击>>显示下一页,效果如下:红色框表示变化的地方
点击上图第一行的编辑,就会显示在下方的编辑区
修改密码为123后,点击编辑,刷新页面,改变web5为123
点击id=6的一行的删除链接,即刚才修改的那行,id=6就不见了
这里有个细节,就是你输入的用户名是之前就有的话,会提示你的名字不可用
至此 CRUD 该演示的应都演示完了,下面是实现的代码
这里要注意,绿色框中的内容都不是我自己手动编写加入的,是使用 MyBatis 的逆向工程自动生成的,这里也就没有必要列出代码了,同时代码的关键地方都清除注释了,应该没有任何阅读障碍
逆向工程具体使用方法可以去参考之前的文章
MyBatis 使用逆向工程自动生成项目的实体层、dao层
逆向工程使用的文件为红色框中的文件
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSONtitle>
<%
pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<script type="text/javascript"
src="${APP_PATH }/static/js/jquery-1.12.4.min.js">script>
<link
href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
rel="stylesheet">
<script
src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js">script>
head>
<style type="text/css">
table{
border-collapse: collapse;
}
a{text-decoration:none}
style>
<body>
<h2>Ajax 纯天然无污染h2>
<table border="1" width="40%" align="center" >
<tr>
<th>Idth>
<th>Usernameth>
<th>Passwordth>
<th>Editth>
<th>Deleteth>
tr>
<tbody id="tableBody">tbody>
table>
<div>
<h4 id="pageShow">h4>
div>
<h4>连续显示的页码h4>
<div id="choose">div>
<hr>
用户名:
<input type="text" id="username"> 密码:
<input type="text" id="password">
<button id="add">新增button>
<div id="message">div>
<hr>
id:
<input type="text" id="ediid" disabled="true">
用户名:
<input type="text" id="ediname" disabled="true">
密码:
<input type="text" id="ediword" >
<button id="edi">编辑button>
<script type="text/javascript">
//注意是 change函数,这也是即时反馈的原因
$('#username').change(function() {
var un = $('#username').val();
$.ajax({
url : "${APP_PATH}/checkuser",//注意里边还可以嵌套$
type : "POST",
data : "userName=" + un,
//data : userName=un,注意是字符串
success : function(result) {
$('#message').empty();
$('#message').append(result.msg);
}
});
})
//点击增加按钮的事件
$('#add').click(function() {
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url : "${APP_PATH}/jsonusers",
type : "POST",
data : "password=" + password + "&username=" + username,//注意格式
//data:$("form").serialize(),这种写法在表单足够复杂是有优势的,目前还存在问题
success : function(result) {
//利用插件设置的合理性,直接暴力到最后一页
//mybatis-config.xml:
toPage(999);
}
});
});
$('#edi').click(function(){
var ediid=$('#ediid').val();
var ediname=$('#ediname').val();
var ediword=$('#ediword').val();
$.ajax({
url:"${APP_PATH}/ediUser",
type:"POST",
data:"id="+ediid+"&username="+ediname+"&password="+ediword,
success:function(result){
alert("修改成功");
}
});
});
//每次打开本页面的时候,先前往第一页
$(function() {
toPage(1);
});
//指定前往页
function toPage(pn) {
$.ajax({
url : "${APP_PATH}/jsonusers",
type : "GET",
data : "pn=" + pn,
success : function(result) {
//下面的的函数都是append标签进去的,每次先情况之前的
$('#tableBody').empty();
$('#pageShow').empty();
$('#choose').empty();
show(result);
page(result);
choice(result);
}
});
}
//删除链接绑定事件
function delUser(id) {
$.ajax({
url : "${APP_PATH}/deluser",
type : "POST",
data : "id=" + id,
success : function(result) {
/*缺点与优化:
①需要再次刷新页面,才能使已经删除的用户消失
②type在restful风格下应为DELETE
*/
}
});
}
//显示表格数据
function show(result) {
var users = result.list;
$.each(users, function(index, user) {
var userId = $(' ').append(user.id);
var userName = $(' ').append(user.username);
var userPassword = $(' ').append(user.password);
//编辑链接、事件
var edi = $('').append("编辑").attr("href", "#");
edi.click(function() {
$('#ediname').val(user.username);
$('#ediword').val(user.password);
$('#ediid').val(user.id);
});
var ediTd = $(' ').append(edi);
//删除链接、事件
var del = $('').append("删除").attr("href", "#");
del.click(function() {
delUser(user.id);
});
var delTd = $(' ').append(del);
$(' ').append(userId).append(userName).append(
userPassword).append(ediTd).append(delTd).appendTo(
'#tableBody');
});
}
//显示页码信息
function page(result) {
var pageInfo = result;
$('#pageShow').append(
'当前页码:' + pageInfo.pageNum + '/总页码' + pageInfo.pages
+ '/总记录数' + pageInfo.total);
}
//页码导航条
function choice(result) {
var first = $('').append('首页').attr("href", "#");
first.click(function() {
toPage(1);
});
var last = $('').append('末页').attr("href", "#");
last.click(function() {
toPage(result.pages);
});
var up = $('').append('《').attr("href", "#");
up.click(function() {
toPage(result.pageNum - 1);
});
var down = $('').append('》').attr("href", "#");
down.click(function() {
toPage(result.pageNum + 1);
});
$('#choose').append(first);
if (result.hasPreviousPage == true) {
$('#choose').append(up);
}
//下面这一步不能省略,直接放下去会报错!!!
var navigatepageNums = result.navigatepageNums;
$.each(navigatepageNums, function(index, pageIndex) {
var pageA = $('').append(pageIndex + " ").attr("href",
"#");
//绑定点击事件,由于是遍历,实际上有很多个
pageA.click(function() {
toPage(pageIndex);
});
$('#choose').append(pageA);
});
if (result.hasNextPage == true) {
$('#choose').append(down);
}
$('#choose').append(last);
}
script>
body>
html>
2、服务层 UserService.java
package com.cun.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cun.bean.User;
import com.cun.bean.UserExample;
import com.cun.dao.UserMapper;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
// 获取所有的用户
public List getAll() {
return userMapper.selectByExample(null);
}
// 新增用户
public void addUser(User user) {
userMapper.insertSelective(user);
}
//检验用户名是否重复
public boolean checkUserName(String username) {
UserExample userExample = new UserExample();
userExample.createCriteria().andUsernameEqualTo(username);
long countByExample = userMapper.countByExample(userExample);
if (countByExample == 0) {
return true;
} else {
return false;
}
}
//查询用户
public User getUser(Integer id) {
return userMapper.selectByPrimaryKey(id);
}
//删除用户
public void delUser(Integer id) {
userMapper.deleteByPrimaryKey(id);
}
//更新用户
public void ediUser(User user) {
userMapper.updateByPrimaryKey(user);
}
}
3、控制层 UserController.java
package com.cun.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cun.bean.User;
import com.cun.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Controller
public class UserController {
@Autowired
UserService userService;
// 定位页码请求处理
@RequestMapping("/users")
// defaultValue在简陋的jsp测试页面无法点击赋值时,发挥作用
public String getUsers0(@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam(value = "num", defaultValue = "5") Integer num, Model model) {
// 页码、每页的大小
PageHelper.startPage(pn, num);
// 获取结果集
List users = userService.getAll();
// 代理结果、连续显示的页数
PageInfo page = new PageInfo(users, 5);
// 保存到Session中
model.addAttribute("pageInfo", page);
// 返回页面
return "list";
}
// 显示所有用户信息
@ResponseBody
@RequestMapping(value = "/jsonusers", method = RequestMethod.GET)
public PageInfo getUsers(@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam(value = "num", defaultValue = "5") Integer num, Model model) {
// 页码、每页的大小
PageHelper.startPage(pn, num);
// 获取结果集
List users = userService.getAll();
// 代理结果、连续显示的页数
PageInfo page = new PageInfo(users, 5);
// 上面是把page存到Session中,这里是直接返回json字符串
return page;
}
// 添加用户
@ResponseBody
@RequestMapping(value = "/jsonusers", method = RequestMethod.POST)
// data : "password="+password+"&username="+username 居然可以用一个user接受两个数据,太智能了
public void addUser(User user) {
// 保存数据到数据库
userService.addUser(user);
}
// 查一个用户
@ResponseBody
@RequestMapping(value = "/getuser/{id}", method = RequestMethod.GET)
public User getUser(Integer id) {
return userService.getUser(id);
}
// 检查用户名是否可用
@ResponseBody
@RequestMapping(value = "/checkuser", method = RequestMethod.POST)
public HashMap checkUserName(String userName) {
boolean tap = userService.checkUserName(userName);
Map map = new HashMap();
if (tap) {
map.put("msg", "you can use it");
} else {
map.put("msg", "you cannot use the name");
}
return (HashMap) map;
}
// 删除用户 method = RequestMethod.POST,用DELETE则无法做到
@RequestMapping(value = "/deluser",method = RequestMethod.POST)
public void delUsers(User user) {
System.out.println("要删除的用户id="+user.getId());
userService.delUser(user.getId());
}
@RequestMapping(value="/ediUser",method=RequestMethod.POST)
public void ediUser(User user) {
System.out.println(user);
userService.ediUser(user);
}
}
4、逆向工程生成文件 MBGTest.java
package com.cun.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class MBGTest {
public static void main(String[] args) throws Exception {
List warnings = new ArrayList();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
}
5、逆向工程配置文件 mbg.xml
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"
password="123">
jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
javaTypeResolver>
<javaModelGenerator targetPackage="com.cun.bean"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
javaModelGenerator>
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.cun.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
javaClientGenerator>
<table tableName="user" domainObjectName="User">table>
context>
generatorConfiguration>
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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.cun.ssmtestgroupId>
<artifactId>springartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>warpackaging>
<dependencies>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.0.0version>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.5version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.8.8version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-validatorartifactId>
<version>5.4.1.Finalversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.41version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
project>
7、sping 的配置 applicationContext.xml
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.cun">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
context:component-scan>
<context:property-placeholder location="classpath:dbconfig.properties" />
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}">property>
<property name="driverClass" value="${jdbc.driverClass}">property>
<property name="user" value="${jdbc.user}">property>
<property name="password" value="${jdbc.password}">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml">property>
<property name="dataSource" ref="pooledDataSource">property>
<property name="mapperLocations" value="classpath:mapper/*.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cun.dao">property>
bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory">constructor-arg>
<constructor-arg name="executorType" value="BATCH">constructor-arg>
bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="pooledDataSource">property>
bean>
<aop:config>
<aop:pointcut expression="execution(* com.cun.service..*(..))"
id="txPoint" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint" />
aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" />
<tx:method name="get*" read-only="true" />
tx:attributes>
tx:advice>
beans>
8、SpringMVC 配置 dispatcherServlet-servlet.xml
<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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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-4.3.xsd">
<context:component-scan base-package="com.cun"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
context:component-scan>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
beans>
9、web.xml 配置
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>HttpPutFormContentFilterfilter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<welcome-file-list>
<welcome-file>/index.jspwelcome-file>
welcome-file-list>
web-app>
优化:
1、本次 CRUD 后端使用了目前流行的ssm框架等之后,编写起来是很快的,不过原因之一也是本测试过于简单了,仅仅是单表的 CRUD ,如果涉及多表的 CRUD 就要自己的去修改 DAO、Bean 层了,
2、本次 CRUD 的界面实在是太简陋了,急需优化
3、本次 CURD 前端处理 JSON,并没有使用目前流行的 MVVM 模式的框架如 Vue,而是大量使用 jQuery 的 Ajax 方法,基于 DOM 的操作实在是太繁杂了,有需改善。
4、2018.2.28:
增加了点 BootStrap样式,算是 2.0版本,代码就不更新了
5、2018.8.5:
分页手动写也是可以的,曾经做一个学校的学生宿舍管理系统,分页用的就是如下的方法,page、size 传入 mybaits 的 mapper.xml 中的 sql 即可,并不复杂:
MySql实现分页查询的SQL,mysql实现分页查询的sql语句 (转)