1.参数绑定
参数绑定可以是常见类型也可以是对象、集合。springmvc可以自动将请求的参数和相应的属性进行绑定,不过规则是请求链接、表单中的名字和属性名相同。绑定对象、集合等需要用“.”。
1,javabean
package com.hhh.t1;
import java.io.Serializable;
public class User implements Serializable {
String name;
String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package com.hhh.t1;
import java.util.List;
import java.util.Map;
public class Account {
String id;
String num;
User user;
List<User> userList;
Map<String, User> userMap;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public Map<String, User> getUserMap() {
return userMap;
}
public void setUserMap(Map<String, User> userMap) {
this.userMap = userMap;
}
@Override
public String toString() {
return "Account{" +
"id='" + id + '\'' +
", num=" + num +
", user=" + user +
", userList=" + userList +
", userMap=" + userMap +
'}';
}
}
2、请求页面
<form action="paramTest" method="post">
id:<input name="id"/><br>
num:<input name="num"/><br>
user1name<input name="user.name"/><br>
user1age<input name="user.age"/><br>
user2name<input name="userList[0].name"/><br>
user2age<input name="userList[0].age"/><br>
user3name<input name="userMap['zero'].name"/><br>
user3age<input name="userMap['zero'].age"/><br>
<input type="submit" value="提交"/>
</form>
其中userList[0]表示集合中的第一元素,userMap[‘zero’]表示键为"zero"。
3、控制器编写
@Controller
public class ParamController {
@RequestMapping("/paramTest")
public String paramTest(Account account){
System.out.println(account);
return "success";
}
}
2.中文乱码过滤器的设置
在web.xml中添加
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
最终运行结果
控制台打印结果
Account{id='111', num=10, user=User{name='张三', age=20}, userList=[User{name='bbb', age=21}], userMap={zero=User{name='ccc', age=23}}}