java - 我无法使用 HttpSession 保存会话属性
问题描述
我正在做一个登录测试应用程序,它以 JSON 格式接收用户名和密码,并将值与数据库进行比较。但由于某种原因,会话没有保存。这是我用于验证用户信息并保存会话的方法:
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response userLogin(Usuario us , @Context HttpServletRequest rq){
HttpSession session ;
//Search for the user with the username provided
Usuario user = usuarioService.getUsuario(us);
//Verify that user != to null
if(user != null){
//verify that password be the same that provided by the client
if(user.getPassword().equals(us.getPassword())){
//Set new Attribute in the session with the user info
session = rq.getSession(true);
session.setAttribute("username" , user.getUsername());
return Response.ok().entity("User:" +user.getUsername() + "has started session with success " + "Session ID : " +session.getId()).build();
}
else{
return Response.ok().entity("Wrong password, please verify and try again" ).build();
}
}else{
return Response.ok().entity("User : "+ us.getUsername()+ " name not found").build();
}
}
当我尝试调用保存用户名的会话属性“用户名”时,问题就来了。当我尝试使用检索当前会话 ID 的方法时,我发现它与添加用户名属性时的会话 ID 不同。接下来我用来验证会话信息的方法:
@GET
@Path("/checkSession")
@Produces(MediaType.APPLICATION_JSON)
public Response userLoginCheck(@Context HttpServletRequest rq){
//Call the current session information
HttpSession session = rq.getSession(false);
String msg;
//Verify if the session is new and return not session available
if( session == null){
msg = " Session not available" + session.getId();
return Response.ok().entity(msg).build();
}else if(session.getAttribute("username") == null){
msg = "Has been not possible call the required session SESSION ID : " + session.getId();
return Response.ok().entity(msg).build();
}
else{ //If session != null & attribute 'username' exist, then call 'username' attribute from the session
return Response.ok().entity(session.getAttribute("user")).build();
}
}
在此先感谢您提供解决此问题的任何帮助或想法。
解决方案
推荐阅读
- reactjs - 如何为 react-bootstrap 的活动选项卡切换 css 类?
- sql - 从其他列计算百分比值
- python - 如何使用 PyGame 计时器事件?如何使用计时器将时钟添加到 pygame 屏幕?
- python - Python tkinter GUI 列表框
- apache-kafka - kafka 只在指定时间后消费消息
- node.js - 节点js多次尝试捕获
- javascript - 如何根据其数据集并使用模板字符串选择元素?
- javascript - 将基本 JS 转换为 Perl
- vim - 自定义 vim-terraform 缩进
- text-to-speech - 如何以编程方式将阿塞拜疆文本转换为语音?