java 在 Servlet 中创建会话并在 JSP 页面中使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11784108/
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
Create Session in Servlet and Use in JSP pages?
提问by HFDev
I want Create Session in CheckForLogin Servlet and Use it in all JSP pages(For checking). What should Write in my JSP pages and instead of ......... in Sevlet.How to define Session in Servlet?
我想在 CheckForLogin Servlet 中创建会话并在所有 JSP 页面中使用它(用于检查)。在我的 JSP 页面中应该写什么,而不是在 Sevlet 中写什么……如何在 Servlet 中定义会话?
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
if (email.equals("") || password.equals("") || email == null || password == null) {
request.getRequestDispatcher("Error.jsp?err=enterdata").forward(request,response);
} else {
UserBl userBl = new UserBl();
if (userBl.checkUser(email, password)) {
..........................
request.getRequestDispatcher("Home.jsp").forward(request, response);
} else {
request.getRequestDispatcher("Error.jsp?err=nulluser").forward(request, response);
}
}
}
回答by HFDev
I Should Write HttpServletRequest instead of ServletRequest and HttpServletResponse instead of ServletResponse in method parameters and then Create Session and access to session
我应该在方法参数中编写 HttpServletRequest 而不是 ServletRequest 和 HttpServletResponse 而不是 ServletResponse 然后创建会话并访问会话
回答by vinay kumar
to get existing session use
获取现有会话使用
HttpSession session=request.getSession(false);
HttpSession session=request.getSession(false);
回答by kosa
session
is jsp implicit variable using which you get session in JSP page.
session
是 jsp 隐式变量,使用它可以在 JSP 页面中获取会话。
example:
例子:
<%
String temp=session.getAttribute( "tvName");
%>
or using EL
或使用 EL
<c:out value="${session.getAttribute("name")}"/>
Note: Using scriptlets in JSP pages is not good practice.
注意:在 JSP 页面中使用 scriptlet 不是一个好习惯。
回答by axcdnt
Actually you can use <%= request.getSession() %>
for example.
其实你可以使用<%= request.getSession() %>
例如。
回答by Terry Gardner
Use ${sessionScope.sessionAttributeName}
in Expression Language in JSP code.
${sessionScope.sessionAttributeName}
在 JSP 代码中的表达式语言中使用。
回答by FrancescoAzzola
I suggest you use include
instead of forward
我建议你使用include
而不是forward
回答by Metalhead
you should use this line
你应该使用这条线
Session httpsession = request.getSession();
This line will create a new session object for you if one doesn't exist or it will return the existing session associated with the same client .
如果不存在,这一行将为您创建一个新的会话对象,或者它将返回与同一客户端关联的现有会话。