使用Sessions将值存储和检索到servlet [英] Storing and retrieving values from JSP to servlet using Sessions

查看:125
本文介绍了使用Sessions将值存储和检索到servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有login.jsp页面,我尝试用户名和文本框中的密码通过会话传递给servlet。代码o login.jsp如下:

I have login.jsp page where I try to username and password from text boxes are passed to servlet though session. The code o login.jsp is given below:

<form name="frm" action="DisplayData" method="post" onsubmit="return Validate()" >
    <table align="center">
        <tr>
            <td align="left">UserName:</td>
            <td><input type="text"  name="username" value=""></input></td>
        </tr>
        <tr>
            <td align="left">Password:</td>
            <td><input type="password"  name="password" value=""></input> </td>
        </tr>
    </table>
    <%
       String name = request.getParameter("username");
       String password = request.getParameter("password");
       session.setAttribute("name",name);
       session.setAttribute("pass", password);
    %>
    <table align="center">
        <tr>
            <input type="hidden" name="hiddenname" value="login">
            <td><input align="middle" type="submit" name="Sign_in" value="Sign_in"  onclick="return Validate()"></input></td>
            <td><input type="button" value="Signup" onClick="javascript:window.location='Signup.jsp';"></input></td>
        </tr>
    </table>
</form>

我想检索login.jsp中设置的用户名和密码到servlet。我尝试使用以下代码,但它给了我null值。我在servlet中使用的java代码如下:

I would like to retrieve the username and password that is set in login.jsp to servlet. I tried using the following code but it gives me null value. The java code I used in servlet is given below:

 HttpSession session = request.getSession(true);
    String name=(String)session.getAttribute("name");
    System.out.println("Welcome"+name);

有人能告诉我哪里出错了。我需要在会话中存储用户名,以便我可以在该servlet中使用它来进行多个请求

Could anyone tell me where I am making mistake. I Need the username to be stored in session so that I can make use of this for multiple request in that servlet

推荐答案

你是从 session.getAttribute(name)返回null,因为在呈现jsp时在会话中设置 name 属性。目前,未输入用户名。您需要做的是在servlet中使用 getParameter()获取用户名,并根据需要将其保存在会话中。

You are getting null being returned from session.getAttribute("name") because you are setting the name attribute in the session when the jsp is rendered. At this time, the username is not entered. What you need to do is get the username using getParameter() in the servlet and save it in the session if you want.

这篇关于使用Sessions将值存储和检索到servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆