JSP页面和html页面中文乱码的解决 - Go语言中文社区

JSP页面和html页面中文乱码的解决


1.在JSP页面添加

<%@ page contentType="text/html; charset=utf-8" %> <%--这里的utf-8是指服务器发送给客服端时的内容编码 --%>

<%@ page pageEncoding="utf-8"%> <%--这里的utf-8是指 .jsp文件本身的内容编码 --%>

2.在HTML中添加

<meta http-equiv= "Content-Type" content="text/html; charset=utf-8" > (添加在<head>标签中)
<!-- 这里的utf-8是这个是网页内容的编码,而不是文件本身的,所以对html文件的保存还需要改用utf-8的编码方式 -->

3.对于客户端提交数据(HttpServletRequest request)给服务器端,如果数据中带有中文的话,有可能会出现乱码情况分两种情况解决:

  • 对于Get请求过来的数据,在url地址栏上就已经经过编码了,tomcat收到了这批数据,getParameter 默认使用ISO-8859-1去解码,所以我们取到的就是乱码。
    解决方式1:先让文字回到ISO-8859-1对应的字节数组 ,然后再按utf-8组拼字符串(转码)
    例子:
    String username = request.getParameter("username");
    //先让文字回到ISO-8859-1对应的字节数组 , 然后再按utf-8组拼字符串
    username = new String(username.getBytes("ISO-8859-1") , "UTF-8");
    System.out.println("userName="+username);

    解决方式2(推荐):直接在tomcat里面做配置,以后get请求过来的数据永远都是用UTF-8编码。 在服务器配置文件 conf/server.xml 加上URIEncoding="utf-8"

  • 对于Post请求,解决方法如下。这种方法对Get请求方式没用。
    /**
    *这行设置一定要写在getParameter之前。
    */
    request.setCharacterEncoding("UTF-8");//这个说的是设置请求体里面的文字编码

        由于一个项目里面有很多servlet,如果都需要处理请求的乱码问题,每个servlet都去写这样的代码,会十分的繁琐,因此,可以动态代理的方式来解决这个问题。

        思路:用过滤器对所有的请求进行拦截,判断当前的请求是get/post  request.getMethod();

  •  如果是post, 设置一句话: request.setCharacterEncoding(“utf-8”);    放行;

  • 如果是get,调用原先的String v = request.getParameter(name);    然后将v进行转码,放行;
public class EncodingFilter implements Filter {

    public EncodingFilter() {}

    public void destroy() {}

    public void init(FilterConfig fConfig) throws ServletException {}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 将request对象转换为HttpServletRequest
        final HttpServletRequest req = (HttpServletRequest) request;
        // 让JDK在内存中生成代理对象:增强了req对象上的getParameter(name);API
        HttpServletRequest myReq = (HttpServletRequest) Proxy.newProxyInstance(EncodingFilter.class.getClassLoader(),
                req.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object obj = null;
                        if (method.getName().equalsIgnoreCase("getParameter")) {
                            // 获取本次请求方式
                            String md = req.getMethod();
                            if ("get".equalsIgnoreCase(md)) {
                                // get方式的请求
                                // 调用req对象上的getParameter方法
                                String v = (String) method.invoke(req, args);
                                // 转码
                                String vv = new String(v.getBytes("iso-8859-1"), "utf-8");
                                return vv;
                            } else {
                                // post方式的请求
                                req.setCharacterEncoding("utf-8");
                                obj = method.invoke(req, args);
                            }
                        } else {
                            obj = method.invoke(req, args);
                        }
                        return obj;
                    }
                });
        // 打印代理对象哈希码
        // System.out.println(myReq.hashCode());
        // 将代理对象放行
        chain.doFilter(myReq, response);
    }
}

在web.xml中注册

<filter>
    <display-name>EncodingFilter</display-name>
    <filter-name>EncodingFilter</filter-name>
    <filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>EncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

4.响应的数据( HttpServletResponse response, 负责返回数据给客户端 )中有中文,那么有可能出现中文乱码。如果想让服务器端出去的中文,在客户端能够正常显示。只要确保一点,出去的时候用的编码和客户端看这份数据用的编码是一样的。HttpServletResponse 有两种输出方式

  • 以字符流的方式写数据 response.getWriter().write("<h1>hello response...</h1>"); 这里写出去的文字,默认使用的是ISO-8859-1, 我们可以指定写出去的时候,使用什么编码写
    //1. 指定输出到客户端的时候,这些文字使用UTF-8编码
    response.setCharacterEncoding("UTF-8");
    //2. 直接规定浏览器看这份数据的时候,使用什么编码来看。
    response.setHeader("Content-Type", "text/html; charset=UTF-8");
    response.getWriter().write("中文...");
  • 以字节流的方式写数据 response.getOutputStream().write("hello response...".getBytes());
     默认情况下getOutputStream 输出使用的是UTF-8的码表 。如果想指定具体的编码,可以在获取byte数组的时候指定。例如
//1.指定浏览器看这份数据使用的码表
response.setHeader("Content-Type", "text/html;charset=GBK");
//2.指定输出的中文用的码表
response.getOutputStream().write("中文..".getBytes("GBK"));

        不管是字节流还是字符流,直接使用一行代码就可以了,上面的方式可忽略。

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

5.如果是使用Spring家族的框架,过滤器可以直接使用其为我们提供的字符编码过滤器,不用自己再去编写过滤器了(仅限post请求),非常方便,在web.xml中添加如下代码:

<!-- 解决post乱码问题 -->
<filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!-- 设置编码参是UTF8 -->
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/CPOHUI/article/details/80459917
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 22:39:40
  • 阅读 ( 896 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢