zoukankan      html  css  js  c++  java
  • Servlet Java Web开发(3) request response和编码

    编码

     这里例子依然是在一个HttpServlet类的doGet方法中,

    一般如果直接发送数据

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.getWriter.printf("中文编码");

    }

    浏览器访问会得到乱码。

    解决方案:response.setCharacterEncoding("utf-8");只是把字符转为utf-8格式,浏览器依然会按照gbk解析。

    在发送之前使用

    response.setHeader("Content-Type", "text/html;charset=utf-8");
    //或者
    response.setContentType("text/html;charset=utf-8");
    //这两者一样

    他们的效果不仅起到response.setCharacterEncoding("utf-8");的作用,还会在http 响应头中增加Content-Type: text/html;charset=utf-8,这样浏览器就会正确解析。

    get 和post的编码

    新建一个form.html文件

    <body>
    This is a HTML Form Page<br>
    <form action="/HelloWorld/BServlet" method="post">
    用户名:<input type="text" name="username" value="李四"/><br>
    <input type="submit" value="提交"/>
    </form>
    
    <a href="/HelloWorld/BServlet?username=李四">GET</a>
    </body>
    </html>

    get和post都会想server发送username=李四

    一个在地址栏,一个在http正文里面

    Get的时候,http报文GET /HelloWorld/BServlet?username=%E6%9D%8E%E5%9B%9B HTTP/1.1

    BServlet代码为

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        
         response.setHeader("Content-Type", "text/html;charset=utf-8"); String name=request.getParameter(("username")); byte[] b=name.getBytes("iso-8859-1"); response.getWriter().println(new String(b,"utf-8"));

     post的时候,http报文

    相应处理post的代码为

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html;charset=utf-8");
            String username=request.getParameter("username");
            response.getWriter().print(username);
        }
  • 相关阅读:
    [BZOJ3513] idiots
    2020牛客暑期多校训练营(第六场)A
    2020牛客暑期多校训练营(第六场)J
    2020牛客暑期多校训练营(第六场)H
    2020牛客暑期多校训练营(第六场)G
    2020牛客暑期多校训练营(第六场)K
    组队训练日志 2020.10.05
    Java基础
    Auditd
    Snort记录
  • 原文地址:https://www.cnblogs.com/legion/p/9056015.html
Copyright © 2011-2022 走看看