原文鏈接:https://blog.csdn.net/NNnora/article/details/80612491
一、 提交方式
表單可以通過get/post接口提交,在RequestMapping中不指定method那么get/post都可以訪問到,指定method=RequestMethod.POST則只能通過post方式訪問。
二、Controller層獲取表單數據的三種方式
1. 在方法簽名中添加HttpServletRequest參數,方法中通過HttpServletRequest.getParameter(“x”)方法得到對應的參數
2. 方法簽名中使用@RequestParam注解獲取表單字段對應的參數,有多少個字段就添加多少個對應的入參。
3. 添加自定義Java類型的對象參數,用來接收表單數據
使用該方式初次看起來寫的代碼要多,但是對象方式使得維護性高。
@RequestMapping(value="/user/save", method=RequestMethod.POST)
public ModelAndView saveUser(User user) {
StringBuilder sb = new StringBuilder();
sb.append("用戶名:"+user.getUsername());
sb.append("郵箱:"+user.getEmail());
sb.append("年齡:"+user.getAge());
String content = sb.toString();
return new ModelAndView("/wecome","result",content);
}
上面代碼中,自定義的User對象用來接收表單數據,user中有getUserName,getPassword等方法,獲取字段的值。
User類:
public class User {
private String username;
private String password;
public User() { //必須要有無參構造函數,否則報錯
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
//getter setter method...
}