Need help for login page using java servlet

Discussions

Web tier: servlets, JSP, Web frameworks: Need help for login page using java servlet

  1. Need help for login page using java servlet (7 messages)

    I have tried to develop a web application with page is login page by jsp and java servlet technology. But I get a problem when I first login with username and password correctly with database, it is successful forwarding to successful page(coding in servlet) then I tried to click on 'Go back' button on browser(Firefox)it return me back to login page with username and password value still there in textbox. After, I tried to login with wrong username and password so it successful redirect to login page and show error messge. But the problem here, when I click 'Go forward' button it send me to successful page without any checking username and password. Please, someones know how to fix this bug, give me a hint or solution and technique. Here are my codes: JSP page: userlogin.jsp User Login <% session = request.getSession(true); String username=""; String password=""; String error = ""; //if(!session.isNew()){ if(session.getAttribute("validated")!=null){ if(session.getAttribute("validated").toString().equalsIgnoreCase("false")){ if(session.getAttribute("Username")!=null)username = session.getAttribute("Username").toString(); error = "Login is failed, username or password could be incorrectly"; } session.setAttribute("validated","false"); response.getWriter().println(session.getAttribute("validated").toString()); } //} %>

    User login



    Please enter your Username and Password

    Username: Password:
    <%=error%>
    --%>
    Servlet: validator.java public class Validator extends HttpServlet { public void init(ServletConfig cfg) throws ServletException{ super.init(cfg); } /** Processes requests for both HTTP GET and POST methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Enumeration paramNames = request.getParameterNames(); HttpSession session = request.getSession(); out.println(""); out.println(""); out.println("Message"); out.println(""); out.println(""); try{ validate(request, session); if(session.getAttribute("validated").toString().equalsIgnoreCase("true")){ out.println("Successful"); } else{ session.setAttribute("Username",request.getParameterValues("Username")[0]); session.setAttribute("Password",""); response.sendRedirect("/OnlineForum/userlogin.jsp"); } }catch(SQLException ex){ out.println(""+"Servlet could not access database - "+ex.getMessage()+""); }catch(ClassNotFoundException ex){ out.println(""+"JDBC Driver not found - "+ex.getMessage()+""); } out.println(""); out.println(""); out.close(); } // /** Handles the HTTP GET method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ processRequest(request, response); } /** Handles the HTTP POST method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ processRequest(request, response); } public void validate(HttpServletRequest request, HttpSession session)throws SQLException, ClassNotFoundException{ boolean validated = false; ResultSet rs = accessDataTable("SELECT * FROM Users"); try{ if(rs != null){ while(rs.next()){ if(rs.getString("Username").toString().equals(request.getParameterValues("Username")[0]) && rs.getString("Password").toString().equals(request.getParameterValues("Password")[0])){ validated = true; session.setAttribute("Username", request.getParameterValues("Username")[0]); session.setAttribute("Password", request.getParameterValues("Password")[0]); } } } }catch(SQLException ex){ throw new SQLException(ex.getMessage()); } if(validated)session.setAttribute("validated","true"); else session.setAttribute("validated","false"); } public ResultSet accessDataTable(String sql)throws SQLException, ClassNotFoundException{ /*Connect to DBMS*/ Connection conn = null; Statement statement = null; ResultSet rs = null; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = DriverManager.getConnection("jdbc:odbc:DBMS"); statement = conn.createStatement(); rs = statement.executeQuery(sql); }catch(SQLException ex){ throw new SQLException(ex.getMessage()); } return rs; } /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } public void destroy(){ super.destroy(); }

    Threaded Messages (7)

  2. Without looking at all of your code, you may want to consider a change of approach. Instead of sending the user to a login page on the start, create a Servlet Filter that checks the authentication credentials stored in the session for each page in the protected domain. You can specify which pages fall under this domain and which do not in the web.xml file for the website. In the Servlet Filter, if the page falls inside the protected domain AND the session is not authenticated, then redirect the user to a login page, but be sure to store the URL they entered initially to redirect them to the right page once they have authenticated their session.
  3. Another thing you might want to take a look at is your validate method. First I would suggest that you do a better SQL query for the user (SELECT * FROM USERS WHERE USERNAME = ), use Java's PreparedStatement to handle the string quotes for you. PreparedStatement stmt = dbConnect.getConnection().prepareStatment("SELECT * FROM USERS WHERE USERNAME = ?"; stmt.setString(1, usernameVar); I would also take a closer look at what happens when you don't find the username. It looks like you may not be completely invalidating your session if you get the wrong username/password combination. I see that you set validate = false in the login page, but I didn't see where you removed the session variables username and password, this may be flawing your program when you log in successfully and then are still able to get in with a bad username/password combo. This session variables are still correct.
  4. Thanks your comment[ Go to top ]

    Again, I wanna thank for your comment and your SQL query you have suggested me, the SQL query is very nice. But as you said, I should have a servlet validated any page. Yes, I agree with you but you may didnt look at my codes. I try to let users login in the login page, when users login, the users will be redirect to my servlet validator. In first, the validator will try to validate user with the method validate(request, session). In this method I try to get username & password from DBMS to compare with username and password which users entered. If correct, session validated will be set to true value if not it is false. public void validate(HttpServletRequest request, HttpSession session)throws SQLException, ClassNotFoundException{ boolean validated = false; ResultSet rs = accessDataTable("SELECT * FROM Users"); try{ if(rs != null){ while(rs.next()){ if(rs.getString("Username").toString().equals(request.getParameterValues("Username")[0]) && rs.getString("Password").toString().equals(request.getParameterValues("Password")[0])){ validated = true; session.setAttribute("Username", request.getParameterValues("Username")[0]); session.setAttribute("Password", request.getParameterValues("Password")[0]); } } } }catch(SQLException ex){ throw new SQLException(ex.getMessage()); } if(validated)session.setAttribute("validated","true"); else session.setAttribute("validated","false"); Back to the first of servlet, after I validate user login then I try to check session validated. If it is true then write down 'successful', and if not then go back login page. validate(request, session); if(session.getAttribute("validated").toString().equalsIgnoreCase("true")){ out.println("Successful"); } else{ session.setAttribute("Username",request.getParameterValues("Username")[0]); session.setAttribute("Password",""); response.sendRedirect("/OnlineForum/userlogin.jsp"); } The problem is it works when the first time I try to login false, it redirect me back to login page, but after that I try login successful then I press 'Go back' button of the browser and try to login false again, it still work well mean I was redirected back to login page again but then I try press 'Go forward' button of the browser it will show validator page with 'successful' on the page same as last time when I login successful, that should be redirect me back to login page as same I press login button. The problem I wanna ask, why I press 'Go forward' button the method validate in servlet validator do not work well, as I think (just my mind, Im not sure)it does not perform servlet validator, it just return back the last page. I wanna know any solution to prevent this problem. Actually, when I try with the login page and a link to go back set in the validator page it works well in many time. But if I press the 'Go back' and 'Go forward' button of the browser it works unwell. I hope I can discuss with you this problem. regard
  5. --%> Is this really necessary? I think you can drop this line altogether, I've never used it before and all it seems to do is do a redirect which you aren't doing. You should also be able to drop these since you aren't overridding them (you only need to include them if you are overridding the superclass method or implementing a class): public void init(ServletConfig cfg) throws ServletException{ super.init(cfg); } public void destroy(){ super.destroy(); } I like your idea with this method below, but it makes it harder for you to use PreparedStatements and in this servlet you only use it once: public ResultSet accessDataTable(String sql) What I would suggest is that you create a Utilities.java class that holds common methods such as getting a DB connection, it will simplify your servlet code I also simplified your methods a little, you've been using request.getParameterValues() when you can use request.getParameter(). I also took the validate method and just passed it the username/password, this way the processRequest method handles all the request/session stuff. I removed most of the HTML code for simplicity in reading online. More comments are in the code in line comments. JSP: Login Form******************************************************************************************************

    User login

    <%=error%>
    Servlet: validator.java********************************************************************************************** public class Validator extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Enumeration paramNames = request.getParameterNames(); HttpSession session = request.getSession(true); out.println(""); out.println(""); out.println("Message"); out.println(""); out.println(""); String username = request.getParamter("Username"); String password = request.getParamter("Password"); try{ if(validate(username, password)){ session.setAttribute("validated","true"); session.setAttribute("Username", username); session.setAttribute("Password", password); out.println("Successful"); }else{ session.invalidate(); //lets do this just in case session.setAttribute("validated","false"); session.setAttribute("Username",username)); session.setAttribute("Password",""); response.sendRedirect("/OnlineForum/userlogin.jsp"); } }catch(SQLException ex){ out.println("Servlet could not access database - "+ex.getMessage()); }catch(ClassNotFoundException ex){ out.println("JDBC Driver not found - "+ex.getMessage()); } out.println(""); out.println(""); out.close(); } private boolean validate(String username, String password) throws SQLException, ClassNotFoundException{ boolean validated = false; if((username != null && username.length() > 0) && (password != null && password.length() > 0)){ /*Connect to DBMS*/ String sql = "SELECT Password FROM Users WHERE Username = ? AND password = ?"; Connection conn = null; PreparedStatement statement = null; ResultSet rs = null; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //move to utilities class getConnection() conn = DriverManager.getConnection("jdbc:odbc:DBMS"); //move to utilities class getConnection() statement = conn.prepareStatement(sql); statement.setString(1, username); statement.setString(2, password); rs = statement.executeQuery(sql); //You should get only one result, no need to loop through it. If you get no returns, validated should be assigned false validated = rs.next(); }catch(SQLException ex){ throw new SQLException(ex.getMessage()); } } return validated; }
  6. Connecting to Google Server[ Go to top ]

    Hi, am currently doing a project with Google server. The thing is that I should connect to the server using my gmail username n password. Am not able to understand how to authenticate the login variables with the google server.. Can u guide me??
  7. Need help..[ Go to top ]

    Hi I want to convert this to a JSP file. public static void main(String[] args) { while(true) { loginInfo[0] = null; loginInfo[1] = null; LoginScreen login = new LoginScreen(loginInfo); login.showLogin(); if (loginInfo[0] == null || loginInfo[1] == null) { return; } try { connection = new Connect(loginInfo[0], loginInfo[1]); break; } catch (MalformedURLException e) { Shell sShell = new Shell(); MessageBox errorBox = new MessageBox(sShell); errorBox.setMessage("Error: Malformed URL exception on login."); errorBox.open(); } catch (IOException e) { Shell sShell = new Shell(); MessageBox errorBox = new MessageBox(sShell); errorBox.setMessage("Error: IOException on login."); errorBox.open(); } catch (ServiceException e) { Shell sShell = new Shell(); MessageBox errorBox = new MessageBox(sShell); errorBox.setMessage("Error: ServiceException on login."); errorBox.open(); } } Can anyone please help me out.. Thanks..
  8. Errors..[ Go to top ]

    Hi, I am getting this error when am trying to load my login servlet.. exception javax.servlet.ServletException: Error instantiating servlet class appl.LoginServ org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619) root cause java.lang.NoClassDefFoundError: com/google/gdata/util/ServiceException java.lang.Class.getDeclaredConstructors0(Native Method) java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) java.lang.Class.getConstructor0(Class.java:2699) java.lang.Class.newInstance0(Class.java:326) java.lang.Class.newInstance(Class.java:308) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619) root cause java.lang.ClassNotFoundException: com.google.gdata.util.ServiceException org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233) java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) java.lang.Class.getDeclaredConstructors0(Native Method) java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) java.lang.Class.getConstructor0(Class.java:2699) java.lang.Class.newInstance0(Class.java:326) java.lang.Class.newInstance(Class.java:308) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619) Can anyone guide me about this?? Thanks..