首页 > 代码库 > response.getWriter().write()乱码问题

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=http://www.mamicode.com/‘/day09/adv.html‘>首页");
        } else {
            //正确的链接
            response.getWriter().write("资源正在下载...");
        }
    }

}

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

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