SpringMVC-接收数据和传递数据

接收数据

 @RequestMapping("/t3/t1")
    public String test1(String name){
    
    
        System.out.println(name);
        return "test";
    }

url:http://localhost:8080/t3/t1?name=张三
控制台打印:张三

    @RequestMapping("/t3/t2")
    public String test2(@RequestParam("name") String username){
    
    
        System.out.println(username);
        return "test";
    }

url:http://localhost:8080/t3/t2?name=李四
控制台打印:李四

public class User {
    
    
    private int id;
    private String name;

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
    @RequestMapping("/t3/t3")
    public String test3(User user){
    
    
        System.out.println(user);
        return "test";
    }

url:http://localhost:8080/t3/t3?name=李四&id=1
控制台打印:User{id=1, name=‘张三’}
这个和顺序无关

传递数据

1.ModelAndView

public class ControllerTest1 implements Controller {
    
    

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    
    
       //返回一个模型视图对象
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

2.ModelMap

@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
    
    
   //封装要显示到视图中的数据
   //相当于req.setAttribute("name",name);
   model.addAttribute("name",name);
   System.out.println(name);
   return "hello";
}

3.Model

@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
    
    
   //封装要显示到视图中的数据
   //相当于req.setAttribute("name",name);
   model.addAttribute("msg",name);
   System.out.println(name);
   return "test";
}

ModelAndView能传数据能设置跳转的视图。
ModelMap底层继承LinkedMap,可以使用LinkedMap的方法。
Model常用,是ModelAndView简化版,只需要传递数据即可。

猜你喜欢

转载自blog.csdn.net/qq_42665745/article/details/112971133