我正在使用 SpringMVC 编写 Web 应用程序。我想在用户注销之前保留一些数据。早些时候我是这样做的@SessionAttributes("someData")
,但后来我不得不@ModelAttribute("someData") someDataType someData
为每个请求映射方法输入参数。所以这就是我所做的:
我的 AccessData 类:
@Component
@Scope(value = "session")
public class AccessData {
private long userID;
private String userKey;
public AccessData(long ID, String key) {
this.userID = ID;
this.userKey = key;
}
public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
}
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
}
第一个控制器(这里我从表单获取并验证用户输入):
@Controller
@Scope(value = "session")
public class LoginController {
@ModelAttribute("accessData")
public AccessData getAccessData() {
return this.accessData;
}
private Utils utilsService;
private LoginService loginService;
@Autowired
private AccessData accessData;
@Autowired
public LoginController(LoginService loginService, Utils utils) {
this.loginService = loginService;
this.utilsService = utils;
}
@RequestMapping(value = ControllerPaths.LOGIN, method = RequestMethod.POST)
public ModelAndView showLoginStatus(
@ModelAttribute(LOGINDATA) LoginData loginData) {
try {
accessData = loginService.validateLoginData(loginData);
} catch (IncorrectLoginDataException e) {
logger.trace("Showing fail login screen...");
return utilsService.getShowView(ViewPaths.LOGIN_FAIL);
} catch (HTTPException e) {
return utilsService.getShowViewWithStringAttribute(
ViewPaths.INFO_VIEW, MESSAGE, CONNECTION_ERROR);
}
return utilsService.getShowView(ViewPaths.LOGIN_SUCCESS);
}
}
第二个控制器:
@Controller
@Scope(value = "session")
public class SecondController {
@ModelAttribute("accessData")
public AccessData getAccessData() {
return this.accessData;
}
private Utils utilsService;
private LoginService loginService;
@Autowired
private AccessData accessData;
@Autowired
public SecondController(LoginService loginService, Utils utils) {
this.loginService = loginService;
this.utilsService = utils;
}
@RequestMapping(value = ControllerPaths.SHOW_ACCESS_DATA, method = RequestMethod.GET)
public ModelAndView showAccessData(
System.out.println(accessData.getUserKey());
return utilsService.getShowView(ViewPaths.INDEX);
}
}
问题是当我在第二个控制器中打印 userKey 值时,该值为空。我检查了我是否从服务器中获取了正确的数据,LoginController
没关系。那么我做错了什么?提前感谢您的帮助