【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>
- <?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>
下边就是要把所有的资源添加到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());
- <?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>
- <?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>
- 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);
- }
- }
- <%@ 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>
源代码地址:
http://download.****.NET/download/u010800530/8961287
相关推荐
- 新手学习mybatis-spring整合技术的简单实例
- dubbo系列(二) 完整SpringMVC项目整合druid redis zookeeper mybatis dubbo spring-data-redis实现分布式session...
- Mybatis_整合笔记02
- mybatis不允许多值传参(@param注解用法)和分页start和end
- 33、整合Mybatis框架
- Java _ Web Mybatis 第二章 输入参数、输出参数类型、动态sql(if标签,where标签、sql片段、foreach标签)、关联查询、整合spring、****
- MyBatis小白鼠002--spring boot整合Mybatis
- 第一步:maven+springboot+mybatis+jersey整合
- spring+springMVC+mybatis的整合 part5
- Spring与Mybatis框架整合的那点事(1)!
- js时间转换+比较 Date.parse的兼容
- ThinkPHP5.0路由之路由注册