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");
  • 相关阅读:
    数据结构(二)(三)栈和队列
    数据结构(一)线性表
    中信卡笔试代码
    Jenkins搭建-简单使用
    python 生成指定两个ip间的所有ip
    形象理解 什么是磁盘碎片
    形象理解软件位宽 32位和64位的区别
    看板娘>_
    Win10一张网卡设置多个ip地址
    VMware ubuntu安装tools灰色?
  • 原文地址:https://www.cnblogs.com/Patrick20726/p/13583568.html
Copyright © 2011-2022 走看看