Solved

code to Store username and password in flat file locally and retrive it.

Posted on 2009-04-06
12
731 Views
Last Modified: 2013-12-18
Hi I want to convert this JSP code to store a single user defined by me (let admin) and a password (admin123) in a flat file locally. and when a user logsin with admin username it should check and authenticate from the flat file only and redirect to Browser.jsp page.
<%@ page language ="java" import="java.sql.*" %>

<html>

<body bgcolor="pink">

<form name="f1" method="post">

<table>

<tr>

<td>User Name</td><td><input type="text" name="t1" ></td>

</tr>

<td>Password</td>

<td><input type=""password"" name="t2"></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="b1" value="LogIn"></td>

</tr>

</table>

<%

String user=request.getParameter("t1");

String pass=request.getParameter("t2");

 

     try{

    

     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

     Connection con=DriverManager.getConnection("jdbc:odbc:mydsn", "jp", "jp");

     Statement st=con.createStatement();

     ResultSet rs=st.executeQuery("select username,password from userlog");

     while(rs.next())

         {

         String username=rs.getString(1);

         String password=rs.getString(2);

         if(user.equals(username) && pass.equals(password))

             {

             %>

             <jsp:forward page="/Training_solutions/LoginSuccess.jsp" />

         <%}

         else

         out.println("Login Failed,Please try Againe");

         %>

        

         <%

     }

}catch(Exception e1)

{}

 

%>

 

</form>

</body>

</html>

Open in new window

0
Comment
Question by:Ramakanta Sahoo
  • 5
  • 5
  • 2
12 Comments
 
LVL 27

Expert Comment

by:rrz
ID: 24077184
You could use something like the code below here.
Manually create a file named    pass.properties  and put it  into your class path.
In that file  write
admin=admin123  
In LoginSuccess.jsp   check for  signedIn  attribute
String signedIn = session.getAttribute("signedIn");
<%@ page import="java.util.Properties,java.io.IOException" %>

<%!

               Properties props = new Properties();

               public void jspInit(){

                       try{

                           props.load(getClass().getResourceAsStream("/pass.properties"));

                          }catch(IOException ioe){System.out.print("can't get pass props");}

               }

%>

<%

  String name = request.getParameter("t1");

  String password = request.getParameter("t2");

  if(name != null && password != null){

    name = name.trim();

    password = password.trim();

    if(password.equals(props.getProperty(name))){   

       session.setAttribute("signedIn","true"); 

       session.setAttribute("username",name); 

       RequestDispatcher rd = request.getRequestDispatcher("/Training_solutions/LoginSuccess.jsp");

       rd.forward(request,response);

    }else out.print("Login Failed,Please try Again");

  }else out.print("Login Failed,Please try Again");

%>

Open in new window

0
 
LVL 6

Expert Comment

by:SamsonChung
ID: 24078195
Hmm... what exactly do you mean?

Did you mean to ignore all users and just verify 'admin' only?

Or do you mean that when username != "admin" use myDSN.
while username == "admin" use flat file stored on Server?

If this is the case....look at the new if condition i've added.

I didn't type in the code because it is relatively simple, just load the file, bufferread it, decode it and compare it.
<%@ page language ="java" import="java.sql.*" %>

<html>

<body bgcolor="pink">

<form name="f1" method="post">

<table>

<tr>

<td>User Name</td><td><input type="text" name="t1" ></td>

</tr>

<td>Password</td>

<td><input type=""password"" name="t2"></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="b1" value="LogIn"></td>

</tr>

</table>

<%

String user=request.getParameter("t1");

String pass=request.getParameter("t2");

 

     try{

    if (t1.equals("admin"){

     //add a file loader here

     //add a read buffer here.

     //decode while reading in lines. 

     //verify decoded password with input t2.

     //go to page

%>

             <jsp:forward page="/Training_solutions/LoginSuccess.jsp" />

         <%

    } else {

     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

     Connection con=DriverManager.getConnection("jdbc:odbc:mydsn", "jp", "jp");

     Statement st=con.createStatement();

     ResultSet rs=st.executeQuery("select username,password from userlog");

     while(rs.next())

         {

         String username=rs.getString(1);

         String password=rs.getString(2);

         if(user.equals(username) && pass.equals(password))

             {

             %>

             <jsp:forward page="/Training_solutions/LoginSuccess.jsp" />

         <%}

         else

         out.println("Login Failed,Please try Againe");

         %>

        

         <%

     }

}

}catch(Exception e1)

{}

 

%>

 

</form>

</body>

</html>

Open in new window

0
 
LVL 4

Author Comment

by:Ramakanta Sahoo
ID: 24084450
Hi Thanks A lot for the kind help RRZ and Samson.

I tried with below code but it throwing below exception. I dont know may i'm too silly but am not able to get it done correctly.
I'm using jakarta tomact 5.0.2.8 , JDK 1.5.0.16.

Please help.
Code:

--------------------------------------------------

<%@ page language ="java" import="java.sql.*" %>

<%@ page import="java.util.Properties,java.io.IOException" %>
 

<html>

<body bgcolor="pink">

<form name="f1" method="post">

<table>

<tr>

<td>User Name</td><td><input type="text" name="t1" ></td>

</tr>

<td>Password</td>

<td><input type=""password"" name="t2"></td>

<tr>

<td></td>

<td><input type="submit" name="b1" value="LogIn"></td>

</tr>

</table>

<%!

               Properties props = new Properties();

               public void jspInit(){

                       try{

                           props.load(getClass().getResourceAsStream("pass.properties"));

                          }catch(IOException ioe){System.out.print("can't get pass props");}

               }

%>

<%

  String name = request.getParameter("t1");

  String password = request.getParameter("t2");

  if(name != null && password != null){

    name = name.trim();

    password = password.trim();

    if(password.equals(props.getProperty(name))){   

       session.setAttribute("signedIn","true"); 

       session.setAttribute("username",name); 

       RequestDispatcher rd = request.getRequestDispatcher("/Training_solutions/LoginSuccess.jsp");

       rd.forward(request,response);

    }else out.print("Login Failed,Please try Again");

  }else out.print("Login Failed,Please try Again");

%>
 

</form>

</body>

</html>
 
 
 

Exception:

-----------------------------------------------------------------
 

exception
 

org.apache.jasper.JasperException

	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:372)

	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)

	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)

	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
 

root cause
 

java.lang.NullPointerException

	java.io.Reader.<init>(Reader.java:61)

	java.io.InputStreamReader.<init>(InputStreamReader.java:80)

	java.util.Properties.load(Properties.java:266)

	org.apache.jsp.ha_jsp.jspInit(ha_jsp.java:17)

	org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:75)

	org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:144)

	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:307)

	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)

	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)

	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
 
 

--------------------------------------------------------------------------

Open in new window

0
 
LVL 6

Expert Comment

by:SamsonChung
ID: 24087554
type=""password""

single "
0
 
LVL 27

Accepted Solution

by:
rrz earned 50 total points
ID: 24088143
>java.lang.NullPointerException
>      java.io.Reader.<init>(Reader.java:61)

Your code can not find the properties file.  Did you put it into your classpath ?  
>props.load(getClass().getResourceAsStream("pass.properties"));  
you forgot the /
Please try the code below here.  Check your console or logs for the messages.
Can you find the message
"entering jsp Init"    
?
<html>

<body bgcolor="pink">

<form name="f1" method="post">

<table>

<tr>

<td>User Name</td><td><input type="text" name="t1" ></td>

</tr>

<td>Password</td>

<td><input type=""password"" name="t2"></td>

<tr>

<td></td>

<td><input type="submit" name="b1" value="LogIn"></td>

</tr>

</table>

<%!

               Properties props = new Properties();

               public void jspInit(){

                       System.out.print("entering jsp Init");

                       try{

                           props.load(getClass().getResourceAsStream("/pass.properties"));

                          }catch(Exception e){System.out.print("can't get pass props");}

               }

%>

<%

  String name = request.getParameter("t1");

  String password = request.getParameter("t2");

  if(name != null && password != null){

    name = name.trim();

    password = password.trim();

    if(password.equals(props.getProperty(name))){   

       session.setAttribute("signedIn","true"); 

       session.setAttribute("username",name); 

       RequestDispatcher rd = request.getRequestDispatcher("/search.jsp");

       rd.forward(request,response);

    }else out.print("Login Failed,Please try Again");

  }else out.print("Login Failed,Please try Again");

%>

 

</form>

</body>

</html>

Open in new window

0
 
LVL 4

Author Comment

by:Ramakanta Sahoo
ID: 24095652
Hi RRZ i copied exact code you gave me and created a file ha.jsp and pass.properties. restarted tomcat running on Sun JDK 1.5.0.16. when i accessed the url I got below compilation error.


org.apache.jasper.JasperException: Unable to compile class for JSP
 

An error occurred at line: 15 in the jsp file: /ha.jsp

Generated servlet error:

/home/rsahoo/programs/jakarta-tomcat-5.0.28/work/Catalina/localhost/_/org/apache/jsp/ha_jsp.java:11: cannot find symbol

symbol  : class Properties

location: class org.apache.jsp.ha_jsp

               Properties props = new Properties();

               ^
 
 

An error occurred at line: 15 in the jsp file: /ha.jsp

Generated servlet error:

/home/rsahoo/programs/jakarta-tomcat-5.0.28/work/Catalina/localhost/_/org/apache/jsp/ha_jsp.java:11: cannot find symbol

symbol  : class Properties

location: class org.apache.jsp.ha_jsp

               Properties props = new Properties();

                                      ^

2 errors
 
 
 

	org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)

	org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:332)

	org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:412)

	org.apache.jasper.compiler.Compiler.compile(Compiler.java:472)

	org.apache.jasper.compiler.Compiler.compile(Compiler.java:451)

	org.apache.jasper.compiler.Compiler.compile(Compiler.java:439)

	org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:511)

	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:295)

	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)

	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)

	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

Open in new window

0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 27

Expert Comment

by:rrz
ID: 24097675
I am sorry. I forgot this line.  Put it at the top.
<%@ page import="java.util.Properties" %>
0
 
LVL 4

Author Comment

by:Ramakanta Sahoo
ID: 24106325
Cool it started showing up the page.but dear its not logging in just showing logging failed I have set admin=admin in pass.properties file.
You have helped me  a lot so i am awarding you points , but please tell me what i need to do to authenticate properly.
I have attched the code. I'm redirecting it to loginsuccess.jsp file  to just test.
<%@ page import="java.util.Properties" %>

<html>

<body bgcolor="pink">

<form name="f1" method="post">

<table>

<tr>

<td>User Name</td><td><input type="text" name="t1" ></td>

</tr>

<td>Password</td>

<td><input type=""password"" name="t2"></td>

<tr>

<td></td>

<td><input type="submit" name="b1" value="LogIn"></td>

</tr>

</table>

<%!

               Properties props = new Properties();

               public void jspInit(){

                       System.out.print("entering jsp Init");

                       try{

                           props.load(getClass().getResourceAsStream("/pass.properties"));

                          }catch(Exception e){System.out.print("can't get pass props");}

               }

%>

<%

  String name = request.getParameter("t1");

  String password = request.getParameter("t2");

  if(name != null && password != null){

    name = name.trim();

    password = password.trim();

    if(password.equals(props.getProperty(name))){   

       session.setAttribute("signedIn","true"); 

       session.setAttribute("username",name); 

       RequestDispatcher rd = request.getRequestDispatcher("/loginsuccess.jsp");

       rd.forward(request,response);

    }else out.print("Login Failed,Please try Again");

  }else out.print("Login Failed,Please try Again");

%>

 

</form>

</body>

</html>
 
 

loginsuccess.jsp

---------------------------------------------
 

String signedIn = session.getAttribute("signedIn");
 

Login Successful!
 

pass.properties

---------------------
 

admin=admin

Open in new window

0
 
LVL 27

Expert Comment

by:rrz
ID: 24107850
>but dear its not logging in just showing logging failed  
Did you see the message "entering jsp Init"   in the  console or logs   ?

>but please tell me what i need to do to authenticate properly.  
You should try coding    loginsuccess.jsp  something like the following
<%
     String signedIn = session.getAttribute("signedIn");
     String username = session.getAttribute("username");
     if("true".equals(signedIn)){
                                                 out.print("Login Successful!  Welcome " + username);
   
     } else response.sendRedirect("yourLoginPage.jsp");  
%>
 
0
 
LVL 4

Author Comment

by:Ramakanta Sahoo
ID: 24110823
Yes I saw it , it was in catlina.log (entering jsp Init)
0
 
LVL 27

Expert Comment

by:rrz
ID: 24112478
Was the properties file found ? Did you put it into your web app's   WEB-INF/classes  folder  ?  
0
 
LVL 4

Author Comment

by:Ramakanta Sahoo
ID: 24128144
Thanks, Now its working like a charm.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This post first appeared at Oracleinaction  (http://oracleinaction.com/undo-and-redo-in-oracle/)by Anju Garg (Myself). I  will demonstrate that undo for DML’s is stored both in undo tablespace and online redo logs. Then, we will analyze the reaso…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Via a live example, show how to restore a database from backup after a simulated disk failure using RMAN.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now