Java 使用会话从 JSP 到 servlet 存储和检索值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23563961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing and retrieving values from JSP to servlet using Sessions
提问by Carol
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:
我有 login.jsp 页面,我尝试将文本框中的用户名和密码通过会话传递给 servlet。login.jsp 的代码如下:
<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>
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:
我想将 login.jsp 中设置的用户名和密码检索到 servlet。我尝试使用以下代码,但它给了我空值。我在servlet中使用的java代码如下:
HttpSession session = request.getSession(true);
String name=(String)session.getAttribute("name");
System.out.println("Welcome"+name);
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
谁能告诉我我哪里出错了。我需要将用户名存储在会话中,以便我可以将该用户名用于该 servlet 中的多个请求
回答by Priyesh
You are getting null being returned from session.getAttribute("name")
because you are setting the nameattribute 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.
您正在返回 null,session.getAttribute("name")
因为您在呈现 jsp 时在会话中设置了name属性。此时,不输入用户名。您需要做的是获取getParameter()
在 servlet 中使用的用户名,并根据需要将其保存在会话中。