1.在index的表单中转向newCustomer.jsp
<form action="query.do", method="post ">
<table>
<tr>
<td>Name:</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">Create New Customer</a></td>
</tr>
</table>
</form>
2.newCustomer.jsp中进行
<%@ page import="MVCCases.Customer" %>
<%@ page import="java.util.List" %><%--
Created by IntelliJ IDEA.
User: Skye
Date: 2017/12/11
Time: 9:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Object message = request.getAttribute("message");
if(message!= null){
%>
<br>
<font color="red"><%=message%></font>
<br>
<br>
<br>
<%
}
%>
<form action="add.do" method="post">
<table>
<tr>
<td>CustomerName:</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>
<%--colspan="2"用来指定单元格横向跨越的列数 横跨两列--%>
<%--rowspan的作用是指定单元格纵向跨越的行数--%>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</body>
</html>
3.CustomerServlet中进行add()方法的编写
注意区分有无重复姓名,若有则进行转发,若么有,则进行重定向
private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取添加的顾客的信息
String name = req.getParameter("name");
String address = req.getParameter("address");
String phone = req.getParameter("phone");
long count = customerDAO.getCountWithName(name);
if(count > 0){
req.setAttribute("message", "用户名" + name + "已被占用");
req.getRequestDispatcher("/newCustomer.jsp").forward(req, resp);
return;
}
//2.创建一个Customer对象
Customer customer = new Customer(name, address, phone);
customerDAO.save(customer);
//若添加成功,则重定向到成功页面
resp.sendRedirect("success.jsp");
}
5.重定向的success.jsp
<%@ page import="MVCCases.Customer" %>
<%@ page import="java.util.List" %><%--
Created by IntelliJ IDEA.
User: Skye
Date: 2017/12/11
Time: 9:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>操作成功</h4>
<h4><a href="index.jsp">return!</a></h4>
</body>
</html>