springmvc4+spring4+hibernate4注解开发,分页查询,表头排序,多条件模糊查询,查询自动补全功能

5 篇文章 0 订阅
3 篇文章 0 订阅

一、数据库

create table if not exists t_student(
student_id int primary key not null auto_increment,
student_name varchar(30),
student_age int ,
student_address varchar(100),
student_qq varchar(20)
) engine = InnoDB default charset = utf8;

insert into t_student values(null,'aaa',21,'China','931391200');
insert into t_student values(null,'bbb',12,'shanghai','931391221');
insert into t_student values(null,'ccc',32,'guangzhou','931391212');
insert into t_student values(null,'ddd',14,'shenzhou','93139122');
insert into t_student values(null,'eee',15,'henan','931391243');
insert into t_student values(null,'fff',17,'zhengzhou','931391214');
insert into t_student values(null,'ggg',24,'taiyuan','931391221');
insert into t_student values(null,'hhh',22,'beijing','93139127');
insert into t_student values(null,'kkk',32,'jinan','93139126');
insert into t_student values(null,'jjj',21,'dingyuan','93139123');
insert into t_student values(null,'rrr',18,'dasong','93139121');
insert into t_student values(null,'eqq',31,'yuangu','93139128');
insert into t_student values(null,'sss',19,'tangshan','9313912112');
insert into t_student values(null,'iii',25,'tangchao','9313912113');
insert into t_student values(null,'lll',27,'niboer','9313912114');
insert into t_student values(null,'yyy',26,'bajisitan','9313912115');
insert into t_student values(null,'ttt',29,'meiguo','9313912116');
insert into t_student values(null,"中国好歌曲",3,'lundun','93139121122');
insert into t_student values(null,'中国好声音',23,'lundun','93139121122');
insert into t_student values(null,'中国好舞蹈',23,'lundun','93139121122');
insert into t_student values(null,'中国之声',23,'lundun','93139121122');
insert into t_student values(null,'中国演说家',23,'lundun','93139121122');
insert into t_student values(null,'中国春节晚会',23,'lundun','93139121122');
二、实体类

      2.1数据库实体类

package com.h3c.zgc.user.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="t_student",catalog="itac")
public class Student {
	@Id  
	@GenericGenerator(name="generator",strategy="increment")  
	@GeneratedValue(generator="generator")  
	@Column(name="student_id",unique=true,nullable=false)
	private Integer studentId;
	@Column(name="student_name")
	private String studentName;
	@Column(name="student_age")
	private Integer studentAge;
	@Column(name="student_address")
	private String studentAddress;
	@Column(name="student_qq")
	private String studentQQ;
	
    //getter setter toStriung
}
2.2分页实体类

package com.h3c.zgc.user.entity;

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

public class Page {

	private int currentPageNum = 1;// 当前第几页(默认第一页),---主要用于传递到前台显示  
    private int totalPageNum;// 总页数  
    private int totalCount;// 总记录数  
    private int perPageSize = 5;// 每页显示的记录条数(默认5条)  
  
    private List entitys = new ArrayList();// 记录当前页中的数据条目  
  
    // 所有参数都进行修改  
  
    public Page(){}  
    public Page(int currentPageNum, int totalCount, int perPageSize,  
            List entitys) {  
        this.totalCount = totalCount;  
        this.perPageSize = perPageSize;  
        this.totalPageNum = totalCount % perPageSize == 0 ? totalCount  
                / perPageSize : totalCount / perPageSize + 1;  
        this.entitys = entitys;  
        this.currentPageNum = currentPageNum<1?1:(currentPageNum>totalPageNum?totalPageNum:currentPageNum);//如果当前页小于第一页,则停留在第一页  
    }  
  
    // 使用默认的当前页和每页显示记录条数  
    public Page( int totalCount, List entitys) {  
        this.totalCount = totalCount;  
        this.totalPageNum = totalCount % perPageSize == 0 ? totalCount  
                / perPageSize : totalCount / perPageSize + 1;  
        this.entitys = entitys;  
        this.currentPageNum = currentPageNum<1?1:(currentPageNum>totalPageNum?totalPageNum:currentPageNum);//如果当前页小于第一页,则停留在第一页  
    }  
  
    public int getCurrentPageNum() {  
        return currentPageNum;  
    }  
  
    public void setCurrentPageNum(int currentPageNum) {  
        this.currentPageNum = currentPageNum<1?1:(currentPageNum>totalPageNum?totalPageNum:currentPageNum);//如果当前页小于第一页,则停留在第一页  
    }  
  
    public int getTotalPageNum() {  
        return totalPageNum;  
    }  
  
    public void setTotalPageNum(int totalPageNum) {  
        this.totalPageNum = totalCount % perPageSize == 0 ? totalCount  
                / perPageSize : totalCount / perPageSize + 1;  
    }  
  
    public int getTotalCount() {  
        return totalCount;  
    }  
  
    public void setTotalCount(int totalCount) {  
        this.totalCount = totalCount;  
    }  
  
    public int getPerPageSize() {  
        return perPageSize;  
    }  
  
    public void setPerPageSize(int perPageSize) {  
        this.perPageSize = perPageSize;  
    }  
  
    public List getEntitys() {  
        return entitys;  
    }  
  
    public void setEntitys(List entitys) {  
        this.entitys = entitys;  
    }  
  
    @Override  
    public String toString() {  
        return "PageUtil [currentPageNum=" + currentPageNum + ", totalPageNum="  
                + totalPageNum + ", totalCount=" + totalCount  
                + ", perPageSize=" + perPageSize + ", entitys=" + entitys + "]";  
    }  
}
2.3接受查询参数的vo

package com.h3c.zgc.user.entity;

import javax.persistence.Column;

public class StudentView {

	private Integer studentId;
	private String studentName;
	private Integer studentAge;
	private String studentAddress;
	private String studentQQ;
	
	//getter setter toString
}
2.4接收分页数据,向前台传递表头排序的vo

package com.h3c.zgc.user.entity;

public class PageView {

    private int currentPageNum = 1;// 当前第几页(默认第一页),---主要用于传递到前台显示  
    private int totalPageNum;// 总页数  
    private int perPageSize = 5;// 每页显示的记录条数(默认5条)  
    
    private String sortRule;   //分页规则,asc升序,desc降序
    private String sortColumn;   //分页列名
	
    //getter setter toString
    
}
dao层

package com.h3c.zgc.user.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.h3c.zgc.user.entity.PageView;
import com.h3c.zgc.user.entity.Student;
import com.h3c.zgc.user.entity.StudentView;

@Repository
public class StudentDao extends HibernateDaoSupport{
	@Resource
	private void set(SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
	
	public void insertStudent(Student student){
		this.getHibernateTemplate().save(student);
	}
	
	@SuppressWarnings("unchecked")
	public List<Student> getStudents(final PageView pv,StudentView sv){
		final String hql = this.getHql(sv, "from Student s where 1=1",pv);
		final int offset = (pv.getCurrentPageNum()-1)*pv.getPerPageSize();
		List<Student> students = this.getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				
				Query query = session.createQuery(hql);
				query.setFirstResult(offset);
				query.setMaxResults(pv.getPerPageSize());
				
				return query.list();
			}
		});
		return students;
	}
	public int getTotalCount(StudentView sv){
		String hql = this.getHql(sv, "select count(studentId) from Student s where 1=1",null);
		int count= ((Long)this.getHibernateTemplate().find(hql.toString()).iterator().next()).intValue();  
		return count;
	}
	
	private String getHql(StudentView sv, String hqlHeader,PageView pv){
		StringBuffer hql = new StringBuffer(hqlHeader);
		if(null!=sv.getStudentId()){
			hql.append( " and studentId = '"+sv.getStudentId()+"'");
		}
		if(null!=sv.getStudentName()&&""!=sv.getStudentName()){
			hql.append(" and studentName like '%"+sv.getStudentName()+"%'");
		}
		if(null!=sv.getStudentAge()){
			hql.append(" and studentAge = '"+sv.getStudentAge()+"'");
		}
		if(null!=sv.getStudentAddress()&&""!=sv.getStudentAddress()){
			hql.append(" and studentAddress like '%"+sv.getStudentAddress()+"%'");
		}
		if(null!=sv.getStudentQQ()&&""!=sv.getStudentQQ()){
			hql.append(" and studentQQ like '%"+sv.getStudentQQ()+"%'");
		}
		if(null!=pv&&null!=pv.getSortColumn()&&""!=pv.getSortColumn()){
			hql.append(" order by "+pv.getSortColumn()+" "+pv.getSortRule());
		}
		return hql.toString();
	}
	public List<String> getStudentsByName(String studentName) {
		return (List<String>) this.getHibernateTemplate().find("select s.studentName from Student s where s.studentName like '%"+studentName+"%'");
	}
	
	public Student getStudent(Integer studentId){
		return this.getHibernateTemplate().get(Student.class, studentId);
	}
	
}
service层

package com.h3c.zgc.user.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.h3c.zgc.user.dao.StudentDao;
import com.h3c.zgc.user.entity.PageView;
import com.h3c.zgc.user.entity.Student;
import com.h3c.zgc.user.entity.StudentView;
@Service
public class StudentService {
	@Resource
	private StudentDao studentDao;
	@Transactional
	public void insertStudent(Student student){
		this.studentDao.insertStudent(student);
	}
	public List<Student> getStudents(final PageView pv,StudentView sv){
		return this.studentDao.getStudents(pv, sv);
	}
	public int getTotalCount(StudentView sv){
		return this.studentDao.getTotalCount(sv);
	}
	public List<String> getStudentsByName(String studentName){
		return this.studentDao.getStudentsByName(studentName);
	}
	public Student getStudent(Integer studentId){
		return this.studentDao.getStudent(studentId);
	}
}
controller层

package com.h3c.zgc.user.controller;

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.h3c.zgc.user.entity.Page;
import com.h3c.zgc.user.entity.PageView;
import com.h3c.zgc.user.entity.Student;
import com.h3c.zgc.user.entity.StudentView;
import com.h3c.zgc.user.service.StudentService;

@Controller
@Scope
public class StudentController {
	@Resource
	private StudentService studentService;
	@RequestMapping("getAllStudent")
	public String getAllStudent(PageView pv,StudentView sv,HttpServletRequest request){
		//获取总页数
		int totalCount = this.studentService.getTotalCount(sv);
		Page page = new Page(pv.getCurrentPageNum(), totalCount, 5, null);
		//如果当前页大于总页数,则将最大页数设置为当前页
		int currentNum = pv.getCurrentPageNum()>page.getTotalPageNum()?page.getTotalPageNum():pv.getCurrentPageNum();
		pv.setCurrentPageNum(currentNum);
		//获取集合
		List<Student> students = this.studentService.getStudents(pv, sv);
		page.setEntitys(students);
		request.setAttribute("page", page);//传递分页参数,
		request.setAttribute("view", sv);//封装前台查询参数
		request.setAttribute("pageView", pv);//主要是表头排序
//		map.put("sortColumn", pv.getSortColumn());
//		map.put("sortRule", pv.getSortRule());
		
		System.out.println(students);
		System.out.println(page);
		System.out.println(pv);
		System.out.println("年龄:"+sv.getStudentAge());
		return "user/userList";
	}
	@RequestMapping("getNames")
	public void getNames(String studentName,HttpServletResponse response){
		List<String> studentNames = this.studentService.getStudentsByName(studentName);
		System.out.println(studentNames);
		Gson gson = new Gson();
		String strs = gson.toJson(studentNames);
		response.setContentType("text/html;charset=UTF-8");
		try {
			response.getWriter().write(strs);
		} catch (IOException e) {
			
		}
		System.out.println(strs);
	}
	@RequestMapping("getStudent")
	public String getStudent(Integer studentId,HttpServletRequest request){
		Student s = this.studentService.getStudent(studentId);
		request.setAttribute("s", s);
		return "user/updateStudent";
	}
}
主页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
<script type="text/javascript" src="${pageContext.request.contextPath }/resources/js/jquery-1.11.1.js"></script>
</head>
<body>
<a href="${pageContext.request.contextPath }/getAllStudent">查找所有用户</a>
</body>
</html>
student全部展示页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
   
<!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>
<style type="text/css">  
    #mytable {    
    padding: 0;  
    margin: 0;    
    border-collapse:collapse;  
}  
  
td {  
    border: 1px solid #C1DAD7;    
    background: #fff;  
    font-size:11px;  
    padding: 6px 6px 6px 12px;  
    color: #4f6b72;  
}  
  
td.alt {  
    background: #F5FAFA;  
    color: #797268;  
}  
.noShow{  
    display: none;  
}  
</style>  
<script type="text/javascript" src="${pageContext.request.contextPath }/resources/js/jquery-1.11.1.js"></script>
</head>
<body>
<form id="search" action="<c:url value="/getAllStudent"/>" method="post">
	<table>
		<tr>
			<td>
			<div >
			<div >
			学生姓名:<input type="text" name="studentName" value="${view.studentName }" οnkeyup="p.autoCompletion(this.value)"/>
			</div>
			<div id="prompt" style="display:none;text-align:right;position:relative;float: right; ">
				 <select id="sname" size="5" style="width: 153px">
					<option></option>
				</select>
			</div>
			</div>
			</td> 
			<td>学生年龄:<input type="text" name="studentAge" value="${view.studentAge }" /></td>
		</tr>
		<tr>
			<td>学生地址:<input type="text" name="studentAddress" value="${view.studentAddress }"/></td>
			<td>学生QQ:<input type="text" name="studentQQ" value="${view.studentQQ }"/></td>
			<td style="display: none;">
				<input id="sortColumn" name="sortColumn" type="hidden" value="${pageView.sortColumn }" />
				<input id="sortRule" name="sortRule" type="hidden" value="${pageView.sortRule }">
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<input type="submit" value="查询" />
			</td>
		</tr>
	</table>

	<table >
		<tr>
			<th οnclick="p.sort('studentId')">学生id</th>
			<th>学生姓名</th>
			<th>学生年龄</th>
			<th>学生地址</th>
			<th>学生QQ</th>
			<th>操作</th>
		</tr>
		<c:forEach items="${page.entitys }" var="s">
			<tr>
				<td>${s.studentId }</td>
				<td>${s.studentName }</td>
				<td>${s.studentAge }</td>
				<td>${s.studentAddress }</td>
				<td>${s.studentQQ }</td>   
				<td>
					<a href="javascript:void(0);" οnclick="p.openWindow('<c:url value="/getStudent?studentId=${s.studentId }"/>')">修改</a>
					<a>删除</a>
				</td>
			</tr>
		</c:forEach>
		<tr>                 
			<td colspan="6">
				<a href="javascript:void(0);" οnclick="p.toPage('<c:url value="/getAllStudent?currentPageNum=1"/>')">首页</a>
				<a href="javascript:void(0);" οnclick="p.toPage('<c:url value="/getAllStudent?currentPageNum=${page.currentPageNum+1 }"/>')">下一页</a>
				${page.currentPageNum }/${page.totalPageNum }
				<a href="javascript:void(0);" οnclick="p.toPage('<c:url value="/getAllStudent?currentPageNum=${page.currentPageNum-1 }"/>')">上一页</a>
				<a href="javascript:void(0);" οnclick="p.toPage('<c:url value="/getAllStudent?currentPageNum=${page.totalPageNum }"/>')">尾页</a>
				   总有${page.totalCount }条记录   
				<input type="button" value="点此跳到" οnclick="p.toThePage('<c:url value="/getAllStudent?currentPageNum="/>')"/>
				<input id="index" type="text"/>页
			</td>
		</tr>
	</table>
</form>
</body>
<script type="text/javascript">
	var p = {
		toPage:function(url){
			$("#search").attr("action",url);
			$("#search").submit();
		},
		toThePage:function(url){
			alert($("#index").val()=="");
			if(""!=$("#index").val()){
				$("#search").attr("action",url+$("#index").val());
				$("#search").submit();
			}
		},
		sort:function(arg){
			$("#sortColumn").val(arg);
			var sortRule = $("#sortRule");
			
			if(""==sortRule.val()||"asc"==sortRule.val()){
				sortRule.attr("value","desc");
			}else{
				sortRule.attr("value","asc");
			}
			$("#search").submit();
		},
		autoCompletion:function(arg){
			if(""==arg){
				/*
				主要功能是,当输入的为空的时候,摁下键盘,不去发送ajax,当输入之后,一个一个进行删除,删到最后为空的时候,
				隐藏提示下拉框
				*/
				$("#prompt").hide();
				return ;
			}
			var d = {"studentName":arg};
			$.ajax({
				type:"post",
				url:"<c:url value="/getNames"/>",
				data:d,
				dataType:"json",
				success:function(data){
					//如果没有查询出元素,则隐藏提示下拉框
					 if(""==data){
						$("#prompt").hide();
					}  
					//添加查询的元素之前需要先清除之前的
					if(""!=data){
						$("#prompt").show();
						$("#sname option").remove();
						for(var i=0;i<data.length;i++){
							$("#sname").append("<option>"+data[i]+"</option>");
						}
					}
				}
			});
		},
		openWindow:function(url){
			alert(url);
			//设置模式窗口的一些状态值  
	        var windowStatus = "dialogWidth:1000px;dialogHeight:700px;center:1;status:0;";  
	        var data = { };  
	        //将模式窗口返回的值临时保存  
	        var temp = showModalDialog(url,data,windowStatus); 
		},
	};

</script>
</html>
student修改页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
</head>
<body>
<table>
	<tr style="display: none;">
		<td>学生id </td>
		<td><input type="hidden" value="${s.studentId }"/></td>
	</tr>
	<tr>
		<td> 学生姓名</td>
		<td><input type="text" name="studentName" value="${s.studentName }"/> </td>
	</tr>
	<tr>
		<td>学生年龄</td>
		<td><input type="text" name="studentAge" value="${s.studentAge }"/> </td>
	</tr>
	<tr>
		<td>学生住址</td>
		<td><input type="text" name="studentAddress" value="${s.studentAddress }"/></td>
	</tr>
	<tr>
		<td>学生QQ</td>
		<td><input type="text" name="studentQQ" value="${s.studentQQ }"/> </td>
	</tr>
</table>
</body>
</html>


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值