• 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);
        }
  • 相关阅读:
    web开发之web 验证码--- webqq 机器人
    赛星软件---智能视频分析事件检测
    模式识别之双目立体视觉---双目立体视觉相关介绍
    安卓项目之微信公众好---初体验
    《数学分析》视频
    单目和双目模式识别---游戏控制
    多媒体开发之音频编码---ffmpeg 编码aac
    PC如何访问手机网址
    linux shell实现守护进程 看门狗 脚本
    grep用法详解:grep与正则表达式
  • 原文地址:https://www.cnblogs.com/legion/p/9056015.html
Copyright © 2020-2023  润新知