gpt4 book ai didi

java - 如何在spring中设置sessionAttributes并在不同的jsps和 Controller 中访问它们

转载 作者:太空宇宙 更新时间:2023-11-04 07:05:57 24 4
gpt4 key购买 nike

我是 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/

关于java - 如何在spring中设置sessionAttributes并在不同的jsps和 Controller 中访问它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21371633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com