小言_互联网的博客

【Java39】综合案例:增删改,分页

405人阅读  评论(0)


1.删除:href=“javascript:void(0);”


如下绿色第一行不走,走第二行。QueryListServlet会自动跳转到list.jsp。

package com.itheima.manager.web;
import com.itheima.manager.service.UserService;
import com.itheima.manager.service.impl.UserServiceImpl;
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 java.io.IOException;

@WebServlet(urlPatterns = "/DeteleServlet")
public class DeteleServlet extends HttpServlet {
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        String id = request.getParameter("id");  //先写=号右边.val回车,自动左边
        //list.jsp中href="/DeteleServlet?id=${user.id} 的id
        UserService service = new UserServiceImpl();
        service.deleteUser(id); //不需要返回值
        
        //request.getRequestDispatcher("/QueryListServlet").forward(request,response); 
        request.getRequestDispatcher("/QueryPageServlet ").forward(request,response); 
    }
}


2.添加:主键自增设为null,BeanUtils

name,value自动拼接,表单提交和文件上传常用post。

//add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- HTML5文档-->
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
    <!-- 指定字符集 -->
    <meta charset="utf-8">
    <!-- 使用Edge最新的浏览器的渲染方式 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
    width: 默认宽度与设备的宽度相同
    initial-scale: 初始的缩放比,为1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <title>添加用户</title>
    <!-- 1. 导入CSS的全局样式 -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. 导入bootstrap的js文件 -->
    <script src="js/bootstrap.min.js"></script>
</head>

<!--1111111111111111111111111111111111111111111111111111111111111111111111111111111111-->
<body>
<div class="container text-left">
    <center><h3>添加联系人页面</h3></center>

 
    <form action="/AddServlet" method="post" class="form-horizontal">  <!--这行最重要-->
        <div class="form-group">
            <label class="col-lg-2 control-label" for="name">姓名:</label>
           <div class="col-lg-8">
               <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
           </div>
            <label class="col-lg-2 control-label" id="nameMsg"></label>
        </div>

        <div class="form-group">
            <label class="col-lg-2 control-label">性别:</label>
            <div class="col-lg-3">
                <input type="radio" name="sex" value="" checked="checked"/></div>
            <div class="col-lg-3">
                <input type="radio" name="sex" value=""/></div>
            <label class="col-lg-2 control-label" id="sexMsg"></label>
        </div>

        <div class="form-group">
            <label for="age" class="control-label col-lg-2">年龄:</label>
            <div class="col-lg-8">
                <input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄">
            </div>
        </div>

        <div class="form-group">
            <label for="jiguan" class="col-lg-2 control-label">籍贯:</label>
            <div class="col-lg-8">
                <select name="address" class="form-control" id="jiguan">
                    <option value="广东">广东</option>
                    <option value="广西">广西</option>
                    <option value="湖南">湖南</option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label for="qq" class="control-label col-lg-2">QQ:</label>
           <div class="col-lg-8">
               <input type="text" class="form-control" id="qq"  name="qq" placeholder="请输入QQ号码"/>
           </div>
        </div>

        <div class="form-group">
            <label for="email" class="col-lg-2 control-label">Email:</label>
           <div class="col-lg-8">
               <input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱地址"/>
           </div>
        </div>

        <div class="form-group" style="text-align: center">
            <input class="btn btn-primary" type="submit" value="提交" />
            <input class="btn btn-default" type="reset" value="重置" />
            <input class="btn btn-default" type="button" value="返回" />
        </div>
    </form>
</div>
</body>
</html>
package com.itheima.manager.web;
import com.itheima.manager.entity.User;
import com.itheima.manager.service.UserService;
import com.itheima.manager.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

@WebServlet(urlPatterns = "/AddServlet")
public class AddServlet extends HttpServlet {
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           
        request.setCharacterEncoding("utf-8"); //post请求中文乱码
      /*  //获取请求参数
        Integer age = Integer.parseInt(request.getParameter("age"));  // ()里返回string类型
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String address = request.getParameter("address");
        String qq = request.getParameter("qq");
        String email = request.getParameter("email");        
        //传到service层,参数太多,封装到JavaBean
        User user = new User();
        user.setAge(age);
        user.setName(name);
        user.setAddress(address);
        user.setQq(qq);
        user.setEmail(email);
        user.setSex(sex);*/
        //如上想到反射,行映射器:下面用BeanUtils,原理一样。
        
//11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
       /* Map<String, String[]> parameterMap = request.getParameterMap(); //获取所有的请求参数
        Set<String> set = parameterMap.keySet(); 
        for (String name : set) {  //name单例集合
            String[] value = parameterMap.get(name);
            System.out.println(name + "->" + Arrays.toString(value));
        }*/

        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        try {
   
            /*
            *   void populate(Object bean, Map properties) :  map中的数据填充到bean中
            *   原理: 反射
            *       1. 遍历map
            *           name = 瘪三
            *       2. 反射
             *          clazz = user.getClass();
             *          setName = clazz.getMethod("set" + "Name",String.class);
             *          setName.invoke(user,"瘪三"); //set进user里,如【Mysql5】第3章
             * 
             *    注意:  BeanUtils
             *      1. 类必须是javaBean(规范必须有set方法)
             *      2. 属性名和参数的key必须一致
             * */
            BeanUtils.populate(user,parameterMap);
        }catch (Exception e) {
   
            e.printStackTrace();
        }

//111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111        
        UserService service = new UserServiceImpl();
        service.addUser(user); 
        request.getRequestDispatcher("/QueryListServlet").forward(request,response); //刷新数据
    }
}

如下是name单例集合遍历



3.修改:${user.id}


如下list.jsp修改按钮。

package com.itheima.manager.web;
import com.itheima.manager.entity.User;
import com.itheima.manager.service.UserService;
import com.itheima.manager.service.impl.UserServiceImpl;
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 java.io.IOException;

@WebServlet(urlPatterns = "/QuerySingleServlet")
public class QuerySingleServlet extends HttpServlet {
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        String id = request.getParameter("id");

        UserService service = new UserServiceImpl();
        User user = service.querySingleUser(id);
        System.out.println("user:" + user);

        request.setAttribute("user",user);
        request.getRequestDispatcher("/update.jsp").forward(request,response);
    }
}

点击前端修改按钮,idea打印如下。

如下进行回显。

//update.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
    <head>
    	<base href="<%=basePath%>"/>
        <!-- 指定字符集 -->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>修改用户</title>
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <script src="js/jquery-2.1.0.min.js"></script>
        <script src="js/bootstrap.min.js"></script>        
    </head>

<!--11111111111111111111111111111111111111111111111111111111111111111111111111111-->
    <body>
        <div class="container" style="width: 400px;">
        <h3 style="text-align: center;">修改联系人</h3>
        
        <form action="/UpdateServlet" method="post">
        <%--TODO: --%>
            <input type="hidden" name="id" value="${user.id}">
            
          <div class="form-group">
            <label for="name">姓名:</label>
            <input type="text" class="form-control" id="name" name="name"  value="${user.name}"
                   readonly="readonly" placeholder="请输入姓名" />
          </div>

          <div class="form-group">
            <label>性别:</label>
              <%--
                逻辑: ${user.sex == '男' ? "checked" :  ""}
              --%>
                <input type="radio" name="sex" value="男"  ${user.sex == '男' ? "checked" :  ""}/>男
                <input type="radio" name="sex" value="女" ${user.sex == '女' ? "checked" :  ""} />女
          </div>

          <div class="form-group">
            <label for="age">年龄:</label>
            <input type="text" class="form-control" id="age"  name="age" placeholder="请输入年龄"  value="${user.age}"/>
          </div>

          <div class="form-group">
            <label for="address">籍贯:</label>
             <select name="address" id="address" class="form-control" >
                <option value="广东" ${user.address == '广东' ? "selected" :  ""} >广东</option>
                <option value="广西" ${user.address == '广西' ? "selected" :  ""} >广西</option>
                <option value="湖南" ${user.address == '湖南' ? "selected" :  ""} >湖南</option>
            </select>
          </div>

          <div class="form-group">
            <label for="qq">QQ:</label>
            <input type="text" id="qq" class="form-control" name="qq" placeholder="请输入QQ号码" value="${user.qq}"/>
          </div>

          <div class="form-group">
            <label for="email">Email:</label>
            <input type="text" id="email" class="form-control" name="email" placeholder="请输入邮箱地址" value="${user.email}"/>
          </div>

             <div class="form-group" style="text-align: center">
                <input class="btn btn-primary" type="submit" value="提交" />
                <input class="btn btn-default" type="reset" value="重置" />
                <input class="btn btn-default" type="button" value="返回"/>
             </div>
        </form>
        </div>
    </body>
</html>

如下id设为hidden,即用户不可见,但服务器知道。

package com.itheima.manager.web;
import com.itheima.manager.entity.User;
import com.itheima.manager.service.UserService;
import com.itheima.manager.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(urlPatterns = "/UpdateServlet")
public class UpdateServlet extends HttpServlet {
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
   
            BeanUtils.populate(user,map); //是apache里,不是spring里
        } catch (Exception e) {
   
            e.printStackTrace();
        }

        UserService service = new UserServiceImpl();
        service.updateUser(user);
        request.getRequestDispatcher("/QueryListServlet").forward(request,response);
    }
}

4.分页:this.value,index=offset

如下count每页都一样,index=offset。

如下方案A不行,因为list.jsp不是同一个,B覆盖A(刷新页面)。背景色在bootstrap中就是class=“active”。

如下按钮个数要动态显示。count是每页显示的个数,btncount是按钮数量,/是整除。

onchange: 当选项改变时触发,省级联动。

4.1 前端

https://v3.bootcss.com/components/#pagination 找到分页组件,复制到最后面,nav就是div占满整个区域。

如下在list.jsp中,QueryPageServlet传来page,如下第一行是EL表达式写法,第二行往后是JSTL标签写法,两种方法都一样。下面page==1,2,3,4,5都要删除,因为没有动态显示。

//list.jsp,前面不变,尾部添加
    <nav aria-label="Page navigation" class="text-center" >
        <ul class="pagination pagination-lg">

            <c:if test="${page == 1}"> 
                <li class="disabled">   <!-- 上一页 《 按钮disabled变灰色-->
                    <a href="javascript:;" aria-label="Previous">   <!--点击事件禁了-->
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            </c:if>
            //没有上一块内容,当page<=1时就被隐藏了
            
<!--1111111111111111111111111111111111111111111111111111111111111111111111111111111111-->
            <c:if test="${page > 1}">   <!--page不能为0,offset为负索引了-->
                <li>
                    <a href="/QueryPageServlet?page=${page-1}&count=${count}" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            </c:if>
          //上面两块内容都为 《 按钮 显示
          
<!--111111111111111111111111111111111111111111111111111111111111111111111111111111111-->
            <%--TODO:
		1. 问题: 我们发现按钮数量太多了
		2. 解决: 参照百度,总共10个按钮, (前5后4)
		3. 逻辑
			1. pageCount <= 10
				1. begin = 1
				2. end = pageCount
			2. pageCount > 10
				1. begin = page - 5
				2. end = page + 4
				3. 越界
					1. begin < 1
						1. begin = 1
						2. end = 10
					2. end > pageCount
						1. end = pageCount
						2. begin = pageCount-9
            --%>
            <c:forEach var="i" begin="1" end="${btnCount}">   <!--按钮个数动态显示-->
                <li <c:if test="${page == i}">class='active' </c:if> ><a href="/QueryPageServlet?page=${i}&count=${count}">${i}</a></li>
            </c:forEach>

<!--11111111111111111111111111111111111111111111111111111111111111111111111111111111111--> 
          //下面内容是 》 按钮        
           <c:if test="${page < count}">   <!--每页显示数量动态化-->
               <li>
                   <a href="/QueryPageServlet?page=${page+1}&count=${count}" aria-label="Next">
                       <span aria-hidden="true">&raquo;</span>   
                   </a>
               </li>
           </c:if>

<!--11111111111111111111111111111111111111111111111111111111111111111111111111111111111-->
            <li>     
                <select onchange="method02(this.value)" class="btn-lg btn-success">
                    <option value="5" ${count == 5? "selected" : ""}>每页显示5条数据</option>
                    <option value="10" ${count == 10? "selected" : ""} >每页显示10条数据</option>
                    <option value="15" ${count == 15? "selected" : ""} >每页显示15条数据</option>
                </select>
            </li>
        </ul>
    </nav>
</div>
</body>
</html>
<script>
    function method02(value) {
     
       location.href = "/QueryPageServlet?page=1&count=" + value
    }
</script>

//index.jsp 前面不变,这里修改原因是一进来只要显示5页就行,其他增删改也要改一下。
  <div align="center">
  	<%--<a
	  href="/QueryListServlet" style="text-decoration:none;font-size:33px">查询所有用户信息
	</a>--%>
        <a
                href="/QueryPageServlet?page=1&count=5" style="text-decoration:none;font-size:33px">查询所有用户信息
        </a>
  </div>
  </body>
</html>

4.2 web

package com.itheima.manager.web;
import com.itheima.manager.entity.User;
import com.itheima.manager.service.UserService;
import com.itheima.manager.service.impl.UserServiceImpl;
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 java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/QueryPageServlet")
public class QueryPageServlet extends HttpServlet {
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        //1. 接收请求
        int page = 1;
        int count = 5;
        String pageStr = request.getParameter("page"); //传参就用你传来的参数,不传参默认第一页,每页显示5条
        String countStr = request.getParameter("count");
        if(pageStr != null && countStr != null){
   
            page = Integer.parseInt(pageStr);   //前端传来字符串,因为要计算,所以转为int
            count = Integer.parseInt(countStr);
        }
        int offset = (page-1) * count;        
        UserService service = new UserServiceImpl();
        List<User> list = service.pageQuery(offset,count); //查询用户数据,不需要page了,用到上面得到的offset

        int sum = service.findUserSum();
        int btnCount = sum%count==0? sum/count : sum/count+1;

        request.setAttribute("list",list);
        request.setAttribute("page",page); //按钮点击显示效果
        request.setAttribute("btnCount",btnCount); //按钮个数
        request.setAttribute("count",count); //每页显示的数量
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }
}


转载:https://blog.csdn.net/weixin_43435675/article/details/113829359
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场