今天我来总结昨天开发的一个简单的jsp web 应用程序时,在做一个调教表单,从servlet端获取数据,这个表单里含有上传文件控件。如果我们在测试的时候,获取数据的是乱码,这时,大家可以先去掉上传控件的,然后测试通过get请求向servlet传数据,通过
response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter();
进行输出中文测试,如果出现乱码,自己去处理页面的编码,以及设置上面的编码方式;这个问题如果解决了,那么在把上传控件放到表单里,再测试!
大家知道,在jsp里,表单里含有上传文件控件的,在服务端,我们大部分采用这样的处理方式:先导入commons-fileupload-1.2.1.jar和commons-io-1.4.jar这两个Jar文件;然后在servlet里这样写:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); DiskFileUpload diskFileUpload = new DiskFileUpload(); diskFileUpload.setHeaderEncoding("utf-8"); diskFileUpload.setSizeMax(100 * 1024 * 1024); diskFileUpload.setSizeThreshold(4096); String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "uploads\\"; diskFileUpload.setRepositoryPath(savePath); try { List fileItems = diskFileUpload.parseRequest(request); Iterator iter = fileItems.iterator(); Ads model = new Ads(); PrintWriter writer = response.getWriter(); for (; iter.hasNext();) { FileItem fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { /* 一般的字段判断 */ if(fileItem.getFieldName().equalsIgnoreCase("catename")) { model.setCatename(fileItem.getString("utf-8")); } } else { /* 控件上传*/ if(fileItem.getFieldName().equalsIgnoreCase("cateicon")) { String fileName = fileItem.getName(); if(!StringUtil.isNullOrEmpty(fileName)) { fileItem.write(new File(savePath + fileName)); model.setCicon(fileName); } } /* 如果表单中有多个控件,继续处理 */ else if(fileItem.getFieldName().equalsIgnoreCase("lefttop")) { String fileName = fileItem.getName(); if(!StringUtil.isNullOrEmpty(fileName)) { fileItem.write(new File(savePath + fileName)); model.setLefttop(fileName); } } } } model.setOrderid(1); AdsDao.add(model); writer.println("<script>alert('添加成功');location.href='/AdsList.jsp';</script>"); writer.flush(); } catch (Exception e) { e.printStackTrace(); } }
在上面,我标注一段用红色表示的
diskFileUpload.setHeaderEncoding("utf-8");
它一定要设置自己需要的编码方式,这样就不会出现问题了!
转载请注明http://www.cnblogs.com/yushengbo,否则将追究版权责任!