MVC案例之新增与修改Customer

新增Customer

添加的流程
Add New Customer 超链接连接到 newcustomer.jsp
新建 newcustomer.jsp:

在 CustomerServlet 的 addCustomer 方法中:参见注释

上图一共有 2 个请求

加载页面的请求:发出请求到页面加载完成,request 结束

点击提交按钮,到 Serlvet,发出了一个 request,Serlvet 转发到 newcustomer.jsp 直到页面加载完成,整个过程一个 request

doPost(request, response) ---> request.getRequestDispatcher(path).forward(request, response);

private void addCustomer(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1.获取表单参数:name address phone
        String name = request.getParameter("name");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");

        // 2.检验 name 是否被占用
        // 2.1调用CustomerDAO的getCountWithName(String name) 获取 name 在数据库中是否存在
        long count = customerDAO.getCountWithName(name);
        // 2.2若返回值大于0,则响应 newcustomer.jsp 页面, 通过转发的方式响应newcustomer.jsp
        if (count > 0) {
            // 2.2.1要求页面显示一个错误消息: 用户名 name已经被占用,请重新选择,
            // 在request中放入一个属性message :用户名 name 已经被占用,请重新选择!
            // 在页面通过request.getAttribute("message")的方式显示
            request.setAttribute("message", "用户名 " + name + "已经被占用,请重新选择");

            // 2.2.2 newcustomer.jsp 的表单可以回显
            // 通过value="<%=request.getParameter("name") == null ? "" :
            // request.getParameter("name") %>"进行回显

            // 2.2.3结束方法:return
            request.getRequestDispatcher("/newcustomer.jsp").forward(request, response);
            return;
        }
        // 3.若验证通过,把表单参数封装为一个Customer 对象 customer
        Customer customer = new Customer(name, address, phone);

        // 4.调用CustomerDAO的 save(Customer customer) 执行保存操作
        customerDAO.save(customer);

        // 5.重定向的 success.jsp 页面:使用重定向可以避免表单的重复提交问题
        response.sendRedirect("success.jsp");
    }

newcustomer.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
    <%
        Object msg = request.getAttribute("message");
        if (msg != null) {
    %>
    <br>
    <font color="red"><%=msg%></font>
    <br>
    <br>
    <%
        }
    %>
    <form action="addCustomer.do" method="post">
        <table>
            <tr>
                <td>CustomerNam:</td>
                <td><input type="text" name="name"
                    value="<%=request.getParameter("name") == null ? "" : request.getParameter("name")%>" /></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><input type="text" name="address"
                    value="<%=request.getParameter("address") == null ? "" : request.getParameter("address")%>" /></td>
            </tr>
            <tr>
                <td>Phone:</td>
                <td><input type="text" name="phone"
                    value="<%=request.getParameter("phone") == null ? "" : request.getParameter("phone")%>" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

修改:
先显示(SELECT 操作)修改的页面,再进行修改(update)

显示修改页面

Update 的超链接:<a href="edit.do?id=<%= customer.getId() %>">UPDATE</a>

edit 方法: 

private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String forwardPath = "/error.jsp";// 初始值
        // 1.获取请求参数 id
        String idStr = request.getParameter("id");
        // 2.调用CustomerDAO 的 customerDAO.get(id) 获取 id 对应的Customer 对象customer
        try {
            Customer customer = customerDAO.get(Integer.parseInt(idStr));
            if (customer != null) {// 当customer为null是转到 error.jsp
                forwardPath = "/updatecustomer.jsp";
                // 3.将customer放入request 中
                request.setAttribute("customer", customer);
            }
        } catch (Exception e) {
        }
        // 4.响应updatecustomer.jsp 页面: 转发
        request.getRequestDispatcher(forwardPath).forward(request, response);
    }

JSP 页面:

获取请求域中的 Customer 对象,调用对应的字段的 get 方法来显示值。

使用隐藏域来保存要修改的 Customer 对象的 id:<input type="hidden" name="id" value=“<%= customer.getId() %>"/>

使用隐藏域来保存 oldName:<input type="hidden" name=“oldName" value=“<%= customer.getName() %>"/>

关于隐藏域:和其他的表单域一样可以被提交到服务器,只不过在额页面上不显示

提交到 update.do

CustomerServlet

package com.aff.mvcapp.servlet;
import java.io.IOException;
import java.lang.reflect.Method;
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 com.aff.mvcapp.dao.CriteriaCustomer;
import com.aff.mvcapp.dao.CustomerDAO;
import com.aff.mvcapp.dao.impl.CustomerDAOImpl;
import com.aff.mvcapp.domian.Customer;

@WebServlet("/customerServlet")
public class CustomerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private CustomerDAO customerDAO = new CustomerDAOImpl();

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 获取ServletPath: /edit.do 或 addCustomer.do
        String servletPath = request.getServletPath();
        // 2.去除 / 和 .do 得到类似于 edit 或 addCustomer 这样的字符串
        String methodName = servletPath.substring(1);
        methodName = methodName.substring(0, methodName.length() - 3);

        try {
            // 3.利用反射获取 methodName 对应的方法
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
                    HttpServletResponse.class);
            // 4.利用反射调用对应的方法
            method.invoke(this, request, response);
        } catch (Exception e) {
            // e.printStackTrace();
            // 可以有一些响应
            response.sendRedirect("error.jsp");
        }
    }

    private void addCustomer(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1.获取表单参数:name address phone
        String name = request.getParameter("name");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");

        // 2.检验 name 是否被占用
        // 2.1调用CustomerDAO的getCountWithName(String name) 获取 name 在数据库中是否存在
        long count = customerDAO.getCountWithName(name);
        // 2.2若返回值大于0,则响应 newcustomer.jsp 页面, 通过转发的方式响应newcustomer.jsp
        if (count > 0) {
            // 2.2.1要求页面显示一个错误消息: 用户名 name已经被占用,请重新选择,
            // 在request中放入一个属性message :用户名 name 已经被占用,请重新选择!
            // 在页面通过request.getAttribute("message")的方式显示
            request.setAttribute("message", "用户名 " + name + "已经被占用,请重新选择");

            // 2.2.2 newcustomer.jsp 的表单可以回显
            // 通过value="<%=request.getParameter("name") == null ? "" :
            // request.getParameter("name") %>"进行回显

            // 2.2.3结束方法:return
            request.getRequestDispatcher("/newcustomer.jsp").forward(request, response);
            return;
        }
        // 3.若验证通过,把表单参数封装为一个Customer 对象 customer
        Customer customer = new Customer(name, address, phone);

        // 4.调用CustomerDAO的 save(Customer customer) 执行保存操作
        customerDAO.save(customer);

        // 5.重定向的 success.jsp 页面:使用重定向可以避免表单的重复提交问题
        response.sendRedirect("success.jsp");

    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String forwardPath = "/error.jsp";// 初始值
        // 1.获取请求参数 id
        String idStr = request.getParameter("id");
        // 2.调用CustomerDAO 的 customerDAO.get(id) 获取 id 对应的Customer 对象customer
        try {
            Customer customer = customerDAO.get(Integer.parseInt(idStr));
if (customer != null) {// 当customer为null是转到 error.jsp
                forwardPath = "/updatecustomer.jsp";
                // 3.将customer放入request 中
                request.setAttribute("customer", customer);
            }
        } catch (Exception e) {
        }
        // 4.响应updatecustomer.jsp 页面: 转发
        request.getRequestDispatcher(forwardPath).forward(request, response);

    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.获取表单参数:id,name,addres, phone, oldName
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String oldName = request.getParameter("oldName");

        // 2.检查name是否被占用
        // 2.比较name和oldName 是否相同,若相同说明 name可用
        // 2.1若不相同, 则调用CustomerDAO 的 getCountWithName(String name) 获取 name在数据库中是否存在
        if (!oldName.equalsIgnoreCase(name)) {
            long count = customerDAO.getCountWithName(name);
            if (count > 0) {
                // 2.2若返回值大于0,则响应 updatecustomer.jsp 页面,
                // 通过转发的方式响应updatecustomer.jsp
                // 2.2.1要求页面显示一个错误消息: 用户名 name已经被占用,请重新选择,
                // 在request中放入一个属性message :用户名 name 已经被占用,请重新选择!
                // 在页面通过request.getAttribute("message")的方式显示
                request.setAttribute("message", "用户名" + name + "已经被占用,请重新选择!");

                // 2.2.2 updatecustomer.jsp 的表单可以回显
                // address, phone 显示提交表单的新的值,而 name 显示oldName, 而不是新提交的 name

                // 2.2.3结束方法:return
                request.getRequestDispatcher("/updatecustomer.jsp").forward(request, response);
                return;
            }
        }
        
        //3.若验证通过,则把表单参数封装为一个Customer 对象 customer
        Customer customer  = new Customer(name, address, phone);
        customer.setId(Integer.parseInt(id));//表单过来的 安全的
        
        //4.调用CustomerDAO 的 update(Customer customer) 执行更新操作
        customerDAO.update(customer);
        //5.重定向到    query.do
        response.sendRedirect("query.do");   
    }

private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String address = request.getParameter("address"); String phone = request.getParameter("phone"); CriteriaCustomer cc = new CriteriaCustomer(name, address, phone); // 1.调用 CustomerDAO 的 getForListWithCriteriaCustomer() 得到 Customer 的集合 List<Customer> customers = customerDAO.getForListWithCriteriaCustomer(cc); // 2.把 Customer 的集合放入 request 中 request.setAttribute("customers", customers); // 3.转发页面到 index.jsp 中( 不能使用重定向) request.getRequestDispatcher("/index.jsp").forward(request, response); } private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idstr = request.getParameter("id"); int id = 0; // try-catch的作用 , 防止恶意的输入, idStr 不能转为int类型,若出异常 id直接为0 try { id = Integer.parseInt(idstr); customerDAO.delete(id); } catch (Exception e) { } response.sendRedirect("query.do"); } }

updatecustomer.jsp

<%@page import="com.aff.mvcapp.domian.Customer"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
    <%
        Object msg = request.getAttribute("message");
        if (msg != null) {
    %>
    <br>
    <font color="red"><%=msg%></font>
    <br>
    <br>
    <%
        }
    %>

    <%
        String id = null;
        String oldName = null;
        String name = null;
        String address = null;
        String phone = null;
Customer customer
= (Customer) request.getAttribute("customer"); if(customer != null){ id = customer.getId()+""; name = customer.getName(); oldName = customer.getName(); address = customer.getAddress(); phone = customer.getPhone(); }else{ id = request.getParameter("id");//旧的 name = request.getParameter("oldName");//旧的 oldName = request.getParameter("oldName");//旧的 address = request.getParameter("address");//新的 phone = request.getParameter("phone");//新的 } %> <form action="update.do" method="post"> <input type="hidden" name="id" value="<%=id%>" /> <input type="hidden" name="oldName" value="<%=oldName%>" /> <table> <tr> <td>CustomerNam:</td> <td><input type="text" name="name" value="<%=name%>" /></td> </tr> <tr> <td>Address:</td> <td><input type="text" name="address" value="<%=address%>" /></td> </tr> <tr> <td>Phone:</td> <td><input type="text" name="phone" value="<%=phone%>" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit" /></td> </tr> </table> </form> </body> </html>

index.jsp

<%@page import="com.aff.mvcapp.domian.Customer"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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="scripts/jquery-1.12.3.js"></script>
<script type="text/javascript">
    $(function() {
        $(".delete").click(function() {
            //找到tr的第二个td也就是name,再获取它的value值
            var content = $(this).parent().parent().find("td:eq(1)").text();
            var flag = confirm("确定要删除" + content + "的信息吗")
            return flag;
        });
    });
</script>
</head>
<body>


    <form action="query.do" method="post">
        <table>
            <tr>
                <td>CustomerNam:</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><input type="text" name="address" /></td>
            </tr>
            <tr>
                <td>Phone:</td>
                <td><input type="text" name="phone" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="Query" /></td>
              <td><a href="newcustomer.jsp">Add New Customer</a></td>
            </tr>
        </table>
    </form>

    <br />
    <br />
    <br />
    <br />

    <%
        List<Customer> customers = (List<Customer>) request.getAttribute("customers");
        if (customers != null && customers.size() > 0) {
    %>
    <hr>
    <br>
    <br>
    <table border="1" cellpadding="10" cellspacing="0">
        <tr>
            <td>ID</td>
            <td>CustomersName</td>
            <td>Address</td>
            <td>Phone</td>
            <td>UPDATEDELETE</td>
        </tr>

        <%
            for (Customer customer : customers) {
        %>

        <tr>
            <td><%=customer.getId()%></td>
            <td><%=customer.getName()%></td>
            <td><%=customer.getAddress()%></td>
            <td><%=customer.getPhone()%></td>
            <td><a href="edit.do?id=<%=customer.getId()%>">UPDATE</a> 
                <a href="delete.do?id=<%=customer.getId()%>" class="delete">DELETE</a>
            </td>
        </tr>

        <%
            }
        %>

    </table>

    <%
        }
    %>

</body>
</html>
All that work will definitely pay off
原文地址:https://www.cnblogs.com/afangfang/p/12735024.html