response.getWriter().write()亂碼問題
阿新 • • 發佈:2017-08-08
xtend exception charset size () 後臺 get meta con
前臺代碼:
<!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()亂碼問題