zoukankan      html  css  js  c++  java
  • 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");
  • 相关阅读:
    jQuery 重新温习 遗忘知识点
    正则表达式获取博客园随笔1
    用django创建一个简单的sns
    WCF小实例以及三种宿主
    iOS: imageIO完成渐进加载图片
    Excel 菜单系统
    分布式EventBus的Socket实现
    Jenkins安装plugin
    邮件系统存储设计问答
    在Windows上使用CodeLite+MinGW+Clang进行开发
  • 原文地址:https://www.cnblogs.com/Patrick20726/p/13583568.html
Copyright © 2011-2022 走看看