JavaWeb06-获取从前台页面提交的用户名和用户密码以及解决乱码问题

  

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>

Servlet代码,通过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");
原文地址:https://www.cnblogs.com/Patrick20726/p/13583568.html