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>");
    
    
        }
    }
    
    
    你以为的极限,也许只是别人的起点
  • 相关阅读:
    将Vim改造为强大的IDE
    Ubuntu首次开启root用户
    ssh-keygen实现免密码登陆
    Ubuntu下配置samba服务器实现文件共享
    Ubuntu下Apache+php+mysql网站架设详解
    IIS支持PHP
    详解C/C++预处理器
    学C++之感悟
    return *this和return this的区别
    const 的全面总结
  • 原文地址:https://www.cnblogs.com/LengDing/p/14469065.html
Copyright © 2011-2022 走看看