十. 测试类
package com.yjl.test; import java.util.Arrays; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.yjl.pojo.User; import com.yjl.service.UserService; import com.yjl.util.PageBean; import com.yjl.util.QueryHelper; /** @author:yuejl @date: 2019年5月27日 下午3:04:08 @Description 类的相关描述 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class UserTest { @Resource private UserService userService; @Test public void AddTest(){ User user=new User(); user.setName("蝴蝶飞3"); user.setSex("男"); user.setAge(24); userService.addEntity(user); } @Test public void updateTest(){ User user=userService.getEntityById(6); user.setName("蝴蝶飞4"); user.setAge(25); userService.updateEntity(user); } @Test public void deleteTest(){ userService.deleteEntity(6); } @Test public void saveOrUpdateTest(){ User user=new User(); user.setId(7); user.setName("蝴蝶飞4"); user.setSex("男"); user.setAge(24); userService.saveOrUpdateEntity(user); } @Test public void getEntityByIdTest(){ User user=userService.getEntityById(7); System.out.println(user); } @Test public void getEntityTest(){ //User user=userService.getEntity("From User where name=? and age=?",new Object[]{"张三",24}); User user=userService.getEntity("From User where name=? and age=?",Arrays.asList(new Object[]{"张三",24})); System.out.println(user); } @Test public void findAllEntitysTest(){ List<User> userList=userService.findAllEntitys(); userList.forEach(n->System.out.println(n)); } @Test public void findEntitysByIds(){ //List<User> userList=userService.findEntitysByIds(new Long[]{3L,4L}); List<User> userList=userService.findEntitysByIds(new Long[]{3L,4L}); userList.forEach(n->System.out.println(n)); } @Test public void findEntitysByHql(){ //List<User> userList=userService.findEntitysByHql("From User where sex=? and age=?",new Object[]{"男",24}); //List<User> userList=userService.findEntitysByHql("From User where sex=? and age=?",Arrays.asList(new Object[]{"男",24})); List<User> userList=userService.findEntitysByHql("From User where sex=? and age=?",Arrays.asList(new Object[]{"男",24}),1,2); userList.forEach(n->System.out.println(n)); } @Test public void countTest(){ //System.out.println(userService.count()); //System.out.println(userService.count("select count(*) From User")); //System.out.println(userService.count("select count(*) From User where sex=? and age=?",Arrays.asList(new Object[]{"男",24}))); System.out.println(userService.count("select count(*) From User where sex=? and age=?",new Object[]{"男",24})); } @Test public void queryHelper1Test(){ QueryHelper qh=new QueryHelper(User.class); qh.addCondition("sex=?",new Object[]{"男"}) .addCondition("age=?",24); System.out.println("输出值:"+qh.getListQueryHql()); List<User> userList=userService.findEntitysByHql(qh); userList.forEach(n->System.out.println(n)); } @Test public void queryHelper2Test(){ QueryHelper qh=new QueryHelper(User.class); qh.addCondition("sex=?",new Object[]{"男"}) .addCondition("age=?",24); qh.setCount(); System.out.println(userService.count(qh)); } @Test public void queryHelper3Test(){ QueryHelper qh=new QueryHelper(User.class); qh.addCondition("sex=?",new Object[]{"男"}) .addCondition("age=?",24); PageBean<User> userList=userService.page(1,2,qh); System.out.println(userList.toString()); } @Test public void uniqueTest(){ //Object o=userService.queryUnique("select count(*) From User where sex=? and age=?",new Object[]{"男",24}); //Object o=userService.queryUnique("select max(id) From User where sex=? and age=?",new Object[]{"男",24}); Object o=userService.queryUnique("From User where name=? and age=?",new Object[]{"王二",24}); System.out.println((User)o); } }
其中,数据库值有:
十一 BaseAction 类
package com.yjl.util; import java.lang.reflect.ParameterizedType; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.util.ValueStack; /** * 自己定义好的BaseAction, 需要继承这个BaseAction. *author 作者 yuejl *version 创建时间 2018年1月11日上午9:38:19 */ public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>{ private static final long serialVersionUID = 1L; /** * @param 要封闭的Model */ protected T model; /** @return 构造方法,获得model的值 */ @SuppressWarnings("unchecked") public BaseAction(){ ParameterizedType p=(ParameterizedType) this.getClass().getGenericSuperclass(); Class <T> clazz=(Class<T>) p.getActualTypeArguments()[0]; try { model=clazz.newInstance(); } catch (Exception e) { e.printStackTrace(); } } /** * @return 获得封装后的数据 */ @Override public T getModel() { return model; } //定义分页所用的值 private int currentPage; private int pageSize; public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** * * @return 获取值栈 */ public ValueStack getValueStack(){ return ActionContext.getContext().getValueStack(); } /** * @return 获取当前的request */ public HttpServletRequest getCurrentRequest(){ return ServletActionContext.getRequest(); } /** * @return 获取当前的session */ public HttpSession getCurrentSession(){ return getCurrentRequest().getSession(); } /** * @return 获取当前的response */ public HttpServletResponse getCurrentResponse() { return ServletActionContext.getResponse(); } //可以继续添加一些常见的方法。 }
十二 UserAction 类,需要继承BaseAction
package com.yjl.web.action; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.yjl.pojo.User; import com.yjl.service.UserService; import com.yjl.util.BaseAction; import com.yjl.util.QueryHelper; /** @author:yuejl @date: 2019年5月22日 下午8:05:24 @Description 类的相关描述 */ @Controller @Scope("prototype") public class UserAction extends BaseAction<User>{ private static final long serialVersionUID = 1L; @Resource private UserService userService; public String list(){ /*List<User> userList=userService.findAllEntitys(); ActionContext.getContext().getValueStack(). set("userList", userList);*/ QueryHelper qh=new QueryHelper(User.class); getValueStack().push( userService.page( super.getCurrentPage(), super.getPageSize(), qh)); return "list"; } }
十三 pageView.jspf 分页界面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <s:if test="pageCount==0"> <span class="text-danger">对不起,没有查询到相关的记录信息</span> </s:if> <s:else> <div class="row"> <div class="col-md-4" style="height:20px;font-size:13px;"> 页次:<span class="text-danger" style="font-size:16px" id="showCurrentPage">${currentPage}</span>/ <span class="text-danger" style="font-size:16px">${pageCount}</span>页 <span id="showPageSize" class="hidden" style="display:none;">${pageSize}</span> 每页显示:<select class="text-danger" style="font-size:16px" id="pageSize"></select> 条 <span id="showRecordCount" class="hidden" style="display:none;">${recordCount}</span> 总记录数:<span class="text-danger" style="font-size:16px">${recordCount}</span> 条 </div> <div class="col-md-6" style="margin-top:-25px"> <ul class="pagination pagination-sm"> <!-- 首页的时候 --> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(1);">首页</a></li> <!-- 判断向后页是否可用 --> <s:if test="start"> <li class="disabeld"><a href="javascript:void(0)">«</a></li> </s:if> <s:else> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(${currentPage}-1);">«</a></li> </s:else> <!-- 显示前面的... --> <s:if test="beginPageIndex>1"> <s:if test="currentPage>10"> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(${currentPage}-10);">...</a></li> </s:if> <s:else> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(${currentPage}-1);">...</a></li> </s:else> </s:if> <s:iterator begin="%{beginPageIndex}" end="%{endPageIndex}" var="num"> <s:if test="#num == currentPage"> <%-- 当前页 --%> <li class="active"><a href="javascript:void(0)">${num}</a></li> </s:if> <s:else> <%-- 非当前页 --%> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(${num});">${num}</a></li> </s:else> </s:iterator> <!-- 显示后面的... --> <s:if test="currentPage<pageCount-5"> <s:if test="currentPage+5<pageCount"> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(${currentPage}+5);">...</a></li> </s:if> <s:else> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(${currentPage}-1);">...</a></li> </s:else> </s:if> <!-- 判断向后页是否可用 --> <s:if test="end"> <li class="disabeld"><a href="javascript:void(0)">»</a></li> </s:if> <s:else> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(${currentPage}+1);">»</a></li> </s:else> <!--是尾页的时候 --> <li><a href="javascript:void(0)" onclick="javascript:gotoPage(${pageCount});">尾页</a></li> </ul> </div> <div class="col-md-2"> <span class="pull-right" style="font-size:16px;">快速到第: <select onchange="gotoPage(this.value)" id="_pn" style="width:45px;"> <s:iterator begin="1" end="%{pageCount}" var="num"> <option value="${num}">${num}</option> </s:iterator> </select> 页</span> <script type="text/javascript"> $("#_pn").val("${currentPage}"); </script> </div> </div> </s:else> <script type="text/javascript"> function gotoPage(pageNum){ $("#pageForm").append("<input type='hidden' name='currentPage' value='" + pageNum +"'>"); var pageSize=$("#pageSize").val(); $("#pageForm").append("<input type='hidden' name='pageSize' value='"+pageSize+"'>"); $("#pageForm").submit(); } $("#pageSize").on("change",function(){ //获取显示的页面数 var pageSize=$(this).val(); //获取当前的页数。 var currentPage=$("#showCurrentPage").text(); if(pageSize*currentPage>recordCount){ currentPage=1; } //先看一下,是否有那些值。 if($("#pageForm input[name='currentPage']").length>0){ $("#pageForm input[name='currentPage']").val(currentPage); $("#pageForm input[name='pageSize']").val(pageSize); }else{ $("#pageForm").append("<input type='hidden' name='currentPage' value='" + currentPage +"'>"); $("#pageForm").append("<input type='hidden' name='pageSize' value='"+pageSize+"'>"); } $("#pageForm").submit(); }) //设置显示的页数 var pageSizeList=[1,5,10,15,20]; var recordCount=$("#showRecordCount").text(); if(!inArray(recordCount,pageSizeList)){ //不再这里面,才添加。 pageSizeList.push(recordCount); } var createPageSize=function(data,target){ target.empty(); $.each(data,function(idx,item){ $("<option value='"+item+"'>"+item+"</option>").appendTo(target); }) } createPageSize(pageSizeList,$("#pageSize")); $("#pageSize").val($("#showPageSize").text()); function inArray(data,arr){ var flag=false; $.each(arr,function(idx,item){ if(item==data){ flag=true; return false; } }) return flag; } </script>
十四. user.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="${pageContext.request.contextPath}/JS/bootstrap/css/bootstrap.min.css" type="text/css"/> <script type="text/javascript" src="${pageContext.request.contextPath}/JS/jquery/jquery-3.1.0.min.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/JS/bootstrap/js/bootstrap.min.js"></script> <title>显示列表信息</title> </head> <body> <div class="container"> <!--这个查询的 id的值 一定要是pageForm,不能变。--> <s:form id="pageForm" class="form-inline" action="User_list.action"> <div class="row"> <!-- 这是查询搜索的框 --> <div class="text-info col-md-1">查询搜索:</div> <div class="col-md-3"> <div class="row"> <label for="loginName" class="col-md-6 control-label text-right">用户名:</label> <div class="col-md-6"> <s:textfield class="form-control inputClass" id="userName" name="userName" value="%{userName}" cssStyle="width:150px;"> </s:textfield> </div> </div> </div> <div class="form-group pull-right col-sm-1"> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span>查询结果 </button> </div> </div> <div class="row"> <table class="table table-bordered table-hover"> <caption>查看用户信息</caption> <thead> <tr> <th class="col-xs-2">姓名</th> <th class="col-xs-2">性别</th> <th class="col-xs-2">年龄</th> <th class="col-xs-4" colspan="3">相关操作 <span style="padding-left:40px"> <a href="#">添加按钮</a> </span> </th> </tr> </thead> <tbody> <s:iterator value="recordList" var="user"> <tr> <td>${user.name}</td> <td>${user.sex}</td> <td>${user.age}</td> <td> <a href="#">查看详情</a> <a href="#">修改</a> <a href="#">删除</a> </tr> </s:iterator> </tbody> </table> </div> <!--添加分页信息,注意路径--> <%@ include file="pageView.jspf"%> </s:form> </div> </body> </html>
十五 启动服务器,查看效果
具体的源代码已经上传,可于: 下载。
谢谢!!!