zoukankan      html  css  js  c++  java
  • Servlet页面解析中文乱码问题

    提交表单时,中文可能会产生乱码


    在Servlet中,在使用request和response之前设置一下request和response的编码格式为utf-8。
    如下:

    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    

    如果使用response.getWriter()输出html页面,应该设置浏览器显示的编码为utf-8。如下:

    response.setContentType("text/html;charset=utf-8");
    

    注意,编码的设置要写在getWriter前面

    例程

    package com.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    public class SampleServlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
    
            //resp.getWriter向浏览器树出的数据流
            PrintWriter writer = resp.getWriter();
            writer.println("<a href='http://www.baidu.com'>Baidu</a>");
            String name = req.getParameter("name");
            writer.println("<h1>name="+name+"</h1>");
    
    
        }
    }
    
    
    你以为的极限,也许只是别人的起点
  • 相关阅读:
    keepalived的一些。。
    virtualbox复制了以后网卡启动不了。
    mysql安装之后需要调的参数
    mysql5.6 thread pool
    $releasever 不正确解析
    linux 被入侵后扫尾工作
    简单启动脚本编写
    tcmalloc安装
    rsyslog及loganalyzer
    nsswitch & pam
  • 原文地址:https://www.cnblogs.com/LengDing/p/14469065.html
Copyright © 2011-2022 走看看