javaEE13(网站第8章两个课后题)

1、对"jsp+servlet+javabean实现分页查询"功能做如下补充:

(1)记录批量删除:每个记录前添加复选框,点击批量删除,删除选中记录。

  1. 增加跳转到任意页功能。
  2. 用户可改变每页记录条数。

页面:

java 复制代码
<%@ page   pageEncoding="UTF-8" import="java.util.List,dao.StudentDao,entity.Student"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head><title>模糊</title>

<script>

function qingchu(){

    document.getElementById("sno").value='';

    document.getElementById("sname").value='';

    document.getElementById("sex").value='';

}

function jump1(pageNo){

    var queryForm=document.getElementById("queryForm");

    queryForm.pageNo.value=pageNo;

    queryForm.submit();

}

function jump2(pageNo){

    var pageNo1=document.getElementById("pageNo1").value;

    if(pageNo1!=""){

    jump1(pageNo1);

    }

}

function btSelectAllOnclick(obj) {  

    var isCheck=obj.checked;

    var inputs=document.getElementsByTagName("input");  

    for(var i=0;i<inputs.length;i++){  

        if(inputs[i].type=="checkbox" && inputs[i].id!="selectAll") //刷选出所有复选框  

        {  

            inputs[i].checked=obj.checked;

            if(isCheck==true){

            inputs[i].name="check";

            }else{

            inputs[i].name="user";

            }

        }  

    }  

}

function getCheckBox()  

{  

    var inputs=document.getElementsByTagName("input");  

    var chkInputs=new Array();  

    var j=0;  

    for(var i=0;i<inputs.length;i++)  

    {  

        if(inputs[i].type=="checkbox" && inputs[i].id!="selectAll") //刷选出所有复选框  

        {  

            chkInputs[j]=inputs[i];  

            j++;  

        }  

    }  

    return chkInputs;  

}

function toChkSon(obj)  

{  

var isCheck=obj.checked;

obj.name="check";

    if(isCheck==false) //单选复选框未选中 全选为未选  

    {  

        document.getElementById("selectAll").checked=false;

        obj.name="user";

        return ;  

    }  

  

    var chkInputs=getCheckBox();

    var j=0;  

    for(var i=0;i<chkInputs.length;i++)  

    {  

        if(chkInputs[i].checked==isCheck)  

            j++;  

        else  

            break;  

    }     

    if(j==chkInputs.length) //当所有复选框为同一状态时 赋值全选同一状态  

        document.getElementById("selectAll").checked=isCheck;  

}



function submitForm(){

    document.getElementById("queryForm").submit();

}

function pagesizee(){

    var pagesize=document.getElementById("pageSize").value;

    if(pagesize!=""&&pagesize!=null){

        document.getElementById("queryForm").submit();

    }

}





</script>

<style>

th,td{

border:2px solid gray;

padding:3px;

text-align:center;

}

table,form{

border-collapse:collapse;

margin:0 auto;

text-align:center;

}

#pageSwitch{

margin:5px;

text-align:center;

}



</style>

</head>

<body>



<form method="post" action="${pageContext.request.contextPath}/student" id="queryForm">

学号<input type="text" name="sno" id="sno" value="${param.sno}">

姓名<input type="text" name="sname" id="sname" value="${param.sname}">

性别<input type="text" name="sex" id="sex" value="${param.sex}">

<input type="button"  value="清除" onclick="qingchu()"/>

<input type="hidden" name="action" value="query3"/>

<input type="hidden" name="pageNo" value="1"/>

<input type="submit" value="查询"/>

<br>

<br>

<c:if test="${requestScope.recordCount==0}">

<div style="text-align:center">无记录</div>

</c:if>

<c:if test="${requestScope.recordCount>0}">



<table id="tab">

<tr>

<th><input type="checkbox"  id="selectAll" name="selectAll" onclick="btSelectAllOnclick(this)"/></th>

<th>序号</th><th>学号</th><th>姓名</th><th>性别</th><th>修改</th><th>删除</th>

</tr>

<c:forEach items="${studentList}" var="student" varStatus="status">

<tr>

<td><input type="checkbox" onclick="toChkSon(this);" value="${student.id}" id="user" name="user"></td>

<td>${status.index+1}</td>

<td>${student.sno}</td>

<td>${student.sname}</td>

<td>${student.sex}</td>

<td><a href="${pageContext.request.contextPath}/student/edit.jsp?id=${student.id}&sno=${student.sno}&sname=${student.sname}&sex=${student.sex}">修改</a></td>

<td><a href="${pageContext.request.contextPath}/student?id=${student.id}&action=delete" onclick="return confirm('确实要删除该记录吗?')">删除</a></td>

</tr>

</c:forEach>

</table>

<input type="button"  value="删除所选" onclick="submitForm()" />

<div id="pageSwitch">

 共有记录${recordCount}条, 第${pageNo}/${pageCount}页,

<c:if test="${pageNo>1}">

 <a href="javascript:jump1('1')">首页</a>

 <a href="javascript:jump1('${pageNo-1}')">上页</a>

</c:if>

<c:if test="${pageNo==1}">
   
   首页  上页

</c:if>

<c:if test="${pageNo<pageCount}">

   <a href="javascript:jump1('${pageNo+1}')">下页</a>

   <a href="javascript:jump1('${pageCount}')">末页</a>

</c:if>

 <c:if test="${pageNo==pageCount}">

   下页   末页

</c:if>

跳转到第<input type="text" name="pageNo1" id="pageNo1" value="" onclick="jump2('${pageNo}')">

页,每页<input type="text" name="pageSize" id="pageSize" value="" onclick="pagesizee()">

条

 </div>

 </c:if>

 </form>

 <%

String pagesize=request.getParameter("pageSize");

if(pagesize!=null&&pagesize!=""){

    session.setAttribute("pageSize",pagesize);

}

%>

</body>

</html>

Servlet:

java 复制代码
private void query3(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        request.setCharacterEncoding("UTF-8");

        String users[]=request.getParameterValues("check");

        StudentDao studentDao=new StudentDao();

        HttpSession session=request.getSession();

        if(users!=null){

            for(int i=0;i<users.length;i++){//循环删除被选中的数据

                try {

                studentDao.delete(Integer.parseInt(users[i]));

            } catch (Exception e) {

                e.printStackTrace();

            }

            }

        }

       

        try {

            String condition=" where 1=1 ";

            String sno=request.getParameter("sno");

            String sname=request.getParameter("sname");

            String sex=request.getParameter("sex");

            if(notEmpty(sno)) {

                condition+=" and sno like '%"+sno+"%' ";

            }

            if(notEmpty(sname)) {

                condition+=" and sname like '%"+sname+"%' ";

            }

            if(notEmpty(sex)) {

                condition+=" and sex like '%"+sex+"%' ";

            }

            int pageNo=1;

            int pageSize=10;

            try {

                pageNo=Integer.parseInt(request.getParameter("pageNo"));

            } catch (Exception e) {

            }

           

            String pagesize=request.getParameter("pageSize");

            String pagesize1=(String) session.getAttribute("pageSize");

            if(pagesize!= null && !pagesize.equals("")) {

            pageSize=Integer.parseInt(pagesize);

            }else if(pagesize1!= null && !pagesize1.equals("")) {

            pageSize=Integer.parseInt(pagesize1);

            }

            int recordCount=studentDao.getRecordCount(condition);

            if(recordCount>0){

                 List<Student> studentList=studentDao.query(condition,"",pageNo,pageSize);                     

                   int t1=recordCount%pageSize;;

                   int t2=recordCount/pageSize;

                   int pageCount=(t1==0?t2:t2+1);

                   request.setAttribute("pageNo", pageNo);

                   request.setAttribute("pageCount", pageCount);

                   request.setAttribute("studentList", studentList);

                  

            }

            request.setAttribute("recordCount", recordCount);

        request.getRequestDispatcher("/student/query3.jsp").forward(request,response);

           

           

           

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

       

    }

Dao:

java 复制代码
public void delete(int id) throws Exception{

         Connection conn = null;

         PreparedStatement ps = null;

         try {

            conn = JdbcUtil.getConnection();

            String sql = "delete from student where id=?";

            ps = conn.prepareStatement(sql);

            ps.setInt(1,id);

            ps.executeUpdate();

        }finally {JdbcUtil.free( null,ps, conn);}

       }

2、针对课程表数据库(数据库脚本下载)实现分页查询。同时按课程名、上课时间、上课地点、任课教师四列查询。

样例:http://47.93.11.179/test/courseServlet3

页面:

java 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8" import="java.util.List,dao.courseDao,entity.course"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<style>

  body{

      text-align:center;

  }

  th,td{

  border:2px solid gray;

  text-align:center;

  padding:3px 10px;

  }

  table{

  border-collapse:collapse;

  margin:0 auto;

  }

 </style>

 <script>

 function jump1(pageNo){

   document.getElementById("pageNo").value=pageNo;

   document.getElementById("form11").submit();

 }

 function qc(){

      document.getElementById("kcm").value="";

      document.getElementById("sksj").value="";

      document.getElementById("skdd").value="";

      document.getElementById("rkjs1").value="";

 }

 </script>

 <style>

 .odd{

 background-color:#E0EEEE;

 }

 </style>

</head>



<body>

 <h2>课程表分页查询</h2>

 <form action="${pageContext.request.contextPath}/courseServlet3" method="post" id="form11" >

  课程名<input name="kcm" value="${param.kcm}" id="kcm">

 上课时间<input name="sksj" value="${param.sksj}" id="sksj">

 上课地点<input name="skdd" value="${param.skdd}" id="skdd">

 任课教师<input name="rkjs1" value="${param.rkjs1}" id="rkjs1">

<input type="hidden" name="pageNo" id="pageNo" value="1"/>

<input type="submit" value="查询"/>

<input type="button" value="清除" onclick="qc()"/>

</form>

<br>

<c:if test="${requestScope.recordCount==0}">

<div style="text-align:center">无记录</div>

</c:if>

<c:if test="${requestScope.recordCount>0}">

<table>

<tr>

<th>学院</th><th>课序号</th><th>课程号</th><th>课程名</th><th>任课老师</th><th>上课时间</th><th>上课周次</th><th>上课地点</th><th>班级</th><th>年级</th><th>校区</th>

</tr>

<c:forEach items="${studentList}" var="student" varStatus="status">

<tr>

<td>${status.index+1}</td>

<td>${student.kxh}</td>

<td>${student.kch}</td>

<td>${student.kcm}</td>

<td>${student.rkjs1}</td>

<td>${student.sksj}</td>

<td>${student.skzc}</td>

<td>${student.skdd}</td>

<td>${student.bj}</td>

<td>${student.rs}</td>

<td>${student.xq}</td>

</tr>

</c:forEach>

</table>



<div id="pageSwitch">

 共有记录${recordCount}条, 第${pageNo}/${pageCount}页,

<c:if test="${pageNo>1}">

 <a href="javascript:jump1('1')">首页</a>

 <a href="javascript:jump1('${pageNo-1}')">上页</a>

</c:if>

<c:if test="${pageNo==1}">

  首页  上页

</c:if>

<c:if test="${pageNo<pageCount}">

   <a href="javascript:jump1('${pageNo+1}')">下页</a>

   <a href="javascript:jump1('${pageCount}')">末页</a>

</c:if>

 <c:if test="${pageNo==pageCount}">

   下页   末页

</c:if>



 </div>

 </c:if>

 <br>

</body>

</html>

Servlet:

java 复制代码
package servlet;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;



import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import dao.courseDao;

import entity.course;

@WebServlet("/courseServlet3")

public class CourseServlet extends HttpServlet{

  private static final long serialVersionUID = 1L;

    courseDao studentDao=new courseDao();

    public CourseServlet() {

        super();

        // TODO Auto-generated constructor stub

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

     // TODO Auto-generated method stub

     this.doPost(request, response);

  }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

     // TODO Auto-generated method stub

  response.setContentType("text/html;charset=UTF-8");

        request.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();

     try {

       String condition=" where 1=1 ";

       String kcm=request.getParameter("kcm");

       String sksj=request.getParameter("sksj");

       String skdd=request.getParameter("skdd");

       String rkjs1=request.getParameter("rkjs1");

       if(notEmpty(kcm)) {

         condition+=" and kcm like '%"+kcm+"%' ";

       }

       if(notEmpty(sksj)) {

         condition+=" and sksj like '%"+sksj+"%' ";

       }

       if(notEmpty(skdd)) {

         condition+=" and skdd like '%"+skdd+"%' ";

       }

       if(notEmpty(rkjs1)) {

         condition+=" and rkjs1 like '%"+rkjs1+"%' ";

       }

       int pageNo=1;

       int pageSize=10;

       try {

       pageNo=Integer.parseInt(request.getParameter("pageNo"));

       } catch (Exception e) {

       }

          int recordCount=studentDao.getRecordCount(condition);

         

       if(recordCount>0){

             List<course> studentList=studentDao.query(condition,"",pageNo,pageSize);             

            int t1=recordCount%pageSize;

            int t2=recordCount/pageSize;

            int pageCount=(t1==0?t2:t2+1);

            request.setAttribute("pageNo", pageNo);

            request.setAttribute("pageCount", pageCount);

           request.setAttribute("studentList", studentList);

       }

       request.setAttribute("recordCount", recordCount);

     request.getRequestDispatcher("courseServlet.jsp").forward(request,response);

     } catch (Exception e) {

       // TODO Auto-generated catch block

       e.printStackTrace();

     }

  }

    private boolean notEmpty(String s) {

     return s!=null&&!"".equals(s.trim());

  }

}

Dao:

java 复制代码
package dao;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.ArrayList;

import java.util.List;



import entity.course;

import util.JdbcUtil;

public class courseDao {

  public List<course>  query(String condition) throws Exception{

     Connection conn = null;

     PreparedStatement ps = null;

     ResultSet rs = null;

     List<course> studentList=new ArrayList<course>();

     try {

       conn = JdbcUtil.getConnection();

       String sql = "select * from course "+condition;

       ps=conn.prepareStatement(sql);

       rs=ps.executeQuery();

       while(rs.next()){

          course student=new course();

          student.setId(rs.getInt(1));

          student.setXy(rs.getString(2));

          student.setKxh(rs.getString(3));

          student.setKch(rs.getString(4));

          student.setKcm(rs.getString(5));

          student.setRkjs1(rs.getString(9));

          student.setSksj(rs.getString(11));

          student.setSkzc(rs.getString(12));

          student.setSkdd(rs.getString(13));

          student.setBj(rs.getString(14));

          student.setRs(rs.getString(16));

          student.setXq(rs.getString(17));

          studentList.add(student);

       }

     }finally {JdbcUtil.free(rs, ps, conn);}

     return studentList;

     }

     public int getRecordCount(String condition) throws Exception{

        

        Connection conn = null;

        PreparedStatement pst = null;

        ResultSet rs = null;

       int recordcount=0;

       try {

            conn = JdbcUtil.getConnection();

            String sql = "select count(*) from course "+condition;

            pst = conn.prepareStatement(sql);

            rs=pst.executeQuery();

            rs.next();

            recordcount=rs.getInt(1);

           

         }finally {

            JdbcUtil.free(rs, pst, conn);

         }

         return recordcount;

        

     }

     public List<course>  query(String condition,String order,int pageNo,int pageSize) throws Exception{

       Connection conn = null;

       PreparedStatement ps = null;

       ResultSet rs = null;

       List<course> studentList=new ArrayList<course>();

       try {

         conn = JdbcUtil.getConnection();

         String sql = "select * from course "+condition+order+" limit ?,?";

         ps=conn.prepareStatement(sql);

         ps.setInt(1, (pageNo-1)*pageSize);

         ps.setInt(2, pageSize);

         rs=ps.executeQuery();

         while(rs.next()){

            course student=new course();

            student.setId(rs.getInt(1));

            student.setXy(rs.getString(2));

            student.setKxh(rs.getString(3));

            student.setKch(rs.getString(4));

            student.setKcm(rs.getString(5));

            student.setRkjs1(rs.getString(9));

            student.setSksj(rs.getString(11));

            student.setSkzc(rs.getString(12));

            student.setSkdd(rs.getString(13));

            student.setBj(rs.getString(14));

            student.setRs(rs.getString(16));

            student.setXq(rs.getString(17));

            studentList.add(student);

         }

       }finally {JdbcUtil.free(rs, ps, conn);}

       return studentList;

        }



}
相关推荐
小灰灰__15 分钟前
IDEA加载通义灵码插件及使用指南
java·ide·intellij-idea
夜雨翦春韭19 分钟前
Java中的动态代理
java·开发语言·aop·动态代理
程序媛小果39 分钟前
基于java+SpringBoot+Vue的宠物咖啡馆平台设计与实现
java·vue.js·spring boot
追风林44 分钟前
mac m1 docker本地部署canal 监听mysql的binglog日志
java·docker·mac
芒果披萨1 小时前
El表达式和JSTL
java·el
duration~2 小时前
Maven随笔
java·maven
zmgst2 小时前
canal1.1.7使用canal-adapter进行mysql同步数据
java·数据库·mysql
跃ZHD2 小时前
前后端分离,Jackson,Long精度丢失
java
blammmp2 小时前
Java:数据结构-枚举
java·开发语言·数据结构
暗黑起源喵3 小时前
设计模式-工厂设计模式
java·开发语言·设计模式