问题描述:
近期有同学反馈购买的web项目中,部分web页面的提示信息中文乱码。而这些中文乱码只在接口请求后返回的提示信息中。如下图所示,图中中文乱码信息本应当为
"你已经评价过该老师。不能重发评价"
原因及解决方案
通过如下代码,我们可以看到
req.setAttribute("msg", "你已经评价过该老师。不能重发评价"); 是有中文汉字的,但是req没有设置编码格式。此时我们只需要在代码中设置req的编码格式即可。
public void pingjiaAdd(HttpServletRequest req,HttpServletResponse res)
{
String pingjia_id=String.valueOf(new Date().getTime());
int tea_id=Integer.parseInt(req.getParameter("tea_id"));
int zongfenshu=0;
String shijian=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
int stu_id=((Tstu)(req.getSession().getAttribute("stu"))).getId();
if("yipingjia".equals(liuService.panduan_shifou_pingjia(tea_id, stu_id)))
{
req.setAttribute("msg", "你已经评价过该老师。不能重发评价");
}
if("weipingjia".equals(liuService.panduan_shifou_pingjia(tea_id, stu_id)))
{
String zhibiao_id=req.getParameter("zhibiao_id");
String[] zhibiao_id1=zhibiao_id.split(",");
for(int i=0;i<zhibiao_id1.length;i++)
{
int zhibiao_id2=Integer.parseInt(zhibiao_id1[i]);
int fenshu=Integer.parseInt(req.getParameter(String.valueOf(zhibiao_id2)));
zongfenshu+=fenshu;
System.out.println(zhibiao_id2+"^^"+fenshu);
liuService.save_pingjia_xuanxiang(zhibiao_id2, fenshu, pingjia_id);
}
liuService.save_pingjia(pingjia_id, tea_id, zongfenshu,shijian,stu_id);
req.setAttribute("msg", "评价完毕");
}
String targetURL = "/common/msg.jsp";
dispatch(targetURL, req, res);
}
解决方案:在下面的代码中增加 req.setCharacterEncoding("UTF-8");
增加完如下代码后,会有一个错误提示,Unhandled exception: java.io.UnsupportedEncodingException 如上图所示;
此时,我们只需要点击报错信息前面的红色灯泡按钮,鼠标双击选择第一个提示Add exception to method signature按钮。
双击完成后,代码中就会自动添加异常捕获信息提示,如下图所示:
这样就不会再有中文乱码现象了。
若msg是放在response中,则我们需要在response中设置编码格式,可以增加如下代码,原理与request中设置编码格式相同。
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");//解决乱码