您的位置:首页 > 其它

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

2016-05-19 21:22 507 查看
首先,你需要在一个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中的用法,如果大家有什么意见或者问题,可以直接在下方评论,博主将感激不尽!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: