解決post請求亂碼問題


1、請求:

<form action="param/test1" method="post">
    userId:<input type="text" name="userId"><br>
    userName:<input type="text" name="userName"><br>
    <input type="submit" value="提交">
</form>

2、實體類:

package com.ly.springmvc.domain;

import java.io.Serializable;

public class User implements Serializable {
    private Integer userId;
    private String userName;

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                '}';
    }
}

3、處理方法:

@RequestMapping("/param/test1")
public String testParam4(User u) {
    System.out.println("testParam4");
    System.out.println(u);
    return "success";
}

4、總結:

4.1、表單若為GET請求方式時中文不會亂碼

4.2、表單若為POST請求方式時中文會亂碼,解決中文亂碼的方式:在web.xml中配置CharacterEncodingFilter過濾器

  <!--解決POST請求中文亂碼-->
  <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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM