我是 spring&java 的初学者。如何正确地将 UserDetailedInfo 模型传递到 SessionAttrtibutes 中以在不同的 Controller 和不同的 jsps 中访问它?我正在尝试使用 spring 框架创建一个登录系统。
//this is my mainpagecontroller.java
@Controller
@SessionAttributes("model")
public class MainPageController{
@RequestMapping(value="/signin", method=RequestMethod.POST)
@ResponseBody
public Map<String, Object> userSignIn(@RequestParam Map<String,String> param, ModelMap sessions) throws UnsupportedEncodingException {
FormHelpers helper = new FormHelpers();
Map<String, Object> resp = new HashMap<String, Object>();
resp.put("status", helper.signIn(param).getError());
sessions.addAttribute("model",resp);
System.out.println(resp);
//System.out.println(info.get);
return resp;
}
}
//formhelpers.java
public UserDetailedInfo signIn(Map<String, String> data) {
Map<String, String> params = new HashMap<String, String>();
SigninModel model = new SigninModel();
model.setEmail(data.get("email"));
model.setPassword(data.get("password"));
params.put("email", model.getEmail());
params.put("password", model.getPassword());
try {
ObjectMapper mapper = new ObjectMapper();
String response = GlobalHelper.callService(RestServicesUrl.SIGNIN_URL, params);
UserDetailedInfo info = mapper.readValue(response, UserDetailedInfo.class);
System.out.println("error"+info.getError());
return info;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new UserDetailedInfo();
}
}
//singedinhomepagecontroller.java
@Controller
@RequestMapping(value="/main")
@SessionAttributes("model")
public class SignedInHomePageController
{
@RequestMapping(method=RequestMethod.GET)
@ResponseBody
public ModelAndView displaySignInHomePage(@ModelAttribute FormHelpers model)
{
ModelAndView view = new ModelAndView("homepage");
System.out.println(model.signIn().getEmail()); //unable to access the from session
return view;
}
}
//home.jsp
在参数上使用http session 并设置属性和获取属性方法
public ModelAndView test(HttpSession session)
{
session.setAttribute("success" , "successfully accessed");
}
然后在其他 Controller 方法中
public ModelAndView test(HttpSession session)
{
String sessionVar = session.getAttribute("success");
}
关于创建登录系统我建议使用http://projects.spring.io/spring-security/
我是一名优秀的程序员,十分优秀!