1.概述:当前端表单提交到后台时,我们需要对数据进行封装,如果每次都request获取各个属性再封装很麻烦,不如一次性获取来的方便;因此,为了方便,我们可以使用已经写好的开发工具包BeanUtils来封装Javabean。BeanUtils由Apache公司提供 ,专门进行javabean操作,在web层各种框架中被使用,例如:struts 使用BeanUtils封装JavaBean对象 。
2.导jar包:首先,要想使用已经开发好的工具包,就必须先导如jar包到项目中(WEB-INF/lib下);
(1)commons-beanutils-1.8.3.jar(网盘链接:https://pan.baidu.com/s/1i0eEGrFfjK4I0fOPx0rSIg 密码:dj87)
(2)commons-logging-1.1.1.jar(网盘链接:https://pan.baidu.com/s/1NKCYglN4TUDgmCBafTrT7g 密码:xm3d)
注意:引入jar包需要:import org.apache.commons.beanutils.BeanUtils;
3.常用的方法
(1)BeanUtils.setProperty(bean, name, value);顾名思义,用来设置目标对象的属性值;其中bean是指你将要设置的目标对象,name指的是将要设置的属性,value为属性值。
(2)BeanUtils.populate(bean,Map),此处的Map为Map<String(key),String[](value)>
将请求的Map封装为JavaBean对象,注意其中Map中的key值须与对象中的属性名相同,否则不能实现拷贝。
(4)BeanUtils.copyProperties(newObject,oldObject),实现对象的拷贝。
4.应用实例
(1)首先,编写JavaBean对象
package com.user;
public class user {
private Long id;
private String username;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
}
(2)接下来,编写业务层代码(代码是Struts2项目一部分,不全,请自行补充)
//获取前端表单发来的数据,request方式
HttpServletRequest request=ServletActionContext.getRequest();
//以Map接受,arg0是key值,arg1是value值
Map<String,String[]> map=request.getParameterMap();
user u=new user();
try {
System.out.println("前"+u.getUsername());
BeanUtils.populate(u, map);//将map的kay-value拷贝到user对象中
System.out.println("后"+u.getUsername());
}
(3)最后,编写前端jsp页面代码
<%@ page language="java"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Struts2 Test</title>
</head>
<body>
<center>
<form class="form-horizontal" name="form1" action="/Struts2Test/user_Login.action" method="post">
<fieldset>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">用户名</label>
<div class="controls">
<input type="text" name="username" placeholder="username" class="input-xlarge">
</div>
</div>
<br>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">密码</label>
<div class="controls">
<input type="password" name="password" placeholder="password" class="input-xlarge">
</div>
</div>
<br>
<input type="submit" value="登陆">
</fieldset>
</form>
</center>
<!--
<a href="${ pageContext.request.contextPath }/wjk_sayhello.action">问候语</a>
<a href="${ pageContext.request.contextPath }/wjk_sayGoodbye.action">再见语</a>
-->
</body>
</html>