Click here to Skip to main content
15,890,336 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
Hey Friends,
I'm doing a project using JAVA,OOP and DAO techniques. In my project users can access pages after login. as an example i have a menu page which can see after login. think if some one trying to go to this page without login. then it should go to the login page with an error message.think I have 15 jsps and 10 servlets.Inside those there are so many attributes. cannot code same thing in every page.so my question is how to do that easily using DAO or OOP techniques?

Here is my UserServlet.java code

Java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String operation = request.getParameter("operation");
		if(operation!=null && operation.equalsIgnoreCase("displayMenu")){
			displayHomePage(request,response);
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	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("logout")){
			logoutSession(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";			    
				request.setAttribute("message", message);
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/menu.jsp");
				rd.forward(request, response); 
				HttpSession session = request.getSession(true);
			    session.setAttribute("loggedUser", u);
			    String reqUrl = (String)session.getAttribute("requestedURL");
			    session.removeAttribute("requestedURL");
				response.sendRedirect(reqUrl);				
			}else {
				String message = "You have to register first or check Your user name password again!";				
				request.setAttribute("loginMsg", message);
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/login2.jsp");
				rd.forward(request, response); 
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block			
			e.printStackTrace();
		}
	}
	private void logoutSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        
	    HttpSession  session = request.getSession();
	    session.invalidate();
		try{
			String message = "Logout!";	   
	        session.removeAttribute("loggedUser");  
	        session.invalidate();
			request.setAttribute("loginMsg", message);
			response.sendRedirect(request.getContextPath() + "/login2.jsp");
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
	private void displayHomePage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		HttpSession session = request.getSession(true);
		String nextPage = "/login2.jsp";
		if(session!=null){
			User user = (User)session.getAttribute("loggedUser");
			if(user!=null){
				nextPage = "menu.jsp";
			}else{
				request.setAttribute("errorMsg","Please Login...!");	
				session.setAttribute("requestedURL", "login?operation=displayMenu");
			}
		}
		//response.sendRedirect(nextPage);
		request.getRequestDispatcher(nextPage).forward(request, response);
		//response.sendRedirect(request.getContextPath() + "/Login.jsp");		
	}
}


home.jsp// index page of the project

ASP.NET
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<p>Welcome to DemoBank</p>	
	<p><a href="login?operation=displayMenu">Go to home page</a></p>	
</body>
</html>



home.jsp(index page of the project)->login.jsp->other pages(if login success)

if someone go to other pages it should directs to login.jsp->then it directs to above successfull path
Posted
Comments
[no name] 8-Jul-13 9:59am    
use Filter
mali_angel 8-Jul-13 23:01pm    
Can you explain step by step?
[no name] 9-Jul-13 3:35am    
you need a filter servlet, filter servlets are invoked before the actual resource, so you would have some checks to decide forward the request to the actual page or another page. a filter servlet is bind to some URLs, for example an admin filter servlet are listen to "/_admin/*" pattern, it means everything under _admin/ folder/name, so here you set the all URLs that need login to the filter, and just checks that user has loged in or not, if yes forward to the actual page, else forward to login page :D, if you still have problem I would provide a simple example too
mali_angel 9-Jul-13 4:12am    
please give Your example.

1 solution

Here is my FilterRequest.java file code

Java
public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
		try{
	      //HttpServletResponse responce = (HttpServletResponse) resp;
	      //HttpServletRequest request = (HttpServletRequest) req;	      
	      //String servletPath = request.getServletPath();
	      HttpSession session =  ((HttpServletRequest) req).getSession();
	      User u = (User) session.getAttribute("loggedUser");
	      System.out.println(u);
	      if (u!= null)
	      {
	         chain.doFilter(req, resp);
	         return;
	      }
	      /*if (servletPath.equals("/login2.jsp"))
	      {
	         chain.doFilter(req, resp);
	         return;
	      }*/else{
			String message = "Please Login!";				
			req.setAttribute("loginMsg", message);
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login2.jsp");
			rd.forward(req, resp); 
	      }	      
		}catch(Exception e){
			e.printStackTrace();
		}
	}


This is my web.xml Mapping code..

XML
<filter>
        <filter-name>FilterRequest</filter-name>
        <filter-class>com.mobitel.bankdemo.web</filter-class>
</filter>
    <filter-mapping>
        <filter-name>FilterRequest</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


when I run the project from the beginning it says "
SQL
The requested resource is not available.

"

Where i went wrong? please guide me
 
Share this answer
 
Comments
Shubhashish_Mandal 9-Jul-13 7:24am    
Same question over and over in all the post.Do something by yourself instead for asking each code.
[no name] 9-Jul-13 10:34am    
because your filter mapping is not good, try to put all login-required under /admin folder, then change the filter url pattern to /admin/*, the filter looks okay, the error you have got is because, MAYBE your web.xml has not configured probably, what is your root / resource? servlet? try to change the login2.jsp as welcome page

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