javaweb:javabean在表單收集數(shù)據傳到servlet傳到jsp頁面由jsp:getProperty顯示
來源:我的學習筆記


代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8"
? ? pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>number one page</title>
</head>
<body>
<h4>請輸入客戶信息</h4>
<form action="CustomerServlet" method="post">
<table>
<tr><td>客戶名:</td><td><input type="text" name="name"></td></tr>
<tr><td>郵箱地址:</td><td><input type="text" name="email"></td></tr>
<tr><td>電話:</td><td><input type="text" name="phone"></td></tr>
<tr>
<td><input type="submit" value="確定"></td>
<td><input type="reset" value="重置"></td>
</tr>
</table>
</form>
</body>
</html>

代碼:
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
import com.demo.Customer;
/**
?* Servlet implementation class CustomerServlet
?*/
@WebServlet(name ="CS" ,urlPatterns = {"/CustomerServlet"})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
? ? ? ?
? ??
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
String email=request.getParameter("email");
String phone=request.getParameter("phone");
Customer customer=new Customer(name,email,phone);
HttpSession session =request.getSession();
synchronized (session) {
session.setAttribute("customer",customer);
}
RequestDispatcher rd=request.getRequestDispatcher("/displayCustomer.jsp");
rd.forward(request, response);
}
}

代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8"
? ? pageEncoding="UTF-8"%>
? ?<jsp:useBean id="customer" class="com.demo.Customer" scope="session"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>顯示客戶信息</title>
</head>
<body>
<h2>客戶信息如下:</h2>
<table border="1">
<tr>
<td>客戶名:</td>
<td><jsp:getProperty name="customer" property="name"/></td>
</tr>
<tr>
<td>郵件地址:</td>
<td><jsp:getProperty name="customer" property="email"/></td>
</tr>
<tr>
<td>電話:</td>
<td><jsp:getProperty name="customer" property="phone"/></td>
</tr>
</table>
</body>
</html>

代碼:
package com.demo;
public class Customer {
private String name;
private String email;
private String phone;
public Customer() {
super();
// TODO Auto-generated constructor stub
}
public Customer(String name, String email, String phone) {
super();
this.name = name;
this.email = email;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}

