SSM框架之数据分页,模糊查询

Java-SSM 专栏收录该内容
1 篇文章 0 订阅

1、创建springMVC项目,搭建环境
2、创建Page.java,存储信息

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Page {
	//显示第几页
	private int pageNow = 1;
	//每页显示条数
	private int pageSize = 3;
	//查询总条数
	private int totalCount;
	//查询总页数
	private int totalPages;
	
	//坐标
	private int offSet;
	//返回查询数据
	private List<?> datas;
	
	//装载查询条件
	Map<String,Object> query = new HashMap();

	public int getPageNow() {
		return pageNow;
	}

	public void setPageNow(int pageNow) {
		this.pageNow = pageNow;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getTotalPages() {
		//直接返回总页数
		return this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:this.totalCount/this.pageSize+1;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}

	public List<?> getDatas() {
		return datas;
	}

	public void setDatas(List<?> datas) {
		this.datas = datas;
	}

	public Map<String, Object> getQuery() {
		return query;
	}

	public void setQuery(Map<String, Object> query) {
		this.query = query;
	}

	public int getOffSet() {
		//显示在数据库里是第几条
		return (this.pageNow-1)*this.pageSize;
	}

	public void setOffSet(int offSet) {
		this.offSet = offSet;
	}
	
	
}

3、创建pojo类,User.java

public class User {
	private String userId;
	private String userName;
	private Integer userAge;
	private String userSex;
	private String userRoleId;
	private Integer userStatus;
	private String userDeptId;
	private String userDesc;
	private String account;
	private String password;
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public Integer getUserAge() {
		return userAge;
	}
	public void setUserAge(Integer userAge) {
		this.userAge = userAge;
	}
	public String getUserSex() {
		return userSex;
	}
	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}
	public String getUserRoleId() {
		return userRoleId;
	}
	public void setUserRoleId(String userRoleId) {
		this.userRoleId = userRoleId;
	}
	public Integer getUserStatus() {
		return userStatus;
	}
	public void setUserStatus(Integer userStatus) {
		this.userStatus = userStatus;
	}
	public String getUserDeptId() {
		return userDeptId;
	}
	public void setUserDeptId(String userDeptId) {
		this.userDeptId = userDeptId;
	}
	public String getUserDesc() {
		return userDesc;
	}
	public void setUserDesc(String userDesc) {
		this.userDesc = userDesc;
	}
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [userId=" + userId + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex
				+ ", userRoleId=" + userRoleId + ", userStatus=" + userStatus + ", userDeptId=" + userDeptId
				+ ", userDesc=" + userDesc + ", account=" + account + ", password=" + password + "]";
	}
	
	
	

}

4、编写UserMapper.xml文件

<?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.znn.dao.UserMapper">
	<resultMap type="com.znn.model.User" id="resultUser">
		<!-- id在数据库中用uuid()方法创建的 -->
		<id property="userId" javaType="String" column="user_id" jdbcType="VARCHAR"/>
		<result property="userName" javaType="String" column="user_name" jdbcType="VARCHAR"/>
		<result property="userAge" javaType="Integer" column="user_age" jdbcType="INTEGER"/>
		<result property="userSex" javaType="String" column="user_sex" jdbcType="VARCHAR"/>
		<result property="userRoleId" javaType="String" column="user_role_id" jdbcType="VARCHAR"/>
		<result property="userStatus" javaType="Integer" column="user_status" jdbcType="INTEGER"/>
		<result property="userDeptId" javaType="String" column="user_dept_id" jdbcType="VARCHAR"/>
		<result property="userDesc" javaType="String" column="user_desc" jdbcType="VARCHAR"/>
		<result property="account" javaType="String" column="account" jdbcType="VARCHAR"/>
		<result property="password" javaType="String" column="password" jdbcType="VARCHAR"/>
	</resultMap>
	<sql id="user_column">
		user_id,user_name,user_age,user_sex,user_role_id,user_status,user_dept_id,user_desc,account,password
	</sql>
	<!-- 1、获取用户列表 -->
	<!-- 返回值用Page,因为把所有属性都封装在page里面了 -->
	<select id="selectUserList" resultMap="resultUser" parameterType="com.znn.model.Page">
		SELECT
			<include refid="user_column"/>
		FROM
			`user`
		<where>
			<!-- 1、查询的属性可以直接用对象取,即不用page.query调用 
				 2、连接符 and 不能用 && ,如果想用请用转义字符
			-->
			<if test="query.user_sex != null and query.user_sex != ''">
				user_sex = #{query.user_sex}
			</if>
			<if test="query.user_name != null and query.user_name != ''">
				AND user_name LIKE CONCAT('%',#{query.user_name},'%')
			</if>
		</where>
		ORDER BY 
			user_id DESC
		LIMIT 
			${offSet},${pageSize}
	</select>
	<!-- 2、获取用户查询条数 -->
	<select id="queryUserCount" parameterType="com.znn.model.Page" resultType="_int">
		SELECT COUNT(*) FROM `user`
		<where>
			<if test="query.user_sex != null and query.user_sex != ''">
				user_sex = #{query.user_sex}
			</if>
			<if test="query.user_name != null and query.user_name != ''">
				AND user_name LIKE CONCAT('%',#{query.user_name},'%')
			</if>
		</where>
	</select>

</mapper>

5、编写Dao层接口 UserMapper.java

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.znn.model.Page;
import com.znn.model.User;

@Repository
public interface UserMapper {
	
	/**
	 * 查询user表全部数据
	 * @return list
	 */
	List<User> selectUserList(Page page);
	/**
	 * 获取总条数
	 * @param page
	 * @return int
	 */
	int queryUserCount(Page page);

}

6、编写Service层 UserService.java接口

import java.util.List;
import java.util.Map;

import com.znn.model.Page;
import com.znn.model.User;

public interface UserService {
	
	/**
	 * 将查询结果全部添加到page中
	 * @return pagelist
	 */
	Page find(Page page);
}

7、编写Service接口实现类

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.znn.dao.UserMapper;
import com.znn.model.Page;
import com.znn.model.User;
import com.znn.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	UserMapper userMapper;
	
	@Override
	public Page find(Page page) {
		//获取全部数据存储到page中
		page.setDatas(userMapper.selectUserList(page));
		//获取总条数,用于配置分页
		page.setTotalCount(userMapper.queryUserCount(page));
		return page;
	}

}

8、编写Controller

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.znn.model.Page;
import com.znn.model.User;
import com.znn.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	UserService userService;
	
    //page查询单独一个方法,方便前台ajax取值
    @RequestMapping("/userList")
    @ResponseBody
    public Page page(Page page){
    	page = userService.find(page);
    	return page;
    }
    
    @GetMapping("/page")
    public String page(Page page,Model model) {
    	model.addAttribute("page",page(page));
		return "view/sys/page";
    }

}

9、编写前台页面,带回显

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	//项目的发布路径,例如: /rabc
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!-- 引入jstl标签 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<!-- 引入时间标签  格式化时间,有时间查询的时候使用,本文没做处理 -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>系统用户管理</title>

<link rel="shortcut icon" href="favicon.ico">
<link href="resource/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
<link href="resource/css/font-awesome.css?v=4.4.0" rel="stylesheet">

<link href="resource/css/animate.css" rel="stylesheet">
<link href="resource/css/style.css?v=4.1.0" rel="stylesheet">

</head>
<script type="text/javascript" src="resource/jquery-3.4.1.min.js"></script>

<script type="text/javascript">
	
<body class="gray-bg">
	<div class="row">
		<div class="col-sm-12">
			<div class="ibox">
				<div class="ibox-title">
					<h5>系统用户管理</h5>
					<!--<div class="ibox-tools">
                            <a href="projects.html" class="btn btn-primary btn-xs">创建新项目</a>
                        </div>-->
				</div>
				<form action="page" method="get" id="form">
				<div class="ibox-content">
					<div class="row m-b-sm m-t-sm">
						<div class="col-md-2">
							<button type="button" id="user-add-btn"
								class="btn btn-primary btn-sm">
								<i class="fa fa-user-plus"></i> 新建
							</button>
							<button type="button" id="user-loading-btn"
								class="btn btn-white btn-sm">
								<i class="fa fa-refresh"></i> 刷新
							</button>
							
						</div>
						<div class="col-md-2 col-md-offset-4">
							<select class="input-sm form-control input-s-sm inline"
								style="font-size: 12px;" name="query['user_sex']">
								<option value="" id="selector">请选择性别</option>
									<option value="男" 
										<c:if test="${page.query.user_sex =='男'}">
											selected="selected"
										</c:if>
									>男</option>
									<option value="女" 
										<c:if test="${page.query.user_sex =='女'}">
											selected="selected"
										</c:if>
									>女</option>
								
							</select>
						</div>
						<div class="col-md-3">
							<div class="input-group">
							/* query['user_name'] 用于设置属性值,固定写法   query为page中的属性  */
								<input type="text" placeholder="请输入用户的姓名" name="query['user_name']" 
								value="${page.query.user_name }"
									class="input-sm form-control"> <span
									class="input-group-btn">
									<button type="button" id="btn" class="btn btn-sm btn-primary">
										搜索</button>
								</span>
							</div>
						</div>
							//编写隐藏域,往后台传值,用于分页
							<input hidden="hidden" name="pageNow" id="pageNow" value="${page.pageNow }">
							<input hidden="hidden" id="totalPages" value="${page.totalPages }">
						</form>
					</div>

					<div class="project-list">

						<table class="table table-hover">
							<tbody id="tbody">
							<c:forEach items="${requestScope.page.datas }" var="user" varStatus="vs">
								<tr>
									<td class="client-avatar"><img alt="image" onerror="this.src='resource/img/a2.jpg'"
										src=""></td>
									<td>
										<!-- A标签的样式,暂时没有使用该链接 --> 
										<a href="javascript:;"class="client-link">${user.userName }</a>
									</td>
									<td>${user.account }</td>
									<td class="contact-type"><i class="fa fa-user-secret">
									</i></td>
									<td>超级管理员</td>
									<td class="client-status">
									<c:if test="${user.userStatus==1 }" var="flag">
										<span class="label label-primary">已激活</span></td>
									</c:if>
									<c:if test="${!flag }">
										<span class="label label-danger">已禁用</span></td>
									</c:if>
										
									<td class="contact-type"><i class="fa fa-clock-o"> </i></td>
									<td>
										<%-- <fmt:formatDate value="${user.userCreateTime }" pattern="yyyy-MM-dd HH:mm:ss"/> --%>
										2019-9-9 09:54:34
									</td>
									<td>${user.userAge }</td>
									<td>${user.userSex }</td>
									<td><a href="system_user_update.html"
										class="btn btn-success btn-sm"><i class="fa fa-pencil"></i>
											编辑 </a> <!-- 设置自定义数据 pk-id 用于表示注解 --> <a href="javascript:;"
										pk-id="-999" user-status="2"
										class="btn btn-warning btn-sm user-status-btn"><i
											class="fa fa-power-off"></i> 禁用 </a> <a href="javascript:;"
										pk-id="-999" user-status="1"
										class="btn btn-danger btn-sm user-status-btn"><i
											class="fa fa-remove"></i> 删除 </a> <a href="javascript:;"
										pk-id="-999" user-status="3"
										class="btn btn-primary btn-sm user-status-btn"><i
											class="fa fa-smile-o"></i> 激活 </a> <a href="javascript:;"
										pk-id="-999" class="btn btn-info btn-sm user-role-btn"><i
											class="fa fa-odnoklassniki"></i> 角色 </a> <a href="javascript:;"
										pk-id="-999" class="btn btn-white btn-sm user-photo-btn"><i
											class="fa fa-file-photo-o"></i> 头像 </a></td>
								</tr>
							</c:forEach>
							</tbody>
						</table>
					</div>
					<div class="row m-b-sm m-t-sm">
						<div class="col-md-2">
							<span style="line-height: 30px;">显示 ${page.pageNow } 到 ${page.totalPages }项,共${page.totalCount } 项</span>
						</div>
						<div class="col-md-5 col-md-offset-5">
							<span class="input-group-btn">
								<button type="button" class="btn btn-sm btn-white" id="first">首页</button>
								<button type="button" class="btn btn-sm btn-white" id="prev">上一页</button>
								<button type="button" class="btn btn-sm btn-white" id="next">下一页</button>
								<button type="button" class="btn btn-sm btn-white" id="end">尾页</button>
							</span>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- 全局js -->
	<script src="resource/js/jquery.min.js?v=2.1.4"></script>
	<script src="resource/js/bootstrap.min.js?v=3.3.6"></script>
	<script src="resource/js/plugins/layer/layer.min.js"></script>


	<!-- 自定义js -->
	<script src="resource/js/content.js?v=1.0.0"></script>
	<script type="text/javascript">
		$(function(){
			$("#end").click("on",function(){
				$("#pageNow").val($("#totalPages").val());
				$("#form").submit();
			})
			$("#first").click("on",function(){
				$("#pageNow").val(1);
				$("#form").submit();
			})
			$("#prev").click("on",function(){
				var pageNow = $("#pageNow").val();
				if(pageNow==1){
					layer.msg("已经是第一页了");
					return false;
				}
				$("#pageNow").val(pageNow-1);
				$("#form").submit();
			})
			$("#next").click("on",function(){
				var pageNow = $("#pageNow").val();
				if(pageNow==$("#totalPages").val()){
					layer.msg("已经是最后一页了");
					return false;
				}
				$("#pageNow").val(parseInt(pageNow)+1);
				$("#form").submit();
			})
			$("#btn").click("on",function(){
				$("#pageNow").val(1);
				$("#form").submit();
			})
			
			/* $("#selector option[value='男']").prop("selected", true); */
		})
	</script>

	<script>
		$(document).ready(function() {
			$('#user-loading-btn').click(function() {
				simpleLoad($(this), true)
			});

			$("#user-add-btn").click(function() {
				window.location.href = "system_user_add.html";
			});

			$(".user-status-btn").click(function() {
				//获取两个自定义属性
				var user_id = $(this).attr("pk-id");
				var user_status = $(this).attr("user-status");
				console.log("用户主键:" + user_id + ",用户状态:" + user_status);

				var textArray = [ "激活", "禁用", "注销" ]

				layer.confirm('您确定要[' + textArray[user_status - 1] + ']操作吗?', {
					skin : 'layui-layer-molv', //样式类名
					btn : [ '确定继续', '取消' ], //按钮
					shade : 0.01, //显示遮罩
					shift : 6
				}, function() {

					//需要发送ajax请求
					$.get("result.json", {
						user_id : user_id,
						user_status : user_status
					}, function(data) {
						if (data.flag == "success") {
							window.location.reload();
							return false;
						} else {
							layer.msg('操作失败');
							return false;
						}
					})
				}, function() {
				});

			});

			$(".user-role-btn").click(function() {
				var user_id = $(this).attr("pk-id");
				layer.open({
					title : "系统用户设置角色",
					type : 2,
					area : [ '400px', '220px' ],
					fixed : false, //不固定
					shade : 0.01,
					content : 'system_user_role.html?user_id=' + user_id
				});
			});

			$(".user-photo-btn").click(function() {
				var user_id = $(this).attr("pk-id");
				layer.open({
					title : "系统用户头像",
					type : 2,
					area : [ '350px', '400px' ],
					fixed : false, //不固定
					shade : 0.01,
					content : 'system_user_photo.html?user_id=' + user_id
				});
			});
		});

		function simpleLoad(btn, state) {
			if (state) {
				btn.children().addClass('fa-spin');
				btn.contents().last().replaceWith(" Loading");
				window.location.reload();
			} else {
				setTimeout(function() {
					btn.children().removeClass('fa-spin');
					btn.contents().last().replaceWith(" Refresh");
					window.location.reload();
				}, 2000);
			}
		}
	</script>


</body>
</html>
</html>

10、注意事项
①开发工具用的eclipse,Version: 2019-06 (4.12.0)
②数据库用的mysql,Version:12.1.18
③前台用的模板,需要的自取,下载链接见附录
④没了,新手一枚,有不足之处还请大佬多多指教,愿大佬温柔待我

附录:Hplus官方完整版带文档 v.4.1.0
链接:https://pan.baidu.com/s/13666pH-QOgxGS4_PDu1btQ
提取码:znzo

  • 0
    点赞
  • 0
    评论
  • 3
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值