最近在学ssm框架和一个前端EasyUI,就整合一下做了一个图书的增删改查的一个小项目,下面就是代码
项目的目录结构

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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">
<display-name>SSM_EasyUI</display-name>
<!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置springmvc -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解决post乱码 -->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
config.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 自定义别名 -->
<typeAliases>
<!-- 批量定义别名:指定包名,mybatis自动扫描包中pojo类,自定义别名,别名就类名(首字母大写或小写) -->
<package name="com.qhit.pojo"/>
</typeAliases>
<!-- 定义映射器 -->
<mappers>
<!-- 批量加载mapper -->
<!-- 指定mapper接口的包名,mybatis自动扫描包下边的所有mapper接口进行加载 -->
<package name="com.qhit.mapper"/>
</mappers>
</configuration>
springmvc.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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 使用组件扫描业务包 -->
<context:component-scan base-package="com.qhit.controller,com.qhit.service,com.qhit.mapper"/>
<!-- 自动加载装配 -->
<mvc:annotation-driven/>
<!-- 配置静态资源访问 -->
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:default-servlet-handler/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
database.properties配置
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.password=123456
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd ">
<!-- 加载数据库配置 localtion属性的值数据库连接的属性文件 classpath:代表编译后的跟目录 -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- mapper配置,让spring管理sqlSessionFactory使用mybatis和spring整合的包中 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:config.xml" />
</bean>
<!-- 配置mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qhit.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
主界面
jsp页面
index.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=UTF-8">
<title>EasyUI for SSM</title>
<link rel="stylesheet" href="./jquery-easyui-1.3.3/themes/icon.css">
<link rel="stylesheet"
href="./jquery-easyui-1.3.3/themes/default/easyui.css">
<script type="text/javascript" src="./jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript"
src="./jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript"
src="./jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
</head>
<body class="easyui-layout">
<div region="north" split="true" style="height: 160px;">
<img src="Logo.png" style="height: 150px;width: 850px;">
</div>
<div region="center">
<div id="MenusTabs" class="easyui-tabs" fit="true" border="false">
<div title="首页">
<div align="center" style="padding-top: 100px;">
<font color="red" size="15">
Welcome ! Enjoy To Use EasyUI!
</font><br/>
<font color="red" size="15">
欢迎 ! 享受 EasyUI!~
</font>
</div>
</div>
</div>
</div>
<div region="west" split="true" title="导航菜单" style="width:150px;">
<ul id="TreeMenus"></ul>
</div>
<div region="south" split="true" style="background-color:gray;height:100px;line-height:80px;"align="center">版权所有 Copy Right</div>
<script type="text/javascript" src="./js/MyEasyUICRUD.js"></script>
</body>
</html>
data.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=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="./jquery-easyui-1.3.3/themes/icon.css">
<link rel="stylesheet"
href="./jquery-easyui-1.3.3/themes/default/easyui.css">
<script type="text/javascript" src="./jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript"
src="./jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript"
src="./jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>
<table id="data" title="信息" class="easyui-datagrid"
url="list" toolbar="#ToolBar" pagination="true"
fitColumns="true" fit="true" rownumbers="true">
<thead>
<tr>
<th field="cb" checkbox="true"></th>
<th field="bid" width="100px">编号</th>
<th field="bname" width="100px">名字</th>
<th field="author" width="100px">作者</th>
<th field="buytime" width="100px">购买时间</th>
<th field="sname" width="100px">类别</th>
</tr>
</thead>
</table>
<div id="ToolBar">
<div style="height: 40px;">
<a href="javascript:Add()" class="easyui-linkbutton"
iconCls="icon-add" plain="true">添加</a> <a
href="javascript:ModifyBySelect()" class="easyui-linkbutton"
iconCls="icon-edit" plain="true">修改</a> <a
href="javascript:DeleteByFruitName()" class="easyui-linkbutton"
iconCls="icon-remove" plain="true">删除</a>
</div>
</div>
<div id="AddDialog" class="easyui-dialog" buttons="#AddDialogButtons"
style="width: 280px; height: 250px; padding: 10px 20px;" closed="true">
<form id="ModiyDialogForm" method="post">
<table>
<tr>
<td>名字:</td>
<td><input type="text" class="easyui-validatebox" required
name="bname" id="bname" /></td>
</tr>
<tr>
<td>作者:</td>
<td><input type="text" name="author" id="author" /></td>
</tr>
<tr>
<td>购买时间:</td>
<td><input type="text" name="buytime" id="buytime" class="easyui-datebox"></td>
</tr>
<tr>
<td>类别:</td>
<td>
<select name="sid" id="sid">
<option value="1">计算机/软件</option>
<option value="2">小说/文摘</option>
<option value="3">随笔</option>
</select>
</td>
</tr>
</table>
</form>
</div>
<div id="AddDialogButtons">
<a href="javascript:SaveDialog()" class="easyui-linkbutton"
iconCls="icon-ok">保存</a> <a href="javascript:CloseDialog()"
class="easyui-linkbutton" iconCls="icon-cancel">取消</a>
</div>
<script type="text/javascript" src="./js/MyEasyUICRUD.js"></script>
</body>
</html>
MyEasyUICRUD.js文件
var url;
function ResetValues(){
$("#bname").val('');
$("#author").val('');
$("#buytime").val('');
$("#sname").val('');
}
function SaveDialog(){
$("#ModiyDialogForm").form('submit',{
url:url,
onSubmit:function(){
return $(this).form('validate');
},
success:function(result){
if( result.errorMsg ){
$.messager.alert("系统提示",result.errorMsg);
return;
}
else{
$.messager.alert("系统提示","保存成功");
ResetValues();
$("#AddDialog").dialog('close');
$("#data").datagrid('reload');
}
}
});
ResetValues();
}
function CloseDialog(){
ResetValues();
$("#AddDialog").dialog('close');
}
function Add(){
$("#AddDialog").dialog('open').dialog('setTitle',"添加数据");
url = "save";
}
function ModifyBySelect(){
var SelectRows = $("#data").datagrid('getSelections');
if( 1 != SelectRows.length ){
$.messager.alert("系统提示", "请选择一行要编辑的数据");
return;
}
var SelectRow = SelectRows[0];
$("#AddDialog").dialog('open').dialog('setTitle',"编辑数据");
$("#ModiyDialogForm").form('load',SelectRow);
url = "save?bid="+SelectRow.bid;
}
function DeleteByFruitName(){
var SelectRows = $("#data").datagrid('getSelections');
if( 0 == SelectRows.length ){
$.messager.alert("系统提示", "请选择要删除的数据");
return;
}
var SelectIndexArr = [];
for( var i = 0 ; i < SelectRows.length; i++ ){
SelectIndexArr.push(SelectRows[i].bid);
}
var SelectIndexToString = SelectIndexArr.join(",");
$.messager.confirm("系统提示", "你确定要删除<font color=red> " + SelectRows.length + " </font>条数据吗?", function(xo){
if( xo ){
$("#data").datagrid('reload');
$.post("delete",{DeleteIndexArr:SelectIndexToString},function(result){
if( result.success ){
$.messager.alert("系统提示", "你已成功删除 <font color=green> " + result.DeleteCounts + " </font>条数据!~");
$("#data").datagrid('reload');
}
else{
$.messager.alert("系统提示", "<font color=red>删除失败</font>");
}
},"json");
}
});
}
function OpenTab(Text,URL){
if( $("#MenusTabs").tabs('exists', Text) ){
$("#MenusTabs").tabs('select', Text);
}
else{
var Content = "<iframe frameborder='0' scrolling='auto' style='width:100%;height:100%' src=" + URL + "></iframe>";
$("#MenusTabs").tabs('add',{
title:Text,
closable:true,
content:Content
});
}
}
(function(){
var TreeMenusDatas=[{
text:"图书馆图书系统",
children:[{
text:"小说图书信息",
attributes:{
url:"data.jsp"
}
}]
}];
$("#TreeMenus").tree({
data:TreeMenusDatas,
lines:true,
onClick:function(node){
if( node.attributes ){
OpenTab( node.text, node.attributes.url );
}
}
});
})();
接下来看看代码目录结构

package com.qhit.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.qhit.pojo.BookSort;
import com.qhit.pojo.Books;
import com.qhit.pojo.PageBean;
import com.qhit.service.UserService;
import com.qhit.tools.ResponseUtil;
@Controller
public class UserController {
@Autowired
private UserService userService;
/**
* 图书分页查询
* @param page
* @param rows
* @param books
* @param response
* @return
*/
@RequestMapping("/list")
public String list(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,Books books,HttpServletResponse response){
PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
Map<String, Object> map = new HashMap<String, Object>();
map.put("start", pageBean.getStart());
map.put("size", pageBean.getPageSize());
List<BookSort> bookList = userService.getBooksByPage(map);
System.out.println(bookList.get(0).getSname());
int total = userService.getTotal(map);
System.out.println("start:"+pageBean.getStart()+",size:"+pageBean.getPageSize());
System.out.println("total:"+total);
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = JSONArray.fromObject(bookList);
jsonObject.put("rows", jsonArray);
jsonObject.put("total", total);
ResponseUtil.Write(response, jsonObject);
return null;
}
/**
* 图书添加或者修改
* @param books
* @param response
* @return
*/
@RequestMapping("/save")
public String save(Books books,HttpServletResponse response){
System.out.println(books.getBid());
System.out.println(books.getBname());
System.out.println(books.getAuthor());
System.out.println(books.getBuytime());
int resultTotal = 0;
if(books.getBid() == null){
resultTotal = userService.addBooks(books);
}else{
resultTotal = userService.updateBooks(books);
}
JSONObject jsonObject = new JSONObject();
if(resultTotal>0){
jsonObject.put("success", "true");
}else{
jsonObject.put("errorMsg", "添加失败");
}
ResponseUtil.Write(response, jsonObject);
return null;
}
/**
* 图书删除
* @param DeleteIndexArr
* @param response
* @return
*/
@RequestMapping("/delete")
public String delete(@RequestParam(value="DeleteIndexArr")String DeleteIndexArr,HttpServletResponse response){
int deleteFruit = 0;
String[] ids = DeleteIndexArr.split(",");
JSONObject jsonObject = new JSONObject();
for(String id:ids){
deleteFruit = userService.deleteBooks(Integer.parseInt(id));
}
jsonObject.put("success", "true");
jsonObject.put("DeleteCounts", deleteFruit);
ResponseUtil.Write(response, jsonObject);
return null;
}
}
package com.qhit.service;
import java.util.List;
import java.util.Map;
import com.qhit.pojo.BookSort;
import com.qhit.pojo.Books;
public interface UserService {
//查询
public List<BookSort> getBooksByPage(Map<String, Object> map);
//获取总条数
public int getTotal(Map<String, Object> map);
//添加
public int addBooks(Books books);
//修改
public int updateBooks(Books books);
//删除
public int deleteBooks(int bid);
}
UserServiceImpl
package com.qhit.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qhit.mapper.UserMapper;
import com.qhit.pojo.BookSort;
import com.qhit.pojo.Books;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public List<BookSort> getBooksByPage(Map<String, Object> map) {
// TODO Auto-generated method stub
return userMapper.getBooksByPage(map);
}
@Override
public int getTotal(Map<String, Object> map) {
// TODO Auto-generated method stub
return userMapper.getTotal(map);
}
@Override
public int addBooks(Books books) {
// TODO Auto-generated method stub
return userMapper.addBooks(books);
}
@Override
public int updateBooks(Books books) {
// TODO Auto-generated method stub
return userMapper.updateBooks(books);
}
@Override
public int deleteBooks(int bid) {
// TODO Auto-generated method stub
return userMapper.deleteBooks(bid);
}
}
PageBean 分页工具类
package com.qhit.pojo;
public class PageBean {
private int page;//第几页
private int pageSize;//每页记录数
private int start;//起始页
public PageBean(int page,int pageSize){
this.page = page;
this.pageSize = pageSize;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getStart() {
return (page-1)*pageSize;
}
}
Books 图书实体类
package com.qhit.pojo;
public class Books {
private Integer bid;//编号
private String bname;//名字
private String author;//作者
private String buytime;//购买时间
private Integer sid;//分类外键
public Books() {
super();
}
public Integer getBid() {
return bid;
}
public void setBid(Integer bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBuytime() {
return buytime;
}
public void setBuytime(String buytime) {
this.buytime = buytime;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
}
Sort 类别表
package com.qhit.pojo;
public class Sort {
private Integer sid;//编号
private String sname;//分类
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}
BookSort
package com.qhit.pojo;
public class BookSort extends Books{
private Integer sid;
private String sname;
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}
ResponseUtil工具类,主要用于返回json数据:
package com.qhit.tools;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class ResponseUtil {
public static void Write(HttpServletResponse response,JSONObject object){
try {
PrintWriter printWriter;
response.setContentType("text/html;charset=utf-8");
printWriter = response.getWriter();
printWriter.println(object.toString());
printWriter.flush();
printWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
StringUtil,字符串工具类:
package com.qhit.tools;
public class StringUtil {
public static boolean isEmpty(String str){
if("".equals(str) || str == null){
return true;
}else{
return false;
}
}
public static boolean isNotEmpty(String str){
if(!"".equals(str) && str!=null){
return true;
}
return false;
}
public static String formatLike(String str){
if(isNotEmpty(str)){
return "%"+str+"%";
}else{
return null;
}
}
}
UserMapper
package com.qhit.mapper;
import java.util.List;
import java.util.Map;
import com.qhit.pojo.BookSort;
import com.qhit.pojo.Books;
public interface UserMapper {
//分页查询
public List<BookSort> getBooksByPage(Map<String, Object> map);
//查询总条数
public int getTotal(Map<String, Object> map);
//添加
public int addBooks(Books books);
//修改
public int updateBooks(Books books);
//删除
public int deleteBooks(int bid);
}
UserMapper.xml mybatis的动态sql语句<?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.qhit.mapper.UserMapper">
<!-- 分页查询 -->
<select id="getBooksByPage" parameterType="map" resultType="BookSort">
select b.*,s.sname from books b,sort s where b.sid=s.sid limit ${start},${size}
</select>
<!-- 查询总条数 -->
<select id="getTotal" parameterType="map" resultType="int">
select count(*) from books
</select>
<!-- 添加 -->
<insert id="addBooks" parameterType="books">
insert into books(bname,author,buytime,sid) values(#{bname},#{author},#{buytime},#{sid})
</insert>
<!-- 修改 -->
<update id="updateBooks" parameterType="books">
update books set bname = #{bname},author = #{author},buytime = #{buytime},sid = #{sid} where bid = #{bid}
</update>
<!-- 删除 -->
<delete id="deleteBooks" parameterType="int">
delete from books where bid = #{bid}
</delete>
</mapper>
mysql数据库结构


运行截图


