SpringMVC 中文乱码

乱码分为多种情况,本文介绍两种常见的乱码现象和解决办法
1.@ResponseBody返回数据乱码
SpringMVC @ResponseBody默认情况下返回中文为乱码,原因是@ResponseBody采用的是
StringHttpMessageConverter,而它采用的是ISO-8859-1编码。

//StringHttpMessageConverter 部分源码
/**
 * Implementation of {@link HttpMessageConverter} that can read and write strings.
 *
 * 

By default, this converter supports all media types ({@code */*}), * and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden * by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property. * * @author Arjen Poutsma * @since 3.0 */ public class StringHttpMessageConverter extends AbstractHttpMessageConverter { public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1"); private final Charset defaultCharset; private final List availableCharsets; private boolean writeAcceptCharset = true;

乱码问题有两种解决方案:
1.1局部解决方案
在@RequestMapping中声明produces

@ResponseBody
@RequestMapping(value = "/login",method = RequestMethod.POST,produces = "text/html;charset=UTF-8")

该方案只对已配置的请求生效,要全局生效需要采用方案二
1.2全局解决方案
在SpringMVC.xml中配置,可以从StringHttpMessageConverter源码中看出,需要配置supportedMediaTypes

    
        
            
                
            
        
    

2.jsp传入参数乱码
2.1解决办法,在web.xml中加入编码过滤器

    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    
    
        CharacterEncodingFilter
        /*
    

你可能感兴趣的:(SpringMVC 中文乱码)