1.1. 使用实体类接收请求参数
Spring MVC 会按请求参数名和 实体类属性名进行自动匹配,自动为该对象填充属性值。支持级联属性。
@RequestMapping("/pojoParams") public String pojoParams(User user){ System.out.println(user); return "helloworld"; }
User.java:
package com.ibigsea.springmvc.model; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -5975751076183659876L; private String name; private int age; private Department department; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", department=" + department + "]"; } }
Department.java :
package com.ibigsea.springmvc.model; import java.io.Serializable; public class Department implements Serializable { private static final long serialVersionUID = 6881984318733090395L; private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Department [id=" + id + ", name=" + name + "]"; } }
JSP:
<h1>PoJo param</h1> <form action="pojoParams" method="post"> name:<input type="text" name="name"><br/> age:<input type="text" name="age"><br/> department id :<input type="text" name="department.id"><br/> department name :<input type="text" name="department.name"><br/> <input type="submit" value="submit"> </form>
运行结果:
User [name=bigsea, age=23, department=Department [id=1, name=test]]
1.2. ServletAPI 作为请求参数
@RequestMapping("/servletApi") public String servletApi(HttpServletRequest request,HttpServletResponse response,HttpSession session){ System.out.println("servletApi"); return "helloworld"; }
从源码中可以知道 spirngMVC 支持 9种 参数
javax.servlet.ServletRequest
javax.servlet.ServletResponse
javax.servlet.http.HttpSession
java.security.Principal
java.util.Locale
java.io.InputStream
java.io.Reader
java.io.OutputStream
java.io.Writer
时间: 2024-10-10 01:17:45