【MyBatis】MyBatis+SpringMVC+EasyUI整合分页

一、介绍

环境:MyBatis 3.0.x+Spring 3.0.x+EasyUI

采用SpringMVC+MyBatis框架整合的分页Demo,用的是首页这个:http://www.jeasyui.com/demo/main/index.php

Demo结构如下:

再看一下效果:

二、项目详解:

前提是首先把所有的jar包导入进入,不管是用Maven或者手动都可以。

1、首先建立javabean,User.java:

package com.bee.po;

public class User {
	private int id;
	private String name;
	private String password;
	private String sex;
	private int age;
	private String address;

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				+ ", sex=" + sex + ", age=" + age + ", address=" + address
				+ "]";
	}
	//省略setter和getter方法
}

顺带着把数据库也建立了

2、然后建立dao层接口类,UserMapper以及UserMapper.xml(因为MyBatis是接口编程,只需要实现mapper而不用实现dao接口)

UserMapper.java:

package com.bee.dao;
import java.util.List;
import com.bee.po.User;

public interface UserMapper {
	/**
	 * 通过姓名查找用户
	 * @param name 用户名
	 * @return 返回用户对象
	 */
	public User findUserByName(String name);

	/**
	 * 查询所有用户,显示列表
	 */
	public List<User> findUsersList();
	/**
	 * 根据页数和记录数,返回记录
	 */
	public List<User> findUsersListByPage(int start,int end);
	/**
	 * 添加用户
	 */
	public void addUser(User user);
	/**
	 * 修改用户
	 */
	public void updateUser(User user);
	/**
	 * 根据ID删除用户
	 */
	public void deleteUser(int id);
	/**
	 * 插入学生自动生成主键
	 */
	public 	String createStudentAutoKey(User user);

}

根据UserMapper接口,我们可以写出映射文件UserMapper.xml(直接写在Dao层了,这样写不是太好):

<?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.bee.dao.UserMapper">
	<!-- 用户列表List -->
	<resultMap type="User" id="resultListUser">
		<id column="id" property="id" />
		<result column="name" property="name" />
		<result column="password" property="password" />
		<result column="sex" property="sex" />
		<result column="address" property="address" />
	</resultMap>

	<!-- 通过名称查找 -->
	<select id="findUserByName" parameterType="String" resultType="User">
		select *
		from user where name=#{name}
	</select>

	<!-- 查找用户列表 -->
	<select id="findUsersList" resultMap="resultListUser">
		select * from user
	</select>
	<!-- 根据页数和记录数返回查找记录 -->
	<select id="findUsersListByPage"  resultMap="resultListUser">
		select * from user limit #{0},#{1}
	</select>

	<!-- 添加用户 -->
	<insert id="addUser" parameterType="User" useGeneratedKeys="true"
		keyProperty="id">
		insert into user(name,password,sex,age,address)
			values(#{name},#{password},#{sex},#{age},#{address})
	</insert>

	<!-- 更新用户 -->
	<update id="updateUser" parameterType="User">
		update user set
		<if test="name != null">
			name=#{name},
		</if>
		<if test="password != null">
			password=#{password},
		</if>
		<if test="sex != null">
			sex=#{sex},
		</if>
		<if test="age != null">
			age=#{age},
		</if>
		<if test="address != null">
			address=#{address}
		</if>
		where id=#{id}
	</update>

	<!-- 删除用户 -->
	<delete id="deleteUser" parameterType="int">
		delete from user where id=#{id}
	</delete>

	<!-- 插入学生,自动生成主键 -->
	<insert id="createStudentAutoKey" parameterType="User" keyProperty="id">
		<selectKey keyProperty="id" resultType="String" order="BEFORE">
			select user
		</selectKey>
		insert into user(id,name,password,sex,age,address)
		values(#{id},#{name},#{password},#{sex},#{age},#{address})
	</insert>
</mapper>

接着配置MyBatis的配置文件:Configuration.xml直接写在src根下边了:

<?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>
		<!-- 给实体类起别名 -->
		<typeAlias type="com.bee.po.User" alias="User"/>
	</typeAliases>

	<!--装载Mapper -->
	<mappers>
		<mapper resource="com/bee/dao/UserMapper.xml" />
	</mappers>
</configuration>

MyBatis基本上已经配置结束

下边就是要把所有的资源添加到Spring容器中,在src根下配置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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=GBK"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
		<property name="defaultAutoCommit" value="true"></property>
	</bean>

	<!-- 配置SqlSessionFactory,注入数据源 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:configuration.xml" />
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 配置Mapper,注入sqlSessionFactory -->
	<bean id="userMapper" class="org.mybatis.spring.MapperFactoryBean">
		<property name="mapperInterface" value="com.bee.dao.UserMapper"></property>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>

	<!-- 配置Service -->
	<bean id="userService" class="com.bee.service.impl.UserServiceImpl">
		<property name="userMapper" ref="userMapper"></property>
	</bean>

</beans>

写一个测试类,检查下看有没有问题:

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) applicationContext.getBean("userService");

		User user = userService.findUserByName("admin");
		System.out.println(user.getAddress());

OK,没问题之后就开始配置web端了,首先配置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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>NewTestLogin</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- Spring核心容器 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 监听器,自动装配ApplicationContext配置信息 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 设置拦截器,拦截.html类型的请求,并初始化SpringMVC容器 -->
  <servlet>
  	<servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      	<param-name>contextConfigLocation</param-name>
      	<param-value>classpath:applicationContext-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <!-- 增加了一个filter,设定UTF8,防止中文乱码 -->
  	<filter>
  		<filter-name>Set Character Encoding</filter-name>
  		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  		<init-param>
  			<param-name>encoding</param-name>
  			<param-value>utf8</param-value>
  		</init-param>
  	</filter>
 	<filter-mapping>
  		<filter-name>Set Character Encoding</filter-name>
  		<url-pattern>/*</url-pattern>
 	</filter-mapping>
</web-app>

配置applicationContext-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"
		xsi:schemaLocation="
			http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
			http://www.springframework.org/schema/context
			http://www.springframework.org/schema/context/spring-context-3.0.xsd
			http://www.springframework.org/schema/mvc
			http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
	<!-- 开启包自动扫描 -->
	<context:component-scan base-package="com.bee.action" />
	<!-- 开启注解支持 -->
	<mvc:annotation-driven />
	<!-- 配置viewResolver -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

配置UserLoginAction.java:

package com.bee.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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 com.bee.dao.UserMapper;
import com.bee.po.User;

@Controller
@RequestMapping("/user")
public class UserLoginAction extends BaseAction{
	@Autowired
	private UserMapper userMapper;
	/**
	 * 登录模块
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/login")
	public String userLogin(HttpServletRequest request,Model model){
		//获得前台传入数据
		String name = request.getParameter("username");
		String password = request.getParameter("password");
		String securityCode = request.getParameter("securityCode");

		System.out.println("得到登录信息:"+name+" "+password);
		//获得图片验证码
		HttpSession session = request.getSession();
		String value = session.getAttribute("ValidateCode").toString();

		//根据用户名获得用户对象,通过判断密码、验证码是否正确返回相应视图
		User user = userMapper.findUserByName(name);
		if(user != null && user.getPassword().equals(password) && securityCode.equals(value)){
			return "main/main";
		}
		return "index/fail";
	}
	/**
	 * 用户列表,根据当前页和记录数
	 * @param page 当前页
	 * @param rows 页面记录数
	 * @param response
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping("/userList")
	public  void userList(int page,int rows,HttpServletResponse response,Model model) throws IOException{
		response.setContentType("application/json; charset=utf-8");
		//求得开始记录与结束记录
		int start = (page-1)*rows;
		int end = page * rows;
		//把总记录和当前记录写到前台
		int total = userMapper.findUsersList().size();
		List<User> uList = userMapper.findUsersListByPage(start, end);
		this.toBeJson(uList, total, response);
	}
	/**
	 * 新建用户
	 */
	@RequestMapping("/zengjiaUser")
	public void addUser(HttpServletRequest request,User user){
		System.out.println(user.getAddress());
		userMapper.addUser(user);
	}
	/**
	 * 删除用户
	 */
	@RequestMapping("/deleteUser")
	public void deleteUser(HttpServletRequest request){
		String id = request.getParameter("id");
		userMapper.deleteUser(Integer.parseInt(id));
	}
	/**
	 * 编辑用户
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/updateUser")
	public void updateUser(HttpServletRequest request,User user) throws UnsupportedEncodingException{
		userMapper.updateUser(user);
	}
}

然后在前台使用EasyUI的库:

<%@ 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>用户信息列表</title>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/easyui/themes/color.css">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/easyui/demo/demo.css">
<script type="text/javascript" src="<%=request.getContextPath() %>/easyui/jquery.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/easyui/jquery.easyui.min.js"></script>
<style type="text/css">
        #fm{
            margin:0;
            padding:10px 30px;
        }
        .ftitle{
            font-size:14px;
            font-weight:bold;
            padding:5px 0;
            margin-bottom:10px;
            border-bottom:1px solid #ccc;
        }
        .fitem{
            margin-bottom:5px;
        }
        .fitem label{
            display:inline-block;
            width:80px;
        }
        .fitem input{
            width:160px;
        }
    </style>
</head>
<body>
    <h2>用户信息列表</h2>
    <p>You can add User,or Edit_User、Delete_User if you selected an user</p>
    <table id="dg" title="用户操作" class="easyui-datagrid" style="width:700px;height:250px"
           	url="<%=request.getContextPath()%>/user/userList.html"
            toolbar="#toolbar" pagination="true"
            rownumbers="true" fitColumns="true" singleSelect="true">
        <thead>
            <tr >
                <th field="id" width="30" >用户ID</th>
                <th field="name" width="50">姓名</th>
                <th field="sex" width="30">性别</th>
                <th field="age" width="30">年龄</th>
				<th field="address" width="70">家庭住址</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">新建用户</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">编辑</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">删除</a>
    </div>

    <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
            closed="true" buttons="#dlg-buttons">
        <div class="ftitle">用户信息</div>
        <form id="fm" method="post" novalidate>
            <div class="fitem">
                <label>用户ID:</label>
                <input name="id" class="easyui-textbox" required="true" >
            </div>
            <div class="fitem">
                <label>姓名:</label>
                <input name="name" class="easyui-textbox" required="true">
            </div>
             <div class="fitem">
                <label>密码:</label>
                <input name="password" type="password" class="easyui-textbox" required="true">
            </div>
            <div class="fitem">
                <label>性别:</label>
                <input name="sex" class="easyui-textbox" required="true">
            </div>
            <div class="fitem">
                <label>年龄:</label>
                <input name="age" class="easyui-textbox" required="true">
            </div>
			<div class="fitem">
                <label>家庭住址:</label>
                <input name="address" class="easyui-textbox" required="true">
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveUser()" style="width:90px">保存</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')" style="width:90px">取消</a>
    </div>
    <script type="text/javascript">
        var url_pattern;
        function editUser(){
            var row = $('#dg').datagrid('getSelected');
            if (row){
                $('#dlg').dialog('open').dialog('setTitle','Edit User');
                $('#fm').form('load',row);
                url_pattern = '<%=request.getContextPath()%>/user/updateUser.html';
            }
        }
        function newUser(){
            $('#dlg').dialog('open').dialog('setTitle','New User');
          //  $('#fm').form('clear');
            url_pattern = '<%=request.getContextPath()%>/user/zengjiaUser.html';
        }
        function saveUser(){
        	 $('#fm').form('submit',{
                url: url_pattern,
                onSubmit: function(){
                    return $(this).form('validate');
                },
                success: function(result){
                	$('#dlg').dialog('close');        // close the dialog
                    $('#dg').datagrid('reload');    // reload the user data
                }
            });
        }
        function destroyUser(){
            var row = $('#dg').datagrid('getSelected');
            if (row){
                $.messager.confirm('Confirm','确定要删除这个用户么?',function(r){
                    if (r){
                        $.post('<%=request.getContextPath()%>/user/deleteUser.html',{id:row.id},function(result){
                        	 $('#dg').datagrid('reload');
                        },'json');
                    }
                    $('#dg').datagrid('reload');
                });
            }
        }
    </script>
</body>
</html>

源代码地址:

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2025-02-01 17:02:10

【MyBatis】MyBatis+SpringMVC+EasyUI整合分页的相关文章

【SpringMVC学习04】Spring、MyBatis和SpringMVC的整合

前两篇springmvc的文章中都没有和mybatis整合,都是使用静态数据来模拟的,但是springmvc开发不可能不整合mybatis,另外mybatis和spring的整合我之前学习mybatis的时候有写过一篇,但是仅仅是整合mybatis和spring,所以这篇文章我系统的总结一下spring.mybatis和springmvc三个框架的整合(后面学习到maven时,我会再写一篇使用maven整合的文章,这篇没有用到maven). 1. jar包管理 我之前有写过一篇spring.hi

SpringMVC学习(四)——Spring、MyBatis和SpringMVC的整合

之前我整合了Spring和MyBatis这两个框架,不会的可以看我的文章MyBatis框架的学习(六)——MyBatis整合Spring.本文我再来讲SpringMVC和MyBatis整合开发的方法,这样的话,Spring.MyBatis和SpringMVC三大框架的整合开发我们就学会了.这里我使用的Spring是Spring4.1.3这个版本(SpringMVC自然也是这个版本),MyBatis是MyBatis3.2.7这个版本. 为了更好的学习SpringMVC和MyBatis整合开发的方法

基于Maven的Mybatis+spring+springMVC框架整合(mapper代理方式)

首先看看整个Demo的骨架: 首先这个demo整合是基于maven的,maven下载配置我就不说了,网上也有很多大神配置的案例,鼠标右键点击new选择maven project.在选择select an Archetype的时候选择webapp,通过myeclipse新建的maven项目只有一个src/main/resources包,所以还要自己手动新建几个src folder.详情请参照上图,接着就是要在pom.xml中添加dependencies,就是所需要的jar包. <propertie

MyBatis 和 Springmvc 的整合(二)

d. 本次使用的是 Oracle 11g 数据库,建表SQL 脚本: -------Table : users----------------------------------------------------------------------------------------------------------------------------------- drop table users; create table users(   userId number(10) not n

Mybatis + SpringMVC + Maven实现分页查询

使用Mybatis + Maven + SpringMVC 运行时,突然被需要分页查询的功能给难住了 这里推荐采用的插件是PageHelper这个插件,使用起来十分方便.该插件支持以下数据库: Oracle Mysql MariaDB SQLite Hsqldb PostgreSQL DB2 SqlServer(2005+) Informix H2 对应于github的项目地址: https://github.com/pagehelper/Mybatis-PageHelper 关于使用建议猿友们

SSM--Spring(4.3.2.RELEASE) + SpringMVC(4.3.2.RELEASE) + MyBatis(3.4.1) 整合

. 1. 开发环境搭建 参考博文:Eclipse4.6(Neon) + Tomcat8 + MAVEN3.3.9 + SVN项目完整环境搭建 2. Maven Web项目创建 2.1. 2.2. 2.3. 2.4. 2.5. 完成后目录结构图 2.5 (可选)设置: 选中项目 单击右键设置; 项目编码换成UTF-8:Properties -> Resource -> Text file encoding 设置默认的JRE:Properties -> Java Build Path -&g

SpringMVC +mybatis+spring 结合easyui用法及常见问题总结

1.FormatString的用法. 2.用postAjaxFillGrid实现dataGrid 把form表单转换成一个map对象传入后台实现条件查询. Js代码: var oPage = {     pageIndex: 1,     pageSize: 20 };    postAjaxFillGrid('#FormID','${contextPath}/discountController/selectDiscount','#DataGridId', oPage);   参数说明: fo

(三)springmvc+mybatis+dubbo分布式架构 整合 - maven模块规划

上一篇我们介绍<springmvc+mybatis+zookeeper分布式架构 整合 - 平台功能导图>,从今天开始,我们针对于每一个独立的系统做详细的构建,顺便会把整个构建的过程全部记录下来,方便更多的开发者. 提醒: 在构建dubbo分布式平台之前,必须掌握好maven的相关技能,整个构建过程都是使用maven技术.在构建的过程中解决maven问题的时间往往比编码的时间还多,但这不能阻止我们对<构建dubbo分布式平台>之路,没有掌握好maven技能的开发者,可以在网站找一些

myBatis+SpringMVC+Maven整合

一.先创建表结构 二.使用generator通过表结构自动生成model和dao.mapper 使用步骤: 1.解压generator.rar文件 2.文件中的generator.xml文件需要进行修改,修改里面的文件生成地址 3.打开生成语句.txt文件,复制出里面的内容,回到该文件所在目录下,右键-->打开命令窗口,将该命令执行,将会在相应的目录下生成文件Model,Dao.Mapper 生成的文件包括mapper.xml中生成的封装语句,已办是不够用的,需要后期添加和修改 注意:文件路径不