zoukankan      html  css  js  c++  java
  • SpringMVC中的乱码问题

    此文主要罗列springmvc中的乱码问题解决方案:

      乱码原因:

          我们的请求响应信息是会经过服务器(tomcat)的,而tomcat会对其进行重新编码(默认是ISO-8859-1)。

      一、get请求乱码

        解决方案一:

          修改tomcat配置文件servlet.xml,指定UTF-8编码,如下:    

    <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

        解决方案二:

          手动解码编码处理,如下:  

       @GetMapping(value="getChinese")
        @ResponseBody
        public void getChinese(String str) throws UnsupportedEncodingException {
            System.out.println(new String(str.getBytes("ISO-8859-1"),"UTF-8").toString());
        }

        解决方案三:

          自定义过滤器,统一处理乱码。

      二、post请求乱码

        在web.xml中添加乱码解决过滤器:

      <filter>
              <filter-name>CharacterEncodingFilter</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>
          <filter-mapping>
              <filter-name>CharacterEncodingFilter</filter-name>
              <url-pattern>/*</url-pattern>
          </filter-mapping>

        测试:

      @PostMapping("postChinese")
        public String postChinese(String str) {
            System.out.println(str);
            return "redirect:/test.jsp";//防止报错重定向到原界面
        }

      三、post响应乱码 

         通过produces告诉浏览器使用UTF-8解析服务器穿送过来的数据。

         相当于在响应头中添加ContentType("text/plain; charset=UTF-8")

      @RequestMapping(value="returnChinese",produces="text/plain;charset=UTF-8")
        @ResponseBody
        public String returnChinese() {
            return "返回中文";
        }
    "我们所要追求的,永远不是绝对的正确,而是比过去的自己更好"
  • 相关阅读:
    Matlab .asv是什么文件
    matlab中常数下的点是什么意思
    Matlab 根号的输入
    Paired t-test
    气血
    getCacheDir()、getFilesDir()、getExternalFilesDir()、getExternalCacheDir()
    ViewPager实现滑动翻页效果
    ViewPager结合Fragment进行无限滑动
    ViewPager结合view无限滑动
    Android的ToolBar
  • 原文地址:https://www.cnblogs.com/zomicc/p/12292851.html
Copyright © 2011-2022 走看看