jsp中使用multipart/form-data类型的form提交乱码问题

本文探讨了使用JSP和Servlet实现文件上传时,在Tomcat服务器上出现的中文字符乱码问题。针对该问题提供了详细的解决方案,包括设置页面编码、使用Spring过滤器等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目时发现以前是application/x-www-form-urlencoded的FORM提交数据时正常,  现在为表单添加个上传功能就有乱码了, 在网上看了篇文章

This problem had been bugging me for 3 days!

Background:

Use JSP and Servlet to implement file upload。The uploaded file is stored in file system, the related info like description and Mime type, size and path name is stored in MySQL。JSP and DB table both use UTF-8 CHARSET. If successfully,Servelet forwards to success page with related file info returned.

Promblem(all happened with Chinese characters):

1. On Jetty,except the filename was encoded by UTF-8(unreadable), everything is good.
2. But on Tomcat, all that characters were inserted into DB and returned to client were corrupted.

Solution:
1.No matter how you set a form's charset,Tomcat always treats it by iso 8859-1.So what we read from the input strem are 8859-1 encoded.
If we need to search a substring in the content, we have to use getBytes("ISO-8859-1") on the substring. Also, use String(subBytes, "UTF-8") to return some substrings.

2.In the success jsp, we should add <%@ page contentType="text/html;charset=UTF-8"%>.

(And the <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> is useless.)

3.In the post() method of Servlet, we must add request.setCharacterEncoding("UTF-8"); And it must sit before any sentences that read input stream.

After the previous steps, everything is good on Tomcat.

But on Jetty, the filename was still encoded by UTF-8. I tried to convert UTF-8 to system default encoding by new String(fileName.getBytes("UTF-8"), system.getProperty("file.encoding")), but no use.

 

看起来在Jetty上跑没事, 好像是Tomcat的编码问题, 解决方法也简单, page charset 用utf8就好了, 如果你用spring就加个filter:

 <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值