How to change the character encoding for Servlet 3.0 Spring MVC multipart upload forms?

后端 未结 3 1191
死守一世寂寞
死守一世寂寞 2021-01-04 18:07

I have a pretty simple JSP/Servlet 3.0/Spring MVC 3.1 application.

On one of my pages, I have multiple forms. One of these forms allows the user to upload a file and

相关标签:
3条回答
  • 2021-01-04 18:12

    I also had the problem with encoding when using the Servlet 3 API. After some research, I have found that there is a bug in Tomcat 7 which makes the parameters not to be read with the correct encoding under certain conditions. There is a work-around. First, you need to tell which encoding it actually is (if it is not default iso-8859-1):

    request.setCharacterEncoding("UTF-8");
    

    This is basically what the CharacterEncodingFilter in Spring does. Nothing strange so far. Now the trick. Call this:

    request.getParameterNames()
    

    Make sure this method is invoked before getParts(). If you are using Spring I guess you need to do this in a filter before the request ends up in Spring. The order which the methods are invoked are crucial.

    Update: The Tomcat bug has been fixed in 7.0.41 onwards, so if you use a recent version of Tomcat you only need to set the character encoding to get correct result.

    0 讨论(0)
  • 2021-01-04 18:17

    Since I found no way to set the default encoding using the StandardMultipartResolver, I dumped the servlet 3.0 config and went for the good old CommonsMultipartResolver.

    I configured it like this in my spring servlet context:

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- one of the properties available; the maximum file size in bytes -->
        <property name="maxUploadSize" value="157286400" />
        <property name="maxInMemorySize" value="5242880"/>
        <property name="defaultEncoding" value="utf-8"/>
    </bean>
    

    In the end, there isn't much difference, since under the hood of the StandardMultipartResolver, it just delegates to CommonsMultipartResolver.

    I actually find the servlet 3.0 approach more troublesome, since it requires configuration in both web.xml and your servlet context, and you lose the ability to set the default encoding.

    0 讨论(0)
  • 2021-01-04 18:35

    I created my own multipart filter as holmis83 suggested, and worked fine

        public class MyMultiPartFilter extends MultipartFilter {
    
        Logger logger = LoggerFactory.getLogger(MyMultiPartFilter.class);
    
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
    
            request.setCharacterEncoding("UTF-8");
            request.getParameterNames();
    
            super.doFilterInternal(request, response, filterChain);
        }
    }
    
    0 讨论(0)
提交回复
热议问题