SSM小技巧(一)、Controller中互相调用session中存储的内容

首先,你需要在一个Controller中往session中存内容(取的名字必须含有大写字母,虽然博主也不清楚为什么,如果有知道的人请一定要通知博主,博主将感激不尽):

@Controller
@SessionAttributes("Save") //①将ModelMap中属性名为currUser的属性
//放到Session属性列表中,以便这个属性可以跨请求访问
public class Test1Controller {
    @RequestMapping("save")
    public String save(Integer save,ModelMap model) {
        model.addAttribute("Save",save); //②向ModelMap中添加一个属性
        return "save";
    }
}
这个save数字将自动存储在session中,name为"Save"。


如果是要在同一个controller中调用,可以这么做:

@Controller
@SessionAttributes("Save") //①将ModelMap中属性名为currUser的属性
//放到Session属性列表中,以便这个属性可以跨请求访问
public class <span style="font-family: Arial, Helvetica, sans-serif;">Test1Controller </span>{

    @RequestMapping("save")
    public String save(Integer save,ModelMap model) {
        model.addAttribute("Save",save); //②向ModelMap中添加一个属性
        return "save";
    }
	
    @RequestMapping("get")
    public String get(@ModelAttribute("Save") Integer save,ModelMap model) {
        System.out.println("save:"+save);	//modelMap中的Save将自动绑定在save上
        return "get";
    }
}
我们即可在get中获得了保存在session中的Save对象


如果是要在其他controller中调用,可以这么做

@Controller
@SessionAttributes("Save") //①将ModelMap中属性名为currUser的属性
//放到Session属性列表中,以便这个属性可以跨请求访问
public class <span style="font-family: Arial, Helvetica, sans-serif;">Test2Controller </span>{

    @RequestMapping("get")
    public String get(@ModelAttribute("Save") Integer save,ModelMap model) {
        System.out.println("save:"+save);	//modelMap中的Save将自动绑定在save上
        return "get";
    }
}
方式相同,但需记住, 即使你不使用modelMap,仍需注入该对象,方法中仍需保留该参数,切记!!


以上便是博主在springmvc中的用法,如果大家有什么意见或者问题,可以直接在下方评论,博主将感激不尽!

猜你喜欢

转载自blog.csdn.net/death05/article/details/51457196