基于POJO类型接收Client请求参数:
在实际中如果涉及到,网络通信、或者集群操作或者集群复制的话 这样的对象需要对其进行序列化,就需要实现Serializable接口;
POJO:User
package com.baizhiedu;
public class User {
private String name;
private String password;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
ParamController:param4
package com.baizhiedu;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/param")
public class ParamController {
//通过request获取求情参数
@RequestMapping("/param1")
public String param1(HttpServletRequest request){
String name=request.getParameter("name");
String password=request.getParameter("password");
System.out.println("name="+name);
System.out.println("password="+password);
return "param1";
}
//通过简单变量,获取请求参数
@RequestMapping("/param2")
public String param2(String name,String password){
System.out.println("name="+name+" password="+password);
return "param1";
}
//通过简单变量,获取请求参数,把http协议 传过来的字符串年龄,自动类型转换为整型
@RequestMapping("/param3")
public String param3(String name,Integer age){ //基本数据类型尽量使用包装器,如果不使用基本数据的包装类,如果在地址栏传值时没有给年龄int类型传值,默认为null,int类型不能接收null导致报错
System.out.println("name="+name+"age="+age);
return "param1";
}
//接收POJO类型的参数
@RequestMapping("/param4")
public String param4(User user){
System.out.println("User="+user);
return "param1";
}
//接收简单类型参数, POJO类型的参数
@RequestMapping("/param4")
public String param5(String name,User user){ //name形参和POJO里面的name属性都会获取内容
System.out.println("User="+user);
return "param1";
}
}
form.jsp:
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2022/6/3
Time: 15:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>">
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/param/param4">
UserName:<input type="text" name="name" /><br>
Password:<input type="text" name="password"/><br>
Age:<input type="text" name="age"/><br>
<input type="submit" value="reg">
</form>
</body>
</html>