昨天做struts(版本为1.3)文件上传(用的是struts自带的org.apache.struts.upload.FormFile实现文件的上传)的时候出现了乱码的问题,即提交了包含file类型的input的页面(页面的编码为UTF-8)后,在action中取出参数时候出了问题,具体的表现是页面提交的参数中参数值为中文的时候,在action中获得的参数值为乱码,如当上传的文件的文件名为中文时,在action中取得的文件名是乱码;于是我试图用了两种方法解决这一问题(注意看红色的部分):
第一种:在action中的execute最前面写入
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;chaset=UTF-8");
FileForm fileForm=(FileForm) form;
String spCode= fileForm.getSpCode();
System.out.println("spCode"+spCode);
FormFile file=fileForm.getUpFile();
System.out.println("文件名字是----"+file.getFileName());
return null;
}
}
第二种方法:写一个过滤器,该过滤器拦截.do请求,在该过滤器的doFilter方法中写入
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("到达过滤器");
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
chain.doFilter(request, response);
}
另我感到疑惑的是用第一种方法解决不了乱码的问题,用了第二种方法之后就可以解决这个问题了;哪位牛人可以告诉小弟,到底这两种方法有什么区别吗 ??其实如果单从功能的实现的话用第二种方法就 可以了问题是加多了一个过滤器必然回导致性能上的降低,同时很多被拦截的请求是不必要对编码进行处理的