day15JDBC大案例问题

来源:互联网 发布:数据挖掘 薪酬 前景 编辑:程序博客网 时间:2024/06/08 03:42

思想:

1.修改页面显示原来的数据如何不从数据库查询直接从提交的页面获取而又不与其他提交的数据冲突?

2.分页查询一个比较简洁的方法是通过在Service里来封装数据!?!而不是都用request域里来存储数据!仅就是为了不让request域里的数据不多?不乱?其实最关键的一点,还是通过设定了一个JavaBean来封装分页需要的基本的5个数据:pageSize, totalCount, List, currPage, totalPage!这样才符合面向对象的思想,这样操作起来也是有条理很多!

技巧:

8.自己写的修改页面返回原来的值显示,select和checked都有问题!!!!!!!

显示页面的问题注意会用浏览器开发功能进行调试!

3.超链接提交数据也只能在地址后加问号,然后写值。

4.一个表单里有好几个按钮,通过JS来使得表单的提交可能有多个路径的选择,如表单里添加全选的功能!如下面老师代码的subquery();

问题:

13.对于Map

就是只会接收里name=”“的值!值是value=”“。封装成String 数组!

注意,对于Checked选项,是由数组形式传过来的,只能接收到第一个值!

​ 需要这样处理:String[] arrs = request.getParameterValues(“hobby”);

12.加了date类型,查询有问题!就是数据库日期不能为0000-00-00!!!这样就好了!

java.sql.SQLException: Value ‘0000-00-00’ can not be represented as java.sql.Date Query: select * from student Parameters: []

答:http://blog.csdn.net/bz201/article/details/50685403

http://blog.csdn.net/lizhihai_99/article/details/5648219

​ Datetimes with all-zero components (0000-00-00 …) — These values can not be represented reliably in Java. Connector/J 3.0.x always converted them to NULL when being read from a ResultSet.

Connector/J 3.1 throws an exception by default when these values are encountered as this is the most correct behavior according to the JDBC and SQL standards. This behavior can be modified using the zeroDateTimeBehavior configuration property. The allowable values are:

exception (the default), which throws an SQLException with an SQLState of S1009.

convertToNull, which returns NULL instead of the date.

round, which rounds the date to the nearest closest value which is 0001-01-01.

Starting with Connector/J 3.1.7, ResultSet.getString() can be decoupled from this behavior via noDatetimeStringSync=true (the default value is false) so that you can retrieve the unaltered all-zero value as a String. It should be noted that this also precludes using any time zone conversions, therefore the driver will not allow you to enable noDatetimeStringSync and useTimezone at the same time.

11.人性化互动的问题,功能完善

​ a.注意分页查询还有挺多的人性化细节注意点!!!如在当前页就不能点当前页了,在第一页就不能再前面页了!等!

​ b.添加失败不能很好地提示!!都能添加成功!日期格式转换不成功则添加为空了!

10.首次写的时候,没有保住PageBean的完整性!就是没有把握住service层的分割我没有把PageBean中的List进行封装,就直接将DaoImpl里的查询封装的数据返回了!!!

1.在注册,添加新数据时?用BeanUtil来封装数据还不完全理解?!!这个封装数据需要在Servlet里进行!!因为servlet就是Controler,控制者,用于逻辑处理,数据接收。

2.转发与重定向的问题:仍然关键点是request数据是否要用的问题。

​ a.添加完后跳转回全列表,居然不能显示所有数据!!!

需要转发或重定向到:AllStudentServlet,因为这里会再次执行查询所有的操作,同时显示页面是通过EL来获取的,同时将查询的所有数据放入到一次请求的域里!才能让Student_list.jsp获取到!而直接跳转进Student_list.jsp则没有数据显示!

response.sendRedirect(“/day13_JDBCbig_self/AllStudentServlet“);

​ b.真是注意了,分页查询不能用重定向!!!!因为请求的数据经过转发后就丢失了!而进行新的数据添加时,刷新需要用重定向,不会出现转发而再次保存原来的数据

​ c.在修改编辑页面不能返回原来的页面??可以,已经解决

4.如何进入编辑修改页面而同时带过来显示原来的数据??!!因为这里有一个链接是提交获取所有的查询!

通过单次查询来返回具体实例,然后放进request域里!!!然后再用EL来获取!

注意,编辑修改页面修改提交后要传递id!!!回去对应修改!!隐藏的id!注意做界面显示的时候会用浏览器的调试功能来测试 !

3.一个在Servlet里对数据封装的问题,注意对数据进行封装的步骤!!还不是很理解!!类BeanUtils!

为什么直接将hobby拿出来封装却没有问题?不与前面的request.getParameterMap()冲突?

对数组的封装只封装了第一个元素!!!后面的元素就封装不进去,要自己转为字符串。

另外,BeanUtils只能封装基本数据的类型!

public class AddCustomerServlet extends HttpServlet {    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        try{            // 接收数据            request.setCharacterEncoding("UTF-8");            Map<String,String[]> map = request.getParameterMap();            // 封装数据            Customer customer = new Customer();            // 类型转换:            ConvertUtils.register(new MyDateConverter(), Date.class);            BeanUtils.populate(customer, map);//注意了,这里还是装进去了数据!只装进去了第一个数!            // 手动封装爱好的属性:            String[] arrs = request.getParameterValues("hobby");            String arr = Arrays.toString(arrs);// [aaa,bbb,ccc]            String hobby = arr.substring(1, arr.length()-1);            customer.setHobby(hobby);            // 调用业务层处理数据            CustomerService customerService = new CustomerServiceImpl();            customerService.save(customer);

一个表单里多个请求链接(老师代码),路径提取到JS中,是可以更灵活地拓展!

一是删除,二是高级多条件搜索,三是修改!!

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!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">    function delCustomer(cid){        var flag = confirm("您确定要删除该记录吗?");        if(flag == true){            window.location.href="${ pageContext.request.contextPath }/DeleteCustomerServlet?cid="+cid;        }    }    function subQuery(){        document.getElementById("form1").action="${ pageContext.request.contextPath }/SearchCustomerServlet";        document.getElementById("form1").submit();    }</script></head><body><h1>客户列表页面</h1><form id="form1" action="" method="post">  <TABLE border="1" width="1000">  <TR>    <TD colspan="9">        按姓名:<input type="text" name="cname" value="${ param.cname }">&nbsp;        按性别:        <select name="sex">            <option value="">-请选择-</option>            <option value="男" <c:if test="${ param.sex == '男' }">selected</c:if>>男</option>            <option value="女" <c:if test="${ param.sex == '女' }">selected</c:if>>女</option>        </select>&nbsp;        <input type="button" value="查询" onclick="subQuery()">&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="删除" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="${ pageContext.request.contextPath }/customer/add.jsp">添加</a>    </TD>  </TR>  <TR>    <TD><input type="checkbox" ></TD>    <TD>客户编号</TD>    <TD>客户姓名</TD>    <TD>客户性别</TD>    <TD>客户邮箱</TD>    <TD>客户生日</TD>    <TD>客户爱好</TD>    <TD>客户籍贯</TD>    <TD>操作</TD>  </TR>  <c:forEach var="c" items="${ list }">      <TR>        <TD><input type="checkbox" ></TD>        <TD>${ c.cid }</TD>        <TD>${ c.cname }</TD>        <TD>${ c.sex }</TD>        <TD>${ c.email }</TD>        <TD>${ c.birthday }</TD>        <TD>${ c.hobby }</TD>        <TD>${ c.city }</TD>        <TD>        <a href="${ pageContext.request.contextPath }/EditCustomerServlet?cid=${ c.cid }">编辑</a>|        <a href="#" onclick="delCustomer(${ c.cid })">删除</a>        </TD>      </TR>  </c:forEach>  </TABLE>  </form></body></html>

下面是学习吸收:

条件混合查询的sql语句拼接:

    // DAO中高级查询客户的方法:    public List<Customer> search(Customer customer) throws SQLException {        QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());        String sql = "select * from customer where 1=1";        // 创建一个集合,集合用于保存sql中参数的值。        List<Object> paramList = new ArrayList<Object>();        if(customer.getCname()!=null && !"".equals(customer.getCname())){            sql += " and cname like ?";            // 添加参数:            paramList.add("%"+customer.getCname()+"%");        }        if(customer.getSex()!=null && !"".equals(customer.getSex())){            sql += " and sex = ?";            paramList.add(customer.getSex());        }        System.out.println("客户名称==="+customer.getCname());        System.out.println("客户性别==="+customer.getSex());        System.out.println("sql======="+sql);        // 将参数的集合转成数组:        Object[] params = paramList.toArray();        List<Customer> list = queryRunner.query(sql, new BeanListHandler<Customer>(Customer.class), params);        return list;    }

分页查看

10.分页功能需要传递至少5个参数:

当前页数:currPage

每页显示记录数:pageSize

总记录数:totalCount

​ * select count(*) from customer;

总页数:totalPage

每页显示数据集合:list

一些js技巧

<script type="text/javascript">    function delCustomer(cid){        var flag = confirm("您确定要删除该记录吗?");        if(flag == true){            window.location.href="${ pageContext.request.contextPath }/DeleteCustomerServlet?cid="+cid;        }    }    function subQuery(){     //这是提交查询功能        document.getElementById("form1").action="${ pageContext.request.contextPath }/SearchCustomerServlet";        document.getElementById("form1").submit();    }</script>

业务层封装

@Override    // 业务层的分页查询客户的方法    public PageBean<Customer> findByPage(int currPage) throws SQLException {        // 创建一个PageBean对象        PageBean<Customer> pageBean = new PageBean<Customer>();        // 封装pageBean中数据:        // 封装当前的页数:        pageBean.setCurrPage(currPage);        // 封装每页显示的记录数:        int pageSize = 3;        pageBean.setPageSize(pageSize);        // 封装总记录数:        CustomerDao customerDao = new CustomerDaoImpl();        int totalCount = customerDao.findCount();        pageBean.setTotalCount(totalCount);        // 封装总页数: Math.ceil();        /*int totalPage = 0;        if(totalCount % pageSize == 0){            totalPage = totalCount / pageSize;        }else{            totalPage = totalCount / pageSize + 1;        }*/        double tc = totalCount;        Double num = Math.ceil(tc / pageSize);        pageBean.setTotalPage(num.intValue());        // 封装每页显示的数据的集合。        int begin = (currPage - 1) * pageSize;        List<Customer> list = customerDao.findByPage(begin,pageSize);        pageBean.setList(list);        return pageBean;    }

控制servlet

package com.itheima.web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.itheima.domain.Customer;import com.itheima.domain.PageBean;import com.itheima.service.CustomerService;import com.itheima.service.impl.CustomerServiceImpl;/** * 分页显示客户的SErvlet */public class ListCustomerByPageServlet extends HttpServlet {    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        try{            // 接收参数:            int currPage = Integer.parseInt(request.getParameter("currPage"));            // 在页面显示当前页数,每页显示数据的集合,总页数等一些数据。            /** 在页面中需要后台的数据有很多,需要将每个数据都保存到request域中,带到页面上。            request.setAttribute("totalPage", totalPage);            request.setAttribute("currPage", currPage);            request.setAttribute("list", list);            * 这样的做法很麻烦的,可以将要在页面上需要的数据,封装到一个对象里。用request将这个数据带到页面。            */            // 调用业务层:            CustomerService customerService = new CustomerServiceImpl();            PageBean<Customer> pageBean = customerService.findByPage(currPage);            // 将pageBean的数据保存到request域中            request.setAttribute("pageBean", pageBean);            // 页面跳转            request.getRequestDispatcher("/customer/listByPage.jsp").forward(request, response);        }catch(Exception e){            e.printStackTrace();            throw new RuntimeException("分页查询失败!");        }    }    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doGet(request, response);    }}

数据封装类

package com.itheima.domain;import java.util.List;/** * 用于封装分页数据的Java类 * @author jt * */public class PageBean<T> {    private int currPage; // 当前页数    private int pageSize; // 每页显示记录数    private int totalCount; // 总记录数    private int totalPage; // 总页数    private List<T> list; // 每页显示的数据的集合。    public int getCurrPage() {        return currPage;    }    public void setCurrPage(int currPage) {        this.currPage = currPage;    }    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 getTotalPage() {        return totalPage;    }    public void setTotalPage(int totalPage) {        this.totalPage = totalPage;    }    public List<T> getList() {        return list;    }    public void setList(List<T> list) {        this.list = list;    }}

显示页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!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">    function delCustomer(cid){        var flag = confirm("您确定要删除该记录吗?");        if(flag == true){            window.location.href="${ pageContext.request.contextPath }/DeleteCustomerServlet?cid="+cid;        }    }    function subQuery(){        document.getElementById("form1").action="${ pageContext.request.contextPath }/SearchCustomerServlet";        document.getElementById("form1").submit();    }</script></head><body><h1>客户列表页面</h1><form id="form1" action="" method="post">  <TABLE border="1" width="1000">  <TR>    <TD colspan="8">        按姓名:<input type="text" name="cname" value="${ param.cname }">&nbsp;        按性别:        <select name="sex">            <option value="">-请选择-</option>            <option value="男" <c:if test="${ param.sex == '男' }">selected</c:if>>男</option>            <option value="女" <c:if test="${ param.sex == '女' }">selected</c:if>>女</option>        </select>&nbsp;        <input type="button" value="查询" onclick="subQuery()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="${ pageContext.request.contextPath }/customer/add.jsp">添加</a>    </TD>  </TR>  <TR>    <TD>客户编号</TD>    <TD>客户姓名</TD>    <TD>客户性别</TD>    <TD>客户邮箱</TD>    <TD>客户生日</TD>    <TD>客户爱好</TD>    <TD>客户籍贯</TD>    <TD>操作</TD>  </TR>  <c:forEach var="c" items="${ pageBean.list }">      <TR>        <TD>${ c.cid }</TD>        <TD>${ c.cname }</TD>        <TD>${ c.sex }</TD>        <TD>${ c.email }</TD>        <TD>${ c.birthday }</TD>        <TD>${ c.hobby }</TD>        <TD>${ c.city }</TD>        <TD>        <a href="${ pageContext.request.contextPath }/EditCustomerServlet?cid=${ c.cid }">编辑</a>|        <a href="#" onclick="delCustomer(${ c.cid })">删除</a>        </TD>      </TR>  </c:forEach>    <TR>    <TD colspan="8">        第${ pageBean.currPage }/${ pageBean.totalPage } 页&nbsp;&nbsp;        每页显示${ pageBean.pageSize }条&nbsp;&nbsp;        总记录数:${ pageBean.totalCount }条&nbsp;&nbsp;        <c:if test="${ pageBean.currPage != 1 }">            <a href="${ pageContext.request.contextPath }/ListCustomerByPageServlet?currPage=1">[首页]</a> &nbsp;&nbsp;            |<a href="${ pageContext.request.contextPath }/ListCustomerByPageServlet?currPage=${ pageBean.currPage - 1}">[上一页]</a>&nbsp;&nbsp;        </c:if>        &nbsp;&nbsp;        <c:forEach var="i" begin="1" end="${ pageBean.totalPage }">            <c:if test="${ pageBean.currPage == i }">                ${ i }&nbsp;            </c:if>            <c:if test="${ pageBean.currPage != i }">                <a href="${ pageContext.request.contextPath }/ListCustomerByPageServlet?currPage=${ i }">${ i }</a>&nbsp;            </c:if>        </c:forEach>        &nbsp;&nbsp;        <c:if test="${ pageBean.currPage != pageBean.totalPage }">            |<a href="${ pageContext.request.contextPath }/ListCustomerByPageServlet?currPage=${ pageBean.currPage + 1}">[下一页]</a>&nbsp;&nbsp;            |<a href="${ pageContext.request.contextPath }/ListCustomerByPageServlet?currPage=${ pageBean.totalPage}">[尾页]</a>        </c:if>    </TD>    </TR>  </TABLE>  </form></body></html>

注意PageBean的泛型设置!

package com.itheima.domain;import java.util.List;/** * 用于封装分页数据的Java类 * @author jt * */public class PageBean<T> {    private int currPage; // 当前页数    private int pageSize; // 每页显示记录数    private int totalCount; // 总记录数    private int totalPage; // 总页数    private List<T> list; // 每页显示的数据的集合。    public int getCurrPage() {        return currPage;    }    public void setCurrPage(int currPage) {        this.currPage = currPage;    }    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 getTotalPage() {        return totalPage;    }    public void setTotalPage(int totalPage) {        this.totalPage = totalPage;    }    public List<T> getList() {        return list;    }    public void setList(List<T> list) {        this.list = list;    }   }
1 0
原创粉丝点击