Java Spring Controller 獲取請求參數的幾種方法

技術交流羣:233513714

 

 一、直接把表單的參數寫在Controller相應的方法的形參中,適用於get方式提交,不適用於post方式提交。若"Content-Type"="application/x-www-form-urlencoded",可用post提交spring

       url形式:http://localhost:8080/SSMDemo/demo/addUser1?username=lixiaoxi&password=111111 提交的參數須要和Controller方法中的入參名稱一致。  json

複製代碼
/**
  * 1.直接把表單的參數寫在Controller相應的方法的形參中
  * @param username
  * @param password
  * @return
  */
 @RequestMapping("/addUser1")
 public String addUser1(String username,String password) {
   System.out.println("username is:"+username);
   System.out.println("password is:"+password);
   return "demo/index";
 }
複製代碼

 

二、經過HttpServletRequest接收,post方式和get方式app

複製代碼
/**
  * 二、經過HttpServletRequest接收
  * @param request
  * @return
  */
 @RequestMapping("/addUser2")
 public String addUser2(HttpServletRequest request) {
   String username=request.getParameter("username");
   String password=request.getParameter("password");
   System.out.println("username is:"+username);
   System.out.println("password is:"+password);
   return "demo/index";
 }
複製代碼

 

三、經過一個bean來接收,post方式和get方式post

複製代碼
/**
 * 三、經過一個bean來接收
 * @param user
 * @return
 */
@RequestMapping("/addUser3")
public String addUser3(UserModel user) {
  System.out.println("username is:"+user.getUsername());
  System.out.println("password is:"+user.getPassword());
  return "demo/index";
}
複製代碼

 

四、使用@ModelAttribute註解獲取POST請求的FORM表單數據ui

複製代碼
/**
   * 四、使用@ModelAttribute註解獲取POST請求的FORM表單數據
   * @param user
   * @return
   */
  @RequestMapping(value="/addUser5",method=RequestMethod.POST)
  public String addUser5(@ModelAttribute("user") UserModel user) {
    System.out.println("username is:"+user.getUsername());
    System.out.println("password is:"+user.getPassword());
    return "demo/index";
  }
複製代碼

 

五、用註解@RequestParam綁定請求參數到方法入參 url

當請求參數username不存在時會有異常發生,能夠經過設置屬性required=false解決,例如:spa

複製代碼
@RequestParam(value="username", required=false)
  **** 若"Content-Type"="application/x-www-form-urlencoded",post get均可以
  **** 若"Content-Type"="application/application/json",只適用get
   /**
   * 五、用註解@RequestParam綁定請求參數到方法入參
   * @param username
   * @param password
   * @return
   */
  @RequestMapping(value="/addUser6",method=RequestMethod.GET)
  public String addUser6(@RequestParam("username") String username,@RequestParam("password") String password) {
    System.out.println("username is:"+username);
    System.out.println("password is:"+password);
    return "demo/index";
  }
複製代碼

 

六、用request.getQueryString() 獲取spring MVC get請求的參數,只適用get請求code

@RequestMapping(value="/addUser6",method=RequestMethod.GET)
public String addUser6(HttpServletRequest request) { 
  System.out.println("username is:"+request.getQueryString()); 
  return "demo/index"; 
}
相關文章
相關標籤/搜索