when a user logins to my application, he submits a form to be processed through the Servlet. The servlet creates a session for the user. How would I create a link so the user can logout? I cannot seem to directly link to a Servlet. How would I delete the session and link back to the homepage?
Here is a way that I could do it, but it doesn't seem "right".
I could link back to the index.jsp?logout=true. My index.jsp will see if logout is true and delete the sessions.
Is there another way to do it?
Write a servlet mapped to /logout which then executes something like this in doGet:
HttpSession session = request.getSession(false);
if(session != null)
session.invalidate();
request.getRequestDispatcher("/index.jsp").forward(request,response);
It wont matter if the user has a session or not, they will ultimately be redirected to index.jsp.
I found it easiest to do this:
<form method="link" action="logout.jsp">
<input type="submit" value="Logout"/>
</form>
without logout.jsp having this:
<%
session.invalidate();
response.sendRedirect("startpage.html");
%>
Simplest way to do that is make a link of logout like this..
LogOut
And in the "logout.jsp" write below code
<%
session.invalidate();
response.sendRedirect("index.jsp");
%>
logout is not too serious. you can have a simple /logout.jsp just to end session.
Based on cdietschrun's answer, I've made it even more compact:
<%
session.invalidate();
response.sendRedirect(request.getContextPath());
%>
Related
I have this similar question in this forum while learning jsp to build a login/logout on the top menu bar. I wonder is it the same way to use session and should this session object be in LoginServlet or SessionServlet to control this UI behaviour, and how can I achieve this result if I use MongoDB with the session?
It depends where your login/logout will lead to. In the grand scheme, it really doesn't matter. For example, if you chose to direct it towards LoginServlet, you would handle it like so:
HttpSession session = request.getSession();
if(session.getAttribute("ATTRIBUTE")==null){//Make sure that when the user logs in, you set the attribute
//They are not logged in
response.sendRedirect("Login.jsp");
}else{
//They are logged in
response.sendRedirect("Home.jsp");
}
If you want to display whether the user is logged in or logged out, you can use the <c:choose> tag like so:
<c:choose>
<c:when test="${sessionScope.username != null}">
You are logged in!
</c:when>
<c:otherwise>
You are not logged in :(
</c:otherwise>
</c:choose>
Don't forget to important the taglib above the <head>:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
I am trying to forward my error message back in my login page if user keys in the incorrect password. It works for the first try, but when user retype password regardless of the right or wrong password, it will then return me HTTP Status 404
For an example , in user login JSP .. If user is log in as user,
I will do a condition that it will sendRedirect to user page. where else if user is sign in as Admin , it will sendRedirect to Admin page. ---- This part , it is working perfectly good , i am using dispatcher ----
For an example in the code structure i did
login.jsp
<form action="../loginController" method="post">
<p> Username : <input type="text" id="name" name="username" required/</p>
<p> password : <input type="text" name="password" required/> </p>
<button type="submit"> Submit </button>
</form>
<h2><%=request.getAttribute("errorMessage") %></h2>
/-- It should redirect back to this page when user keys in the wrong password . which in the url should input it as .../login.jsp ---/
/--
I created a servlet file , i call it loginController . My user data i retrieve is from oracle. Everything from fetching of data is perfectly fine
The only problem is when im doing the condition.
---/
Servlet is loginController.java
if(loginRS.equals("user")){
response.sendRedirect("User/User.jsp"); /*--This is working --*/
} else if(loginRS.equals("admin")){
response.sendRedirect("Admin/Admin.jsp"); /*--This is working --*/
} else if(loginRS.equals("IncorrectPassword")) {
/*--- This is where the problem starts ---*/
RequestDispatcher rd =
request.getRequestDispatcher("./Login/login.jsp");
request.setAttribute("errorMessage", "Username Not found");
rd.forward(request, response);
/--Up till here, the code is working , the only problem is that it is storing inside servlet.java rather than to forward it back to login.jsp--/
/-- This is where the problem starts, When i key in the wrong password , it returns errorMessage as username not found. BUT in my urlPath , it states that it is still inside LoginController. if in the second try , i were to input the correct password , it return me 404 page not found --/
I thought of putting this code below to redirect it back to login.jsp if the condition is called. but i am unable to sendreDirect it.
response.sendRedirect("./Login/login.jsp");
}
Thank you in advance
SOLVED
Basically the problem I was facing was my connection , hence its leading to error 404
Try removing ./ or . from request.getRequestDispatcher("./Login/login.jsp");
I doing some project based on authentication using servlet/jsp.When user log in initially using username and password where authentication takes place through login servlet,there I need to save user's email in variable ,say String email by executing SELECT query.
I need to access that variable from login servlet to email servlet for sending some sort of OTP to user's email.
How to achieve that using session attribute or any relevant idea??
Use session.setAttribute() and session.getAttribute() methods.
Read javadoc of HttpSession here.
You can refer this complete example.
To save data in session you should use session object from http request like this:
HttpSession session = request.getSession();
session.setAttribute("email", email);
To retrieve data from session object with scriptlet use:
<%= session.getAttribute("email")%>
or
<%= request.getSession().getAttribute("email")%>
You can also use EL expression:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${sessionScope.email}"/>
please use as follows. you can achieve what you need.
<%session.setAttribute( "email", "test#gmail.com" );%>
<%= session.getAttribute( "email" ) %>
The other way that we use.
<c:set var="email" value="test#gmail.com" scope="session"/>
you get this using JS:
var mail ="${email}";
I am writing a JSP code which goes like this:
<% if(---)
{----}
else
{ ---
%>
<jsp:forward page="error.jsp">
<jsp:param name="" value=""/>
</jsp:forward>
<%
}
%>
The error.jsp is in the same directory as the current jsp file still it is throwing "class not found exception". What to do?
Not much clear from your question what you are trying to achieve but If you are adding the another jsp page within current jsp page then use jsp:include otherwise if trying to redirect to another jsp page then following could be used.
Use in scriptlet response.sendRedirect in your case as below:
<%
response.setHeader("header_key", "header_value");
response.sendRedirect("your_page_location")
%>
Above could be used for external pages as well like "www.google.com"
On the other hand you could use request forward with all old parameters and data from calling page. See below:
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);
Also, another easy way could be to submit a form with action="your_jsp.jsp" but this should be used in case of form submissions where you are sending some data etc.
Make choice for any of above options on a case basis.
Hope it helps!
here is my samle request.jsp
pageContext.setAttribute("test", "ccavenue", PageContext.SESSION_SCOPE);
<form id="nonseamless" method="post" name="redirect" action="http://test.ccavenue.com/transaction/transaction.do?command=initiateTransaction"/>
<input type="hidden" id="encRequest" name="encRequest" value="<%= encRequest %>">
<input type="hidden" name="access_code" id="access_code" value="<%= accessCode %>">
<script language='javascript'>document.redirect.submit();</script>
</form>
here is my response.jsp like
String test = (String) pageContext.getAttribute("test", PageContext.SESSION_SCOPE);
out.print(test);
i am setting the pageContext value in request.jsp, redirect the request to ccavenue site and they send the response to response.jsp but in response.jsp getting the pageContext value is null
please help me!
Try using session instead:
session.setAttribute("test", "ccavenue");
response.jsp
String test = (String) session.getAttribute("test");
pageContext.setAttribute():
From docs
Session scope (only valid if this page participates in a session): the
named reference remains available from the HttpSession (if any)
associated with the Servlet until the HttpSession is invalidated.
PageScope
What you put on your page scope is available only for the JSP page
that put it. Any other page in the same request included via or
forwarded will not see object in the first page scope.
May be you should try Session scope or Request Scope for that !!
Instead of pageContext use request.setAttribute("val","value") in request.jsp and request.getAttribute("val") in response.jsp or set to session and use value="${value}" in jsp