springMVC数据传递

1 @RequestMapping的用法
可以放在类上也可以放在方法上,参数可以是一个字符串,也可以是字符串数组

@Controller
@RequestMapping(value = "/test")
public class HomeController {
    @RequestMapping(value = "/hello")
    public String hello(){
        return "index";
    }
}

@Controller
@RequestMapping({"/test","test1"})
public class HomeController {
     ……
}

2 传递模型数据到前端页面
1)返回前端页面路径

@RequestMapping(value = "/hello")
public String hello(Model model){
    List<Spittle> list = new ArrayList<Spittle>();
    model.addAttribute(list);
    return "index";
}

注:当调用addAttribute()方法不指定key时,那么key会根据值得对象类型推断确定,在上例中值是List,那么键值将是spittleList.如果想要显式得声明键值,这可以使用model.addAttribute(“spittleList”,list);如果不想使用model,也可以将其换成map,代码如下:

@RequestMapping(value = "/hello1")
public String hello1(Map map){
    List<Spittle> list = new ArrayList<Spittle>();
    map.put("spittleList",list);
    return "index";
}

2)直接返回数据到前端页面

@Controller
@RequestMapping({"/test","test1"})
public class HomeController {
    @RequestMapping(value = "/hello2")
    public List<Spittle> hello2(Map map){
        List<Spittle> list = new ArrayList<Spittle>();
        map.put("spittleList",list);
        return list;
    }
}

如果请求路径为:http://localhost:8080/test/hello2那么将会返回到webapp/WEB-INF/views/test/hello2.html这个视图,其中webapp/WEB-INF/views为Prefix路径

3重定向数据传递
1)简单的数据传递

@Controller
@RequestMapping({"/test","test1"})
public class HomeController {
    @RequestMapping(value = "/hello3")
    public String hello3(Map map){
        map.put("userName", "adadfasfdas");
        map.put("userId", "111111");
        return "redirect:/test/hello/{userId}";
    }
    ……
}

@RequestMapping(value = "/hello/{userId}")
public String hello(@PathVariable("userId")String userId, @RequestParam("userName") String userName){
    System.out.println(userName);
    System.out.println(userId);
    return "index";
}

测试
请求地址:http://localhost:8080/test/hello3
最终重定向后浏览器地址:http://localhost:8080/test/hello/111111?userName=adadfasfdas
管理台日志:
在这里插入图片描述

2)使用flash属性

@RequestMapping(value = "/hello4")
public String hello4(RedirectAttributes model){
    Map<String, String> userMap = new HashMap<String, String>();
    userMap.put("userName", "adadfasfdas");
    userMap.put("userId", "111111");
    model.addFlashAttribute("userMap", userMap);
    model.addAttribute("userId", "111111");
    return "redirect:/test/hello/{userId}";
}

@RequestMapping(value="/hello/{userId}")
publicStringhello(@PathVariable("userId")StringuserId,Modelmodel){
Map<String,String>userMap=(HashMap<String,String>)model.asMap().get("userMap");
System.out.println(userMap.get("userName"));
System.out.println(userId);
return"index";
}

测试
请求地址:http://localhost:8080/test/hello4
最终重定向后浏览器地址:http://localhost:8080/test/hello/111111
管理台日志:
在这里插入图片描述

发布了98 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/musi_m/article/details/103880411