在浏览器直接调用servlet的时候,先获取PrintWriter对象再去设置返回数据的编码无论怎么改还是一样会乱码
@WebServlet(name = "/ServletLife",urlPatterns = "/life",loadOnStartup = 1)
public class ServletLife extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//原位置
// PrintWriter writer = resp.getWriter();
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//新位置
PrintWriter writer = resp.getWriter();
writer.write("servlet life s宿舍");
System.out.println("learn servlet life宿舍");
}
}
修改后结果