response.getWriter().write 乱码问题 解决方案
最近在使用response.getWriter().write()方法向页面返回一个上传文件的名字时,当文件名字中出现中文,页面显示乱码。代码如下:
response.getWriter().write(“中文”);
最后在调用response.getWriter()之前添加这句话解决问题:
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(“中文”);
案例:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("测试");
response.setContentType("text/html;charset=UTF-8"); //这里写入防止乱码
response.getWriter().write("<a href='https://javar.cc'>JAVA编程好爱者</a>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request. setCharacterEncoding("UTF-8");//这里写入防止乱码
doGet(request, response);
}