这两天在学JavaWeb,看的是传智播客网上书城的教学视频。其中页面提交表单时,使用了一个封装好的CommonUtils类来将request.getParameterMap()获取的Map转为JavaBean对象。CommonUtils内部使用了commons-beanutils包里的BeanUtils.populate方法。
刚开始写的JavaBean是这样的:
public class Domain {
private String name;
private String verifycode;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVerifyCode() {
return verifycode;
}
public void setVerifyCode(String verifycode) {
this.verifycode = verifycode;
}
@Override
public String toString() {
return "Domain [name=" + name + ", verifycode=" + verifycode + "]";
}
}
Servlet中的doPost方法:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String[]> map = request.getParameterMap();
Map<String, String> output = new HashMap<String, String>();
for(Entry<String, String[]> entry : map.entrySet()) {
output.put(entry.getKey(), entry.getValue()[0]);
}
System.out.println(output.toString());
Domain formDomain = new Domain();
ConvertUtils.register(new DateLocaleConverter(), Date.class);
try {
BeanUtils.populate(formDomain, map);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
System.out.println(formDomain.toString());
}
前台表单代码:
<form action="/tools/LoginServlet" method="post">
<input type="hidden" name="method" value="doPost"/>
用户名:<input type="text" name="name"><br />
密 码:<input type="password" name="password"><br />
验证码:<input type="text" name="verifycode"><br />
<img alt="验证码" src="/tools/VerifyCodeServlet" id="imgVerifyCode" οnclick="_hyz()">
<a href="javascript:_hyz()">换一张</a><br>
<input type="submit" name="提交">
</form>
{name=liSi, verifycode=test, method=doPost, 提交=提交, password=123}
Domain [name=liSi, verifycode=null]
可以看到request中的verifycode参数是正常的,但JavaBean中的verifycode却没有值。这里楼主卡了很久,后来将setVerifyCode改为setVerifycode才正常。
实验了一下,什么setVErifycode、setverifycode、setverifyCode之类的都不行,相信各位也知道命名规则了吧。