response.getWriter().write()乱码问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了response.getWriter().write()乱码问题相关的知识,希望对你有一定的参考价值。

前台代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>广告页面</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
  </head>
  
  <body>
    广告内容,请猛戳这里。<br/>
    <a href="/day09/demo4">点击此处下载</a>
  </body>
</html>

后台代码:

package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestDemo4 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setHeader("content-type", "text/html; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        
        String referer = request.getHeader("referer");
        System.out.println("referer == " + referer);
        
        /*
         * 判断非法链接:
         *     1)直接访问的话referer=null
         *  2)如果当前请求不是来自广告   
         */
        
        if(referer == null || referer.contains("/day09/adv.html")) {
            response.getWriter().write("当前是非法链接,请回到首页。<a href=‘/day09/adv.html‘>首页</a>");
        } else {
            //正确的链接
            response.getWriter().write("资源正在下载...");
        }
    }

}

只是添加了response.setCharacterEncoding("utf-8");并不能防止乱码,还需要设置消息头。response.setHeader("content-type", "text/html; charset=utf-8");

以上是关于response.getWriter().write()乱码问题的主要内容,如果未能解决你的问题,请参考以下文章

已为此响应调用 Tomcat 8.5 response.getWriter()

response.getWriter()和jsp中的out对象的区别

response.getWriter().write()与out.print()的区别

response.getWriter()和jsp中out对象的区别

servlet 跳转页面后response.getWriter().println输出的汉字乱码

什么是PrintWriter out = servlet中的response.getWriter()