服务器发给浏览器
response.getWriter();之前使用response.setCharceterEncoding()来设置字符流的编码为utf-8 response.getWriter();之前使用 response.setHeader("Conntent-type","text/html;charset=uft-8")设置响应头 同时也通知浏览器服务器两边使用utf-8;举例
public class FServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().print("呵呵"); } }乱码了…再看看我们添加上两行代码的效果
public class FServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type","text/html;charset=utf-8"); //相当于上面这句response.setContentType("text/html;charset=utf-8"); response.getWriter().print("呵呵"); } }解决请求乱码方式有很多,其中这样也可以解决 去Tomcat安装目录下conf文件查看server.xml添加如下红框
注意:但是这种方式并不建议使用
注意:在server.xml中配置URIEncoding=utf-8这种方式不能使用
举例
public class GServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("username"); System.out.println(username); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String username=request.getParameter("username"); System.out.println(username); } }