【问题标题】:How to create a session object?如何创建会话对象?
【发布时间】:2010-09-05 21:37:09
【问题描述】:

我正在为我的 Web 应用程序创建一个登录页面。我想在任何时候创建一个会话对象 一个新用户登录。我知道会话的概念,但我以前没有使用过。我可以用一个简单的课程来做吗?或者,我必须转移到 servlet。 如果我要使用简单的类方法,如何创建会话对象。


这是我的场景...

HTML 代码:

<table>
<tr>
<td>User Name: </td><td><input id="uName"  class="required" type="text" 
    size="5" /></td>
</tr>
<tr>
<td>Password: </td><td><input id="pwd"  class="required" type="text" size="5"
    onclick="login()"/></td>
</tr>
</table>

JS 代码:

function login(){
var userDetails = { uName : null, pwd : null };
dwr.util.getValues(userDetails);//Yes, i am using DWR.
LoginAuthentication.doLogin(userDetails, loginResult);
}

 function loginResult(nextPage){
window.location.href = nextPage;
}

Java 代码:

public class LoginAuthentication
{
public String doLogin(User user) throws SQLException, ClassNotFoundException{
    String userName = user.getUserName();
    boolean loginResult = verifyUser(user);//Another method that verifies user details with the DB.
    if (loginResult == true){
        /* Here I have to create session object,
          and i want to add the current username in that object. How to do it.*/

        return "MainPage.html";
    }
    else{

        return "loginRetryPage.html";

    }
   }

我得到的关于会话的概念非常简单明了。我必须在有效的用户输入后创建一个会话对象并将用户名添加到该对象,单击注销时销毁该对象。但我以前没有参加过会议。我的意思是,我不知道创建会话变量的语法。

如何在这里创建会话对象?

任何建议都会更感激!!!

提前致谢!!!

【问题讨论】:

  • 什么是“Java 代码”?它在哪个班?它是一个 servlet 吗?
  • @skaffman:哦,对不起。我现在会更新我的问题。
  • 这并没有真正的帮助...LoginAuthentication 是什么,它与其他任何东西有什么关系?
  • @skaffman:它只是一个类名。我删除了其他方法。也许我不知道如何根据用途命名一个类。

标签: java session servlets dwr


【解决方案1】:

在 servlet 中,使用以下行获取会话:

Session session = request.getSession();

要使用 DWR 获取 request 对象,您可以执行 (see here):

WebContext ctx = WebContextFactory.get();
HttpServletRequest request = ctx.getHttpServletRequest();

HttpServletRequest 包含浏览器发送到服务器的所有关于 HTTP 请求的数据)

【讨论】:

  • 什么是“请求”?它的目的是什么?
  • 感谢您的即时更新。我浏览了你的链接,它似乎对我有用。但是,你能解释一下什么是 WebContext。它会做什么?如果我添加这两行会发生什么? WebContext ctx = WebContextFactory.get(); req = ctx.getHttpServletRequest();
  • 是的,它会的。上面三行将为您提供 Session 对象,您可以在其中添加内容和检索内容。
【解决方案2】:

最好总是使用 request.getSession(false);登录成功后。

【讨论】:

  • 登录成功后是什么意思。它是关于检查用户名并通过数据库传递或创建会话对象。
猜你喜欢
  • 2011-01-20
  • 2017-07-16
  • 2013-02-24
  • 2023-03-15
  • 2011-11-15
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
相关资源
最近更新 更多