注册时需要将用户名、密码、邮箱等信息封装成User类传入Controller
并且在用户输入这些信息时要异步查询服务器看看有没有异常,将异常异步返回到页面
1 实体类DemoUser
package com.nowcoder.community.entity;
public class DemoUser {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "DemoUser{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2 Controller
@RequestMapping(path = "/regist",method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> test(DemoUser user){
Map<String, Object> map = new HashMap<>();
if(user==null){
map.put("error","未收到DemoUser类");
}else{
map.put("success","收到DemoUser类");
System.out.println(user);
}
return map;
}
3 前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<form action="/community/regist" method="post">
用户名:<input name="username" type="text"/><br>
密码:<input name="password" type="password"> <br>
<input type="submit" value="注册">
</form>
</body>
</html>
该页面的路径为static/html/demo-regist.html 用localhost://8080/community/html/demo-regist.html可以访问到。community是项目名
4 测试
证明底层确实可以将表单提交的数据封装成类传给Controller 猜想过程是:请求提交后DispatcherServlet传给相应的Controller方法,该方法的输入参数有User,那就从表单提交的数据里匹配User类的属性,前端的name值与User类的属性名一致就将起赋值给该属性,这样将数据封装成User类再传给Controller方法 要看源码确认
|