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);
        }
  • 相关阅读:
    How to build Linux system from kernel to UI layer
    Writing USB driver for Android
    Xposed Framework for Android 8.x Oreo is released (in beta)
    Linux Smartphone Operating Systems You Can Install Today
    Librem 5 Leads New Wave of Open Source Mobile Linux Contenders
    GUADEC: porting GNOME to Android
    Librem 5 – A Security and Privacy Focused Phone
    GNOME and KDE Join Librem 5 Linux Smartphone Party
    Purism计划推出安全开源的Linux Librem 5智能手机
    国产系统之殇:你知道的这些系统都是国外的
  • 原文地址:https://www.cnblogs.com/legion/p/9056015.html
Copyright © 2011-2022 走看看