目录
1.提交的域名称和处理方法的参数名一致
form表单:
<form method="get" action="/u1/t1">
<input type="text" name="name">
<input type="submit" name="Submit">
</form>
处理方法:
@Controller
public class UserController {
@RequestMapping("/u1/t1")
public String test1(String name,Model modle){
System.out.println("输入的姓名为:"+name);
modle.addAttribute("msg",name);
return "hello";
}
}
2.提交的域名称和处理方法的参数名不一致
如提交的名称为username,处理方法中的参数为name
form表单:
<form id="form2" method="get" action="/u1/t2">
<input type="text" name="username">
<input type="submit" name="Submit">
</form>
处理方法:
@Controller
public class UserController {
@RequestMapping("/u1/t2")
public String test2(@RequestParam("username") String name, Model modle){
System.out.println("输入的姓名为:"+name);
modle.addAttribute("msg",name);
return "hello";
}
}
建议:无论名称是否一致,都建议使用@RequestParam
3.提交的是一个对象
要求提交的表单域和对象的属性名一致 , 参数使用对象即可
实体类
package com.pojo;
public class User {
private String name;
private int id;
private int age;
public User() {
}
public User(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
form表单:
<form id="form3" method="get" action="/u1/t3">
<input type="text" name="name">
<input type="number" name="id">
<input type="number" name="age">
<input type="submit" name="Submit">
</form>
处理方法;
import com.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
@RequestMapping("/u1/t3")
public String test2(User user, Model modle){
System.out.println("输入的姓名为:"+user.toString());
modle.addAttribute("msg",user.toString());
return "hello";
}
}
控制台输出:
返回页面: