I am new in jsp. I am trying to do redirection to login page when expire the session.
My code:
String sessionUser = null;
sessionUser = session.getAttribute("UserName").toString();
if(sessionUser == "" || sessionUser == null)
{
System.out.println("In login");
response.sendRedirect("login.jsp");
}
else
{
System.out.println("out login");
}
in above code i get error in line of
sessionUser = session.getAttribute("UserName").toString();
Error
HTTP Status 500 - An exception occurred processing JSP page
How can i do this?
From the error message and your description it seems you have written this code in JSP :
sessionUser = session.getAttribute("UserName").toString();
The above line can throw error if session is null or session doesn't have a UserName attribute .It is bad practice to write scriptlets in JSP.
You need to use a Filter to do anything closer to what you intend to do :
// Do not create session if it doesn't exist
HttpSession session = request.getSession(false);
// check if session is null
if(session != null) {
chain.doFilter(request, response);
} else {
// redirect to login page
response.sendRedirect("/login.jsp");
}
You can implement HttpSessionListener to listen to the session invalidation event. But a Listener is not a good choice here , because it is not tied to a request.
Related
#Override
public void sessionDestroyed(HttpSessionEvent arg0)
{
boolean isRemoved = sessionIdSet.remove(arg0.getSession().getId());
if (isRemoved)
{
arg0.getSession().invalidate();
System.out.println(arg0.getSession().getAttribute("userName"));
System.out.println("session destroyed");
}
}
Suppose the attribute userName was testUser at the time of login. So after timeout in my java console I get null and session destroyed printed. So if it is null that means when I do following in my jsp I should get null but instead still I get testUser
$("body").click(function(event){
var property="<%=session.getAttribute("userName")%>";
//Here I expect property to be null as session is destroyed
//and it prints null in java so it should also here.
alert(property);
//But what i get here is testUser
}
Using Spring interceptor
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
boolean allowRequest = true;
String requestUri = request.getRequestURI().toString();
HttpSession session = request.getSession(false);
logger.info("Pre-intercepting request URI: " + requestUri);
try {
if(null != session) {
String sessionBelongsTo = (String) session.getAttribute("CUR_TYPE");
String user = (String) session.getAttribute("userName");
System.out.println(user);
if(!requestUri.endsWith("/login") && !requestUri.endsWith("/loginauth") && !requestUri.endsWith("sap-ui-core.js") && !requestUri.endsWith("/main")) {
if(null == user) {
logger.info(""
+ "Login required, redirecting to LOGIN page");
response.sendRedirect(request.getContextPath() + "/login");
allowRequest = false;
}
else {
logger.info("Login not required");
}
}
}
else{
logger.debug("session is null.redirecting to login");
session = request.getSession();
response.sendRedirect(request.getContextPath() + "/login");
allowRequest = false;
}
}catch(IOException ioe) {
logger.info(ioe.getMessage());
allowRequest = false;
}
return allowRequest;
}
Using interceptor makes an redirect call GET http://localhost:9090/app/login which is successfull but redirect never really happens.
You are mixing two different codes. You have to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is send to the browser) and Javascript in the browser, after the browser receives the already generated response.
I.e. <%=session.getAttribute("userName")%> is processed on the server, and your browser receives e.g. var property="johndoe"; - the JSP code is NOT executed again when your onclick handler is executed.
I am very new to java servlet programming. I have been writing a simple program for practicing java session. There are two .jsp file. first one called index.jsp, and another one is selection.jsp. And there is a servlet called controller. At first the index.jsp will be called, and user will be submit a input. That will be redirect in servlet controller. In that servlet will check whether it is new request or not. If new then it redirect to other page, else will do some other work.
I am checking whether it is new request or not by session.isNew() method. But it always says it is not new session. But, if I disable the browser cookies option then it is working fine. Now what is my observation is that when in the first I request the index.jsp to the container it assign a session along with that request. So when it comes to servlet it treat as a old session. I got this idea from Head first book Servlet and JSP.
Here is my servlet code -
public class Controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user;
HttpSession session = request.getSession(false);
if (session == null) {
user = request.getParameter("user");
if (user == null) {
response.sendRedirect("index.jsp");
}
session.setAttribute("username", user);
SelectItem selectItem = new SelectItem();
selectItem.setUser(user);
response.sendRedirect("selection.jsp");
session.setAttribute("selectItem", selectItem);
} else {
String selectionItem = request.getParameter("selection");
SelectItem selectItem = (SelectItem) session.getAttribute("selectItem");
if (selectItem != null) {
selectItem.add(selectionItem);
session.setAttribute("selectItem", selectItem);
}
response.sendRedirect("selection.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
So, how to determine whether it is a new session or old one? Thank you.
HttpSession.isNew API:
Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.
So, you're getting true because the client has cookies disabled. The "new session" check in done in the else block of this check:
HttpSession session = request.getSession(false);
if (session == null) {
// create new session
session = request.getSession();
} else {
// existing session so don't create
}
In your code, you don't appear to be creating a new session when a new session is detected. Perhaps that's where you're stumbling.
Note: learning the basic Servlet API is a good thing. However, for my professional work I use frameworks which simplify my programming, like Spring Boot and Spring Security.
I'm trying so send a User object using HttpSession in login and retrieve data from jsps and some servlets.
Here is how I save object to session in login servlet.
HttpSession session = request.getSession();
User user = new User(1, 001);
user.setType(1);
session.setAttribute("user", user);
response.sendRedirect("index.jsp");
In index.jsp I do some dropdown name list loading.And when dropdown is clcked I go to this servlet. (That dropdown selection process is working perfect. This problem is occured after I use objects with session. Other time I only set values to session not entire object and never faced this problem.)
And here is how I retrieve them in servlet
HttpSession session = request.getSession(false);
if (session != null) {
User user = (User) session.getAttribute("user");
if (user != null) {
int userid = user.getId();
int usertype = user.getType();
} else {
System.out.println("NOOOOOO");
}
}
likewise I call this User object in several servlets. But sometimes when I refresh the page this user object is get empty. I don't know how to fix this. Is something wrong with my data retrieving method.
Thank you.
Suppose I have a servlet that processes logins. When the login is successful the user will create a session for this user. Then redirects to a homepage.
Let's say the homepage has a link "view all". This link calls a servlet, viewall.html to process all the data from the database then redirect to a jsp page (viewall.jsp) that will display the data from the servlet.
Somewhere from the servlet viewall.html to the jsp viewall.jsp, I would like to have code that looks like this:
if (session attribute user is null) {
// redirect to the login page
} else {
// if in the servlet, retrieve the data from the database
// if in the jsp, display the data
}
What is the better way to check if there is a session, on the servlet or the jsp? Note I know about filters, let's say the project can't use filters.
It is the same using a servlet of a filter. The general way is :
in the servlet that processes login you
create a new session
Session old = request.getSession(false); // first invalidate old if it exists
if (old != null) {
session.invalidate();
}
Session session = request.getSession(true); // next create one
put the user id as attribute of the session
session.setAttribute("USERID", userId);
then in the element (filter of servlet) where you want to know whether you have a registered user :
Session = request.getSession(false);
if ((session == null) or (session.getAttribute("USERID") == null)) {
response.sendRedirect(homeUrl);
return; // no need to process further (if in a filter no need to go down the chain)
}
in the servlet after controlling you have a logged on user, forward to the jsp
request.getRequestDispacher("/path/to/displayer.jsp").forward(request, response);
That's all ...
If you want to check this before creating, then do so:
HttpSession session = request.getSession(false);
if (session == null) {
// Not created .
session = request.getSession();
} else {
// Already created.
}
If you don't care about checking this after creating, then you can also do so:
HttpSession session = request.getSession();
if (session.isNew()) {
// newly created.
} else {
// Already created.
}
<% if(session.getAttribute("sessionname")==null)
{
response.sendRedirect("index.jsp");
else
{
String activeUser=session.getAttribute("sessionname").toString();
}
I hope it helps you
I am attempting to prevent users viewing a webpage if they are not logged in.
Currently the user is able to "login" which sets a cookie for 24 hours. I achieve this using AJAX which forwards to the admin page after creating the "loggedIn" cookie.
When a user navigates to MainController?page=logout it should delete the cookie and forward the user to the login page, which it appears to do.
But when navigating to MainController?page=admin the user should be forwarded to the login page if no cookies exist, but instead the admin page loads. I'm assuming that I'm not deleting the cookies properly?
Here is the AJAX call to check user credentials when logging in:
$("#loginForm").submit(function(e){
e.preventDefault(); //STOP default action
var postData = $("#loginForm").serializeArray();
var username = $("#username").val();
var password = $("#password").val();
var botCatcher = $(".botCatcher").val();
if(username.length > 3 && password.length > 3 && botCatcher.length == 0){
$.ajax(
{
type: "POST",
url : "MainController",
data : postData,
success: function(data)
{
if(data == "success"){
window.location.href = "MainController?page=admin";
}else if(data == "nope"){
$(".test").html("<p>Login details incorrect. Please try again.</p>");
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$(".test").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
}else{
$(".test").html("<p>Unable to login: ensure details are correct.</p>");
}
});
This is how I'm setting the cookie in the doPost method of the MainController servlet and outputing "success" to allow JQuery to forward to the admin webpage.
Cookie loggedIn = new Cookie("loggedIn", "true");
loggedIn.setMaxAge(60 * 60 * 24);
response.addCookie(loggedIn);
out.print("success");
This is how I control the navigation, as you can see the logout case should delete the cookie which means that the admin case should forward the user to the login page because the cookie object is null? Instead it loads the admin page. - This is actuated using a link on the admin page pointing to MainController?page=logout which is supposed to delete the cookie and forward to the login page, which it appears to do. But I can still navigate back to the admin page without needing to login.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String page = getPageName(request.getParameter("page"));
Cookie cookies[] = request.getCookies();
switch (page) {
case "admin":
if (cookies == null) {
page = "login";
return;
}
break;
case "logout":
for (Cookie cookie : cookies) {
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
page = "login";
break;
}
RequestDispatcher rd = getServletContext().getRequestDispatcher(views + getPageFilename(page));
rd.forward(request, response);
}
Why is it loading the admin page instead of forwarding to the login page ( and thus preventing users not logged in to view this page ). Am I not deleting the cookies correctly?