2012-02-25 89 views
1
public class FeedUpdaterServlet extends HttpServlet { 
public void doGet(HttpServletRequest req, HttpServletResponse resp) 
     throws IOException { 
    PrintWriter out = resp.getWriter(); 
    req.setCharacterEncoding("utf-8"); 
    resp.setLocale(Locale.TAIWAN); 
    resp.setContentType("text/html; charset=utf-8"); 
    resp.setCharacterEncoding("utf-8"); 
    resp.getWriter().println("Hello, [email protected]!"); 
      out.println("我是人"); //some chinese character 
    out.println(resp.getCharacterEncoding()); 
    out.flush(); 
    out.close(); 
    } 

} 

網站XML響應編碼(不能改變響應編碼)

<locale-encoding-mapping-list> 
     <locale-encoding-mapping> 
      <locale>zh_TW</locale> 
      <encoding>utf-8</encoding> 
     </locale-encoding-mapping> 
    </locale-encoding-mapping-list> 

輸出: 你好,世界!@! ??? ISO-8859-1

看來,響應的編碼不能改變,發生了什麼?

回答

3

ServletResponse.setContentType(..)的文檔明確指出,如果在調用getWriter()方法後調用此方法,則該方法無效。

該做的伎倆:

public void doGet(HttpServletRequest req, HttpServletResponse resp) 
     throws IOException { 
    resp.setContentType("text/html; charset=UTF-8"); 
    PrintWriter out = resp.getWriter(); 
    out.println("Hello, [email protected]!"); 
    out.println("我是人"); //some chinese character 
    out.println(resp.getCharacterEncoding()); 
    out.flush(); 
    out.close(); 
} 
+0

你怎麼embbed這個響應轉換成HTML文件的特定部分? – InsaurraldeAP 2012-11-20 04:27:37