1.绑定默认数据类型
当前端请求参数较为简单的时候,后台形参可以直接使用SpringMVC提供的参数类型来绑定数据。
HttpServletRequest:通过request对象获取请求信息;
HttpServletResponse: 通过response处理响应对象;
HttpSession: 通过session对象得到session中存储的对象;
Model/ModelMap: Model是一个接口,ModelMap是一个接口的实现,作用是将Model数据填充到request域;
eg:
@Controller
public class UserController{
@RequestMapping("/selectUser")
public String selectUser(HttpServletRequest request){
String id=request.getParamter("id");
return "success";
}
}
2.绑定简单数据类型
对应的前端请求路径模式:
http://localhost:8080/projectName/selectUser?user_id=1
后台控制器如下:
@Controller
public class UserController{
@RequestMapping("/selectUser")
public String selectUser(@RequestParam Integer id){
System.out.println("id="+id);
return "success";
}
}
//@RequestParam的作用是什么?区分地址栏与前端的参数名的不同;
3.绑定POJO类型
传递多个参数时候,可以考虑用POJO类型。
eg:
User.java
package com.sjl.POJO; import java.io.Serializable; /*对多个数据进行封装*/
public class User implements Serializable {
private Integer id;
private String username;
private Integer password; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public Integer getPassword() {
return password;
} public void setPassword(Integer password) {
this.password = password;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password=" + password +
'}';
}
}
UserController.java
...... /**
* 向用户注册页面跳转
* */
@RequestMapping("/toRegister")
public String toRegister(){
return "register";
} /**
* 接收用户注册信息
* */
@RequestMapping("/registerUser")
public String selectUser(User user){
String username=user.getUsername();
Integer password=user.getPassword();
System.out.println("username:"+username);
System.out.println("password:"+password);
return "success";
}
......
register.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/registerUser" method="post">
用户名:<input type="text" name="username"/><br/>
密 码:<input type="text" name="password"><br/>
<br/>
<input type="submit" value="注册">
</form>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>结果页面</title>
</head>
<body>
<h1 align="center">OK!</h1>
</body>
</html>
未完待补充!