今天在我的springMVC项目——图书管理系统中,希望在登录时将登录的Users存在session中,开始是准备在controller中使用Servlet API中的对象,可是一直无法引用,不知道为什么,难道是要导入什么特定的包吗(如果有知道的朋友,可以的话麻烦留言告诉我下,谢谢了),然后看见网上说可以用@SessionAttributes和@ModelAttribute注释来实现,具体实现如下:
UserController类:
@Controller
@SessionAttributes("userid")//①将ModelMap中属性名为"users"的属性
//放到Session属性列表中,以便这个属性可以跨请求访问
public class UserController {
@Autowired
private UserService service;
@Autowired
private BooksService booksService;
public UserService getService() {
return service;
}
public void setService(UserService service) {
this.service = service;
}
@RequestMapping(value="register")
public String register(String name,String password,Map<String, Object> params){
Users users=new Users();
users.setName(name);
users.setPassword(password);
users.setPoint(0);
users.setType(0);
users.setLevel(0);
service.save(users,params);
params.put("userName", name);
if(params.get("ErrMsg")!=null){
return "register";
}
return "reg_success";
}
@RequestMapping(value="login")
public String login(Users users,ModelMap map){
Users users2 = service.findUsers(users);
if(users2==null){
map.put("ErrMsg","输入有误,请重新输入");
return "";
}
map.put("users", users2);
map.addAttribute("userid", users2.getId());
if(users2.getType()==0){
List<Books> booksList = booksService.findAllBooks();
map.put("booksQueryList", booksList);
map.put("books", new Books());
return "visitor_first";
}else{
return "manager_first";
}
}
}
在另一个要调用userid的BookInfoController中:
@Controller
@SessionAttributes("userid")
public class BookInfoController {
@Autowired
private BookInfoService service;
@Autowired
private BooksService booksService;
@Autowired
private UserService userService;
@Autowired
private RecordsService recordsService;
@RequestMapping(value = "bookInfos")
public String bookInfoList(@RequestParam("bid") int bid, Map<String, Object> map) {
List<BookInfo> bookInfos = service.findBookInfoByBid(bid);
Books books = booksService.findBooksById(bid);
map.put("bookInfoList", bookInfos);
map.put("books", books);
return "bookInfoList";
}
@RequestMapping(value="lendBooks")
public String lendBooks(@RequestParam("id") int id,@ModelAttribute("userid")int uid,Map<String,Object> map){
service.updateBookInfo(id);
System.out.println("userId:"+uid);
BookInfo info = service.findBookInfoById(id);
Records records=new Records();
Users users = userService.findUsersById(uid);
records.setUsers(users);
records.setInfo(info);
records.setLendTime(new Date());
recordsService.addRecords(records);
map.put("Msg","借书成功");
return "saveShow";
}
}
上面这样已经试验成功,但成功之前还是走了不少弯路:
1.开始的时候,我在@SessionAttributes中保存的是持久态的(有id值)users对象,可是在@ModelAttribute中取得的users对象的id值每取一次就自增长,其他的属性都没变,我不知道是我建表有问题还是配置文件有问题,找了半天也没有找到,有知道的朋友也麻烦留言告诉我下吧。
2.在网上查询时看见一位朋友说@SessionAttributes(“userid”)中的“userid”必须要包含一个大写字母,经我试验,完全没有必要啊!
努力努力再努力!