当servlet响应客户端请求的时候,返回去的中文字符会会出现乱码,可以使用response.setContentType("text/html;charset=utf-8");将字符集设置为utf-8,而不是像响应一样req.setCharacterEncoding("UTF-8");这样设置字符集,多数的时候这样设置字符集是没有效果的。
下面用一个例子来演示:
package com.service; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class SafeServlet extends HttpServlet { private int count = 0; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //没有设置编码 PrintWriter writer = resp.getWriter(); writer.print("我是坏蛋,你是小笨猪"); } }运行效果如图所示: 使用req.setCharacterEncoding("UTF-8");来试试
package com.service; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class SafeServlet extends HttpServlet { private int count = 0; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //设置编码 resp.setCharacterEncoding("UTF-8"); PrintWriter writer = resp.getWriter(); writer.print("我是坏蛋,你是小笨猪"); } }运行结果如图: 最后使用response.setContentType("text/html;charset=utf-8");
package com.service; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class SafeServlet extends HttpServlet { private int count = 0; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //设置编码 // resp.setContentType("text/html;charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.print("我是坏蛋,你是小笨猪"); } }运行结果如下: