1. 程式人生 > >資料封裝相關案例

資料封裝相關案例

/**
 * 使用BeanUtils完成資料的封裝
 * @author Administrator
 *
 */
public class UserBeanUtilServlet extends HttpServlet {
private static final long serialVersionUID = 3625882115495534032L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 獲取資料
Map<String, String []> map
= request.getParameterMap();
// 建立User物件
User user = new User();
// 完成註冊
ConvertUtils.register(new MyDateConverter(), Date.class);
// 完成封裝
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 列印
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getMoney());
System.out.println(user.getBirthday());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

}

/**
 * User的JavaBean
 * @author Administrator
 *
 */
public class User {
private String username;
private String password;
private double money;
private Date birthday;

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

/**
 * 字串轉換日期類
 * @author Administrator
 *
 */
public class MyDateConverter implements Converter{
/**
* 字串轉換成日期
*/
public Object convert(Class clazz, Object obj) {
// 把輸入的字串,轉換成日期型別,返回
String dDate = (String) obj;
// 把字串轉換成日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
date = sdf.parse(dDate);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("轉換日期錯誤");
}
return date;
}
}
/**
 * 獲取請求引數,封裝資料
 * @author Administrator
 *
 */
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 6390620317553505800L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 獲取請求引數,建立User物件,設定值。
/**
 * // 獲取表單的內容
String username = request.getParameter("username");
String password = request.getParameter("password");
// 建立User物件,set設定值
User user = new User();
user.setUsername(username);
user.setPassword(password);
 */
// 獲取輸入的資料
Map<String, String []> map = request.getParameterMap();
// 建立User物件
User user = new User();
// 自己編寫封裝資料的方法
try {
populate(map,user);
} catch (Exception e) {
e.printStackTrace();
}
// 完成資料封裝
System.out.println(user.getUsername());
System.out.println(user.getPassword());
}
/**
 * 完成的資料
 * @param map
 * @param user
 * @throws Exception 
 */
private void populate(Map<String, String[]> map, User user) throws Exception {
BeanInfo info = Introspector.getBeanInfo(user.getClass());
// 獲取屬性的描述
PropertyDescriptor [] pds = info.getPropertyDescriptors();
// 迴圈遍歷
for (PropertyDescriptor pd : pds) {
// 獲取到屬性的名稱
String name = pd.getName();
// map的key
if(map.containsKey(name)){
// 獲取屬性的寫的方法
Method m = pd.getWriteMethod();
// 執行之
m.invoke(user, map.get(name)[0]);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

}

/**
 * User的JavaBean
 * @author Administrator
 *
 */
public class User2 {
private String username;
private String password;

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User2(String username, String password) {
this.username = username;
this.password = password;
}
public User2() {
}
}

訪問JavaBean屬性的兩種方式:直接呼叫beansetXXXgetXXX方法。通過內省技術訪問(java.beans包提供了內省的API) 內省技術是基於反射技術的通過Introspector類獲得Bean物件的 BeanInfo,然後通過 BeanInfo來獲取屬性的描述器( PropertyDescriptor),通過這個屬性描述器就可以獲取某個屬性對應的 getter/setter 方法,然後通過反射機制來呼叫這些方法
/**
 * 測試類
 * @author Administrator
 *
 */
public class IntrospectorTest {
@Test
public void run() throws Exception{
User user = new User();
// 獲取類的資訊
BeanInfo info = Introspector.getBeanInfo(user.getClass());
// 獲取屬性的描述
PropertyDescriptor [] pds = info.getPropertyDescriptors();
// 迴圈遍歷,獲取屬性的名稱
for (PropertyDescriptor pd : pds) {
// System.out.println(pd.getName());
if(!"class".equals(pd.getName())){
// 獲取寫的方法
Method m = pd.getWriteMethod();
m.invoke(user, "admin");
}
}
System.out.println(user.getUsername());
System.out.println(user.getPassword());
}
}

SessionDemo

public class SessionDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// session域物件
HttpSession session = request.getSession();
session.setAttribute("username", "小風");
// DD64756D56885AF87E883B887BF77E6Cjsessionid=DD64756D56885AF87E883B887BF77E6C
System.out.println(session.getId());
response.sendRedirect("/day12/session2");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

 public class SessionDemo2 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 手動傳入jsessionid=DD64756D56885AF87E883B887BF77E6C
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("<h4>訪問到了..."+username+"</h4>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

}

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>
<h4>表單提交到JSP的頁面</h4>
<form action="/day12/bean/success.jsp" method="POST">
姓名:<input type="text" name="username" /><br/>
密碼:<input type="password" name="password" /><br/>
<input type="submit" value="登陸"/>
</form>
<h4>表單提交到Servlet程式</h4>
<form action="/day12/user" method="POST">
姓名:<input type="text" name="username" /><br/>
密碼:<input type="password" name="password" /><br/>
<input type="submit" value="登陸"/>
</form>
<h4>表單提交到Servlet(BeanUtils)程式</h4>
<form action="/day12/userBeanUtil" method="POST">
姓名:<input type="text" name="username" /><br/>
密碼:<input type="password" name="password" /><br/>
餘額:<input type="text" name="money" /><br/>
生日:<input type="text" name="birthday" /><br/>
<input type="submit" value="登陸"/>
</form>
</body>

</html>

<h4>表單提交到JSP的頁面</h4>

<%@page import="cn.itcast.vo.User"%>
<%@ 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>
<h3>傳統方式封裝資料</h3>
<%
// 獲取表單的內容
String username = request.getParameter("username");
String password = request.getParameter("password");
// 建立User物件,set設定值
User user = new User();
user.setUsername(username);
user.setPassword(password);
%>
<!-- 使用jsp的標籤封裝資料 -->
<jsp:useBean id="u" class="cn.itcast.vo.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<jsp:getProperty property="username" name="u"/>
<jsp:getProperty property="password" name="u"/>
</body>
</html>

<%@ 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>
<h4>EL的運算</h4>
<form action="/day12/el/elDemo4.jsp" method="POST">
姓名:<input type="text" name="username" /><br/>
<input type="submit" value="登陸"/>
</form>
</body>

</html>

<%@ 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>
<h4>EL的WEB物件</h4>
${ param.username }
<h4>獲取請求頭</h4>
${ header.referer }
<h4>獲取全域性初始化引數</h4>
${ initParam.username }
<h4>pageContext物件</h4>
${ pageContext.request.contextPath }
</body>
</html>

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="true" buffer="8kb" autoFlush="true" 
    errorPage="/jsp/error.jsp" isELIgnored="false"%>

<!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>
<h4>歡迎</h4>
<%
List list = new ArrayList();
// int a = 10 / 0;
request.setAttribute("username", "小風");
%>
<!-- HTML的文字 -->
${ username }
</body>
</html>