index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/LoginServlet" method="get">
<div>
用户:<input type="text" name="uname">
</div>
<div>
密码:<input type="password" name="upwd">
</div>
<input type="submit" value="提交">
</form>
</body>
</html>
通过request中的getParameter方法进行获取。
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uname = req.getParameter("uname");
String upwd = req.getParameter("upwd");
resp.getWriter().print("name: " + uname + "pwd: " + upwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
运行,输入用户和密码并提交
这个地方产生了乱码。
设置响应编码为utf-8,加入以下代码(必须在获取之前加)
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
这样就可以正常显示了。
因为默认的ContentType是"text/html;charset=osi-8859-1"
为了严谨一些,还可以将请求的编码加上
req.setCharacterEncoding("utf-8");