SSM 整合实现 增删改查、PageHelper 实现分页

时间:2022-09-24 17:30:15

一、前言

1、想法

这个SSM(Spring+SpringMVC+MyBatis,基于Maven)实现的 CRUD 测试是之前写的,一直留着想等有空再使用点 BootStrap / EasyUI / ElementUI 对界面(现在纯 HTML)进行优化,却一直没有时间。不过后来想了想,这样代码更加注重后台业务逻辑,更加简单易读。

这里页面虽然使用了 JSP,并没有使用 JSP 的 EL、JSTL 库,全程使用 jQuery 的 Ajax 以 JSON 的数据格式进行交互

后面有时间会实现 vue+ssm 的整合来替代简陋的 JSP 页面,并前后端分离
2、运行环境

①编译器:eclipse
②服务器:Tomcat7
③JDK:1.7
④数据库:MySQL

3、框架、工具

①前端: jQuery
②后台:Spring、SpringMVC、MyBatis、Maven

二、功能介绍

1、jsonlist.jsp 主界面:

相当简单,以后的 CRUD 都在这个页面上

SSM 整合实现 增删改查、PageHelper 实现分页

2、分页功能:

在上述页面中,例如点击>>显示下一页,效果如下:红色框表示变化的地方

SSM 整合实现 增删改查、PageHelper 实现分页

3、编辑功能:

点击上图第一行的编辑,就会显示在下方的编辑区
SSM 整合实现 增删改查、PageHelper 实现分页
修改密码为123后,点击编辑,刷新页面,改变web5为123
SSM 整合实现 增删改查、PageHelper 实现分页

4、删除功能:

点击id=6的一行的删除链接,即刚才修改的那行,id=5就不见了
SSM 整合实现 增删改查、PageHelper 实现分页

5、增加功能:

这里有个细节,就是你输入的用户名是之前就有的话,会提示你的名字不可用
SSM 整合实现 增删改查、PageHelper 实现分页

正确输入后,点击新增
SSM 整合实现 增删改查、PageHelper 实现分页

会自动跳到最后一页,可以看刚刚正确输入的信息
SSM 整合实现 增删改查、PageHelper 实现分页

至此 CRUD 该演示的应都演示完了,下面是实现的代码

三、代码实现

1、代码结构

这里要注意,绿色框中的内容都不是我自己手动编写加入的,是使用 MyBatis 的逆向工程自动生成的,这里也就没有必要列出代码了,同时代码的关键地方都清除注释了,应该没有任何阅读障碍

逆向工程具体使用方法可以去参考之前的文章

MyBatis 使用逆向工程自动生成项目的实体层、dao层

逆向工程使用的文件为红色框中的文件

SSM 整合实现 增删改查、PageHelper 实现分页

2、主界面 jsonlist.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSON</title>
<%
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>Id</th>
<th>Username</th>
<th>Password</th>
<th>Edit</th>
<th>Delete</th>
</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:<property name="reasonable" value="true" />
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 = $('<td></td>').append(user.id);
var userName = $('<td></td>').append(user.username);
var userPassword = $('<td></td>').append(user.password);
//编辑链接、事件
var edi = $('<a></a>').append("编辑").attr("href", "#");
edi.click(function() {
$('#ediname').val(user.username);
$('#ediword').val(user.password);
$('#ediid').val(user.id);
});
var ediTd = $('<td></td>').append(edi);
//删除链接、事件
var del = $('<a></a>').append("删除").attr("href", "#");
del.click(function() {
delUser(user.id);
});
var delTd = $('<td></td>').append(del);
$('<tr></tr>').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 = $('<a></a>').append('首页').attr("href", "#");
first.click(function() {
toPage(1);
});

var last = $('<a></a>').append('末页').attr("href", "#");
last.click(function() {
toPage(result.pages);
});

var up = $('<a></a>').append('《').attr("href", "#");
up.click(function() {
toPage(result.pageNum - 1);
});

var down = $('<a></a>').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 = $('<a></a>').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<User> 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<User> users = userService.getAll();
// 代理结果、连续显示的页数
PageInfo<User> page = new PageInfo<User>(users, 5);
// 保存到Session中
model.addAttribute("pageInfo", page);
// 返回页面
return "list";
}

// 显示所有用户信息
@ResponseBody
@RequestMapping(value = "/jsonusers", method = RequestMethod.GET)
public PageInfo<User> getUsers(@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam(value = "num", defaultValue = "5") Integer num, Model model) {
// 页码、每页的大小
PageHelper.startPage(pn, num);
// 获取结果集
List<User> users = userService.getAll();
// 代理结果、连续显示的页数
PageInfo<User> page = new PageInfo<User>(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<String, String> checkUserName(String userName) {

boolean tap = userService.checkUserName(userName);
Map<String, String> map = new HashMap<String, String>();
if (tap) {
map.put("msg", "you can use it");
} else {
map.put("msg", "you cannot use the name");
}

return (HashMap<String, String>) 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<String> warnings = new ArrayList<String>();
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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<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>

<!-- 指定javaBean生成的位置com.cun.bean -->
<javaModelGenerator targetPackage="com.cun.bean"
targetProject=".\src\main\java">

<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>

<!--指定sql映射文件生成的位置mapper -->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>

<!-- 指定dao接口生成的位置,mapper接口com.cun.dao -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.cun.dao" targetProject=".\src\main\java">

<property name="enableSubPackages" value="true" />
</javaClientGenerator>


<!-- table指定每个表的生成策略 -->
<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.0</modelVersion>
<groupId>com.cun.ssmtest</groupId>
<artifactId>spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<!--引入项目依赖的jar包 -->
<!-- SpringMVC、Spring -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependencies>
<!--引入pageHelper分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<!-- MBG -->
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- 返回json字符串的支持 -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<!--JSR303数据校验支持;tomcat7及以上的服务器, tomcat7以下的服务器:el表达式。额外给服务器的lib包中替换新的标准的el -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!-- Spring-Jdbc -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!--Spring-test -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring面向切面编程 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!--MyBatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- MyBatis整合Spring的适配包 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 数据库连接池、驱动 -->
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<!-- (jstl,servlet-api,junit) -->
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<!-- 之所以这个有这样的设置,是因为在服务器上有,在开发过程中没有 -->
<scope>provided</scope>
</dependency>
<!-- junit -->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>

</project>

7、sping 的配置 applicationContext.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: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>
<!-- Spring的配置文件,这里主要配置和业务逻辑有关的 -->
<!--=================== 数据源,事务控制,xxx ================ -->
<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>
<!--================== 配置和MyBatis的整合=============== -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定mybatis全局配置文件的位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="dataSource" ref="pooledDataSource"></property>
<!-- 指定mybatis,mapper文件的位置 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描所有dao接口的实现,加入到ioc容器中 -->
<property name="basePackage" value="com.cun.dao"></property>
</bean>

<!-- 配置一个可以执行批量的sqlSession -->
<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>
<!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式) -->
<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="*" />
<!--以get开始的所有方法 -->
<tx:method name="get*" read-only="true" />
</tx:attributes>
</tx:advice>

<!-- Spring配置文件的核心点(数据源、与mybatis的整合,事务控制) -->

</beans>

SSM 整合实现 增删改查、PageHelper 实现分页
8、SpringMVC 配置 dispatcherServlet-servlet.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: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"
>


<!--SpringMVC的配置文件,包含网站跳转逻辑的控制,配置 -->
<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>

<!--两个标准配置 -->
<!-- 将springmvc不能处理的请求交给tomcat -->
<mvc:default-servlet-handler />
<!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax...映射动态请求 -->
<mvc:annotation-driven />

</beans>

9、web.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<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">


<!--1、启动Spring的容器 -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!--2、springmvc的前端控制器,拦截所有请求 -->
<!-- The front controller of this Spring Web application, responsible for
handling all application requests -->

<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 默认找 /WEB-INF/[servlet的名称]-servlet.xml -->
<!-- <init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:dispatcherServlet-servlet.xml</param-value>
</init-param> -->


<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 3、字符编码过滤器,一定要放在所有过滤器之前 -->
<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>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 4、使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>HttpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>

</web-app>

四、小结

优化:

1、本次 CRUD 后端使用了目前流行的ssm框架等之后,编写起来是很快的,不过原因之一也是本测试过于简单了,仅仅是单表的 CRUD ,如果涉及多表的 CRUD 就要自己的去修改 DAO、Bean 层了,

2、本次 CRUD 的界面实在是太简陋了,急需优化

3、本次 CURD 前端处理 JSON,并没有使用目前留下的 MVVM 模式的框架如 Vue,而是大量使用 jQuery 的 Ajax 方法,基于 DOM 的操作实在是太繁杂了,有需改善。