Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
can anyone tell me how to use sessions in login methods? here my loging code and its working correctly.

Java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String operation = request.getParameter("operation");
		if(operation!=null && operation.equalsIgnoreCase("login")){
			loginDetail(request,response);
		}//else if(operation!=null && operation.equalsIgnoreCase("login")){
			//logout(request,response);
		//}
	}

	private void loginDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

		
		User u = new User();
		UserService us =new UserServiceImpl() ;
		
		String Uname = request.getParameter("txtUname");		
		String Pwrd = request.getParameter("txtPwrd");	
		
		u.setUname(Uname);
		u.setPwrd(Pwrd);
		
		System.out.println(Uname+""+Pwrd);
		try {
			if(us.Userlogin(u.getUname(),u.getPwrd())){     
				String message = "Thank you, " + Uname +"..You are now logged into the system";
				HttpSession session = request.getSession(true);
			    session.setAttribute("username", Uname);
			    session.setAttribute("password", Pwrd);	 		
		        response.setContentType("text/html");
			    request.setAttribute("message", message);
				request.getRequestDispatcher("/Menu.jsp").forward(request, response);
			}else {
				String message = "You have to register first or check Your user name password again!";				
				request.setAttribute("loginMsg", message);
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login.jsp");
				rd.forward(request, response); 
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block			
			e.printStackTrace();
		}
	}
}


If u need any futher details about my complete code please visit following link

http://www.codeproject.com/Messages/4603628/Re-Login-process-Always-false-cannot-find-the-erro.aspx[^]
Posted
Comments
Shubhashish_Mandal 4-Jul-13 3:07am    
where you stuck?
mali_angel 4-Jul-13 3:12am    
actually i do not knw how to put sessions in that login. i just put some lines but do not knw do rest of the process.please tell me from the begining.
mali_angel 4-Jul-13 3:13am    
if(us.Userlogin(u.getUname(),u.getPwrd()))

check inside this
Shubhashish_Mandal 4-Jul-13 5:04am    
you already did. you assign user name in session if valid user. Still I failed to understand what is your issue.
mali_angel 4-Jul-13 5:18am    
I cannot understand how to check this code. how do I know whether it is correct or not.

next time I don't want to login again to access the functionalities? So, I need to put a flag indicating the login status in the session object which span the life cycle of a specific time, e.g, 30 minutes. And the put a filter to query the flag every time a request comes to determine if the client has logged.

How am I going to do above things? here my another file of this project..


package com.mobitel.bankdemo.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class GetSession
*/
@WebServlet("/GetSession")
public class GetSession extends HttpServlet {
private static final long serialVersionUID = 1L;

public GetSession() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession(false);
try {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><body>");
// If user is not in a session then he is not logged in
if (session == null) {
String message = "You are not logged in!";
request.setAttribute("loginMsg", message);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login.jsp");
rd.forward(request, response);
//current user
} else if (!session.isNew()){
String message = "Thank you, you are already logged in...Here is the data in your session";
request.setAttribute("message", message);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/Menu.jsp");
rd.forward(request, response);
//new user
} else if((String)session.getAttribute("username")==null){
String message = "Time out please login!";
request.setAttribute("loginMsg", message);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login.jsp");
rd.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}</body></html>


Is this correct or not? what are my mistakes here

Thank you in advanced

Hello! :
When I read your question to the end and I think , you wanna keep the HttpSession life time. That link may be reference for you. In my opinion, to keep the Session time is like that
session.setMaxInactiveInterval(2 * 60 * 60); // two hours

I'm just Java Learner and if you know the better way, share us please. :)
 
Share this answer
 
Comments
mali_angel 4-Jul-13 7:21am    
thanx JasminHan309. im also a java learner. defenitly i ll share if i know anythng about this :)
JasminHan 4-Jul-13 7:39am    
You're welcome!! Angel ^^
This is more preferred way to set session time out in web.xml.
HTML
<session-config>
    <session-timeout>30</session-timeout>
  </session-config>


And to validate the each request(whether in same session or not) do the following steps

1. if login success, put a flag(user name in your case) into the session.
2. Create a filter which intercept each request.
3. Inside filter check whether logged user or not(to check logged user extract the flag info(here user name) from session ).
4. if logged user then continue otherwise redirect to the login page

Java
private void loginSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ 

   HttpSession session = request.getSession(true); 
   Object user = session.getAttribute("username");
   if(user == null){
      //go to log in page
   }else{
     //already logged in .
   }
}
 
Share this answer
 
v4
Comments
mali_angel 4-Jul-13 23:12pm    
how to do flag? is this a flag?
session.setAttribute("username", Uname);
Shubhashish_Mandal 5-Jul-13 2:22am    
yes..in this case "username" is flag. You can read this variable from session and check this whether null or not.if null that means the user is not a valid user.otherwise is a valid user
mali_angel 5-Jul-13 3:10am    
I Created This method to check login status. is this right? are there any mistakes? how do we check this code with different users?please tell me whether its correct or not. Thank you in advance

private void loginSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
HttpSession session = request.getSession(false);
try {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><body>");
// If user is not in a session then he is not logged in
if (session == null) {
session = request.getSession();
String message = "You are not logged in!";
response.setContentType("text/html");
request.setAttribute("loginMsg", message);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login.jsp");
rd.forward(request, response);
//current user
}else if(session.isNew()==true){
response.sendRedirect(response.encodeRedirectURL("Login.jsp"));
}
else if (!session.isNew()){
String message = "Thank you, you are already logged in...Here is the data in your session";
request.setAttribute("message", message);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/Menu.jsp");
rd.forward(request, response);
//new user
}else if((String)session.getAttribute("username")==null){
String message = "Time out please login!";
request.setAttribute("loginMsg", message);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login.jsp");
rd.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Shubhashish_Mandal 5-Jul-13 3:30am    
I have updated the existing solution.Check it

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900