|
Sponsored Links
Resources
Enterprise Java Research Library
Get Java white papers, product information, case studies and webcasts
|
Web tier: servlets, JSP, Web frameworks
Web tier: servlets, JSP, Web frameworks
Web tier: servlets, JSP, Web frameworks
|
Messages: 6
Messages: 6
Messages: 6
Printer friendly
Printer friendly
Printer friendly
Post reply
Post reply
Post reply
XML
XML
XML
|
 |
Need help for login page using java servlet
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 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User Login</title> </head> <body> <%@ page import="java.util.*" %> <% 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()); } //} %> <div align="center" style="font-size: 15pt; color: black"> <h3>User login</h3>
Please enter your Username and Password </div> <p></p> <div id="form" align="center"> <form name="UserLogin" id="UserLogin" action="/OnlineForum/build/web/WEB-INF/classes/Validator" method="POST"> <table border="0" cellspacing="1" cellpadding="1" id="UserLogin"> <tbody> <tr> <td align="right" width="140" bgcolor="pink" style="font-size: 12pt; color: red">Username:</td> <td bgcolor="pink"><input type="text" name="Username" id="Username" value='<%=username%>' size="30"/></td> </tr> <tr> <td align="right" width="140" bgcolor="pink" style="font-size: 12pt; color: red">Password:</td> <td bgcolor="pink"><input type="password" name="Password" value='<%=password%>' size="30"/></td> </tr> <tr> <td align="right" width="140" bgcolor="pink" style="font-size: 12pt; color: red"></td> <td bgcolor="pink"><input type="submit" value="Login" name="Login"/> <div align="left" style="font-size: 11pt; color: red"><%=error%></div> </td> </tr> </tbody> </table> <%--<jsp:forward page=""></jsp:forward>--%> </form> </div> </body> </html>
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("<html>"); out.println("<head>"); out.println("<title>Message</title>"); out.println("</head>"); out.println("<body>"); 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("</body>"); out.println("</html>"); out.close(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** 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(); }
|
|
Message #328576
Post reply
Post reply
Post reply
Go to top
Go to top
Go to top
|
 |
Re: Need help for login page using java servlet
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.
|
|
Message #328577
Post reply
Post reply
Post reply
Go to top
Go to top
Go to top
|
 |
Re: Need help for login page using java servlet
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.
|
|
Message #328691
Post reply
Post reply
Post reply
Go to top
Go to top
Go to top
|
 |
Thanks your comment
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
|
|
Message #328695
Post reply
Post reply
Post reply
Go to top
Go to top
Go to top
|
 |
Re: Need help for login page using java servlet
<%--<jsp:forward page="" />--%>
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****************************************************************************************************** <%@ page import="java.util.*" %> <% session = request.getSession(true); String username=""; String password=""; String error = ""; if(session.getAttribute("validated")!=null){ if(session.getAttribute("validated").toString().equalsIgnoreCase("false")){ if(session.getAttribute("Username")!=null){ username = session.getAttribute("Username").toString(); } error = "Login has failed, username or password incorrect"; } session.setAttribute("validated","false"); response.getWriter().println(session.getAttribute("validated").toString()); } %> <h3>User login</h3> <form name="UserLogin" id="UserLogin" action="/OnlineForum/build/web/WEB-INF/classes/Validator" method="POST"> <input type="text" name="Username" id="Username" value='<%=username%>' size="30"/> <input type="password" name="Password" value='<%=password%>' size="30"/> <input type="submit" value="Login" name="Login"/>
<div align="left" style="font-size: 11pt; color: red"><%=error%></div> </form>
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("<html>"); out.println("<head>"); out.println("<title>Message</title>"); out.println("</head>"); out.println("<body>"); 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("</body>"); out.println("</html>"); 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; }
|
|
Message #329395
Post reply
Post reply
Post reply
Go to top
Go to top
Go to top
|
 |
Connecting to Google Server
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??
|
|
Message #329399
Post reply
Post reply
Post reply
Go to top
Go to top
Go to top
|
 |
Need help..
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..
|
|
 |
Hot threads
Hot threads
Hot threads
|
More hot threads
More hot threads
More hot threads
|
 |
Brian Goetz continues to lift the lid and peak into the inner workings of Java in Java Urban Performance Legends. In this article he exposes the fallacy behind some of the more common performance myths found in the annals of the JVM.
(93 comments,
last posted
February 06, 2009)
Bruce Tate, author of Better, Faster Lighter Java and Bitter EJB has come out with a new book called Beyond Java. Bruce has an epiphany about the future of software development. Does it include Java?
(770 comments,
last posted
September 23, 2009)
Looks like today AJAX concept have several interpretations. We can distinguish different approaches of AJAX integration. Can they co-exist within the same application? Can we talk about layered AJAX integration?
(68 comments,
last posted
May 08, 2008)
Artima has published a short article describing the Design-Time API for JavaBeans, which was recently approved as JSR 273. This API promises to bring VB-like ease to Java development, but may face a cultural bias among Java developers who tend to think more in terms of class libraries than components.
(225 comments,
last posted
November 19, 2009)
There is plenty of speculation today regarding a potential buyout of Sun Microsystems by Scott McNealy and Silver Lake Partners. How would privatization of Sun affect Java?
(16 comments,
last posted
May 15, 2009)
More hot threads »
|
|