SpringMVC-数据处理
处理提交数据
1. 提交的域名称与处理方法的参数名一致
- 提交数据【
http://localhost:8080/springmvc/hello?name=iris】 - 处理方法
 
/**
     * location: 8080/user/t1?name=xxx
     * @param name
     */
    @GetMapping("/t1")
    public String test01(String name, Model model) {
        // 接收前端参数
        System.out.println("接收到前端信息("+name+")");
        // 将返回结果传输至前端 -- Model
        model.addAttribute("msg", name);
        // 视图跳转
        return "test";
    }
- 后台输出 
接收到前端信息(iris) - 前端输出 
iris 
2. 提交的域名称与处理方法的参数名不同
- 提交数据【
http://localhost:8080/springmvc/hello?username=iris】 - 处理方法
 - 后台输出 
接收到前端信息(iris) - 前端输出 
iris 
3. 提交的是一个对象/JSON数据
所提交表单域须和对象的属性名一致,参数使用对象即可,否则对应属性值会为null
- 构建对应实体类
 
package cn.iris.pojo;
/**
 * @author Iris 2021/8/16
 */
public class User {
    private String name;
    private int age;
    public User() {
    }
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    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;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
- 提交数据【
http://localhost:8080/springmvc/user/t1?name=iris&age=20】 - 处理方法
 
/**
 * location: 8080/user/t1?name=xxx&age=xxx
 * @param user
 * @param model
 * @return
 */
@GetMapping("/t1")
public String test01(User user, Model model) {
    // 接收前端参数
    System.out.println("接收到前端信息("+user.getName()+","+ user.getAge()+")");
    // 将返回结果传输至前端 -- Model
    model.addAttribute("msg", user.toString());
    // 视图跳转
    return "test";
}
- 后台输出 
接收到前端信息(iris,20) - 前端输出 
User{name='iris', age=20} 
数据显示至前端
1. ModelAndView
public class ControllerTest01 implements Controller {
    public ModelAndView handlerRequest(HttpServletRequest req, HttpServletResponse resp) {
        
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "ControllerTest01");
        mv.setViewName("test");
        return mv;
    }
}
2. ModelMap
@GetMapping("/t3")
public String test03(ModelMap map) {
    map.addAttribute("msg","aaa");
    return "test";
}
3. Model
@Controller
@RequestMapping("/user")
public class UserController {
    @GetMapping("/t2")
    public String test02(@RequestParam("username") String name, Model model) {
    
        // 将返回结果传输至前端 -- Model
        model.addAttribute("msg", name);
        // 视图跳转
        return "test";
    }
}
对比
- ModelAndView (普通发售版)
 - ModelMap(继承于LinkedHashmap,Plus版)
 - Model(精简版,开发常用,具备常规功能)
 

                
            
        
浙公网安备 33010602011771号