表单
收据用户填入的数据,并将这些数据提交给服务器
表单语法
- method请求方式有
- get(默认)提交时,数据跟在URL地址之后
- post提交时,数据在请求体内
- enctype在post请求时,指定数据的格式
- application/x-www-form-urlencoded(默认)
- multipart/form-data
- 其中表单项提供多种收集数据的方式
- 有name属性的表单项数据,才会被发送给服务器
<form action="服务器地址" method="请求方式" enctype="数据格式">
<!-- 表单项 -->
<input type="submit" value="提交按钮">
</form>
<form action="http://localhost:8090/test">
<input type="text" name="userName" value="用户名">
<input type="submit" value="提交按钮">
</form>
@Controller
public class HtmlTestController {
@GetMapping("/test")
@ResponseBody //对返回数据做一个处理
public String formTest(String userName){
System.out.println(userName);
return "数据接受成功:"+userName;
}
}
<form action="http://localhost:8090/test" method="post" enctype="multipart/form-data">
<!-- 文本框 -->
<input type="text" name="userName" value="用户名">
<hr>
<!-- 密码框 -->
<input type="password" name="passWord">
<hr>
<!-- 隐藏框 -->
<input type="hidden" name="id" value="T1">
<!-- 日期框 -->
<input type="date" name="birthday">
<hr>
<!-- 单选 -->
<!-- checked 默认选中 -->
男<input type="radio" name="sex" value="男" checked>
女<input type="radio" name="sex" value="女">
<hr>
<!-- 多选 -->
唱歌<input type="checkbox" name="fav" value="唱歌">
跳<input type="checkbox" name="fav" value="跳">
rap<input type="checkbox" name="fav" value="rap">
篮球<input type="checkbox" name="fav" value="篮球">
<hr>
<!-- 文件上传 -->
<!-- 在做文件上传时,form表单必须带上method 和 enctype 属性,且属性值应该是 post 和 multipart/form-data -->
<input type="file" name="avatar">
<hr>
<input type="submit" value="提交按钮">
</form>
@Controller
public class HtmlTestController {
@RequestMapping("/test")
@ResponseBody //对返回数据做一个处理
public String formTest(User user) {
System.out.println(user.toString());
return "数据接受成功:" + user.toString()+"\n"+"文件大小:"+user.getAvatar().getSize();
}
static class User {
private String userName;
private String passWord;
private String id;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate birthday;
private String sex;
private List<String> fav;
private MultipartFile avatar;
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public List<String> getFav() {
return fav;
}
public void setFav(List<String> fav) {
this.fav = fav;
}
public MultipartFile getAvatar() {
return avatar;
}
public void setAvatar(MultipartFile avatar) {
this.avatar = avatar;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", id='" + id + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", fav=" + fav +
'}';
}
}
}