问题:servlet中使用request.getParameter()获取不到前端发送的form表单数据
post请求是接收到了的,但是输出一直是"null",数据为空,本来一直以为是后台写错了
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
request.setCharacterEncoding("utf-8");
String psd = request.getParameter("psd");
System.out.println(psd);
}
结果是前端提交表单的问题,原本是准备把前端的表单内容和文件上传一起做的,所以在前端form表单中加入了 enctype="multipart/form-data"
<form action="Test" method="post" accept-charset="utf-8">
<div class="title">请输入个人信息</div>
<div class="info">
<label for="username">姓名:</label>
<input type="text" name="username">
<br>
<label for="psd">密码:</label>
<input type="password" name="psd">
<br>
性别:<input type="radio" name="gender" value="man">
<label for="man">男</label>
<input type="radio" name="gender" value="woman">
<label for="woman">女</label>
<br>
<label for="email">电子邮箱:</label>
<input type="text" name="email">
<br>
<label for="hobby">爱好:</label>
<input type="checkbox" name="hobby" value="sing">唱歌
<input type="checkbox" name="hobby" value="dance">跳舞
<input type="checkbox" name="hobby" value="music">音乐
<input type="checkbox" name="hobby" value="swim">游泳
<br>
<label for="file">文件上传:</label>
<input type="file">
<br>
<input type="submit" value="提交" class="submit">
</div>
</form>
所以导致后台输出时候一直都是“null”,当把enctype="multipart/form-data"去掉后,就能正常输出了!
这是因为enctype="application/x-www-form-urlencoded"是默认的编码方式,当以这种方式提交数据时,HTTP报文中的内容是:
<span style="font-size: small;">POST /post_test.php HTTP/1.1
Accept-Language: zh-CN
User-Agent: Mozilla/4.0
Content-Type: application/x-www-form-urlencoded
Host: 192.168.12.102
Content-Length: 42
Connection: Keep-Alive
Cache-Control: no-cache
title=test&content=%B3%AC%BC%B6%C5%AE%C9%FA&submit=post+article
</span>
在传输大数据量的二进制数据时,必须将编码方式设置成enctype="multipart/form-data",当以这种方式提交数据时,HTTP报文中的内容是:
<span style="font-size: small;">POST /post_test.php?t=1 HTTP/1.1
Accept-Language: zh-CN
User-Agent: Mozilla/4.0
Content-Type: multipart/form-data; boundary=---------------------------7dbf514701e8
Accept-Encoding: gzip, deflate
Host: 192.168.12.102
Content-Length: 345
Connection: Keep-Alive
Cache-Control: no-cache
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="title"
test
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="content"
....
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="submit"
post article
-----------------------------7dbf514701e8--</span>