[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 434
  • Last Modified:

Servlet , jdbc, database, JWS2.0?

I want to write servlet programs that can receive your username & password from a web page then my servlet reply success or fail by scan username & password from my database (Access)

Tell me step by step (detail & clearly) to do it
I use JBuilder 2.0 to write servlet?

Thanks a lot
0
anhvu
Asked:
anhvu
  • 14
  • 10
1 Solution
 
dmaguilloCommented:
Here u have a quite useful web where u can obtaint good documentation about servlets and examples that do the same things that u wanna obtain...

http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.html

Bye... :)


0
 
technomanCommented:
I don't use JBuilder but there is a code that you might be needing.

Be sure to have created a your database first.

login.html

<HTML>
 <BODY>
  <FORM ACTION=LoginServlet METHOD=POST>
    id:<input type=text name=ID>
      pass: <input type=password name=PASS>
      <input type-submit>
  </FORM>
</HTML>

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

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet
 {
 
   public void doPost(HttpServletRequest req, HttpServletResponse res)
   throws ServletException, IOException
   {

     String userid = "";
     String passwd = "";

        Enumeration values = req.getParameterNames();
        while(values.hasMoreElements())
        {
         String name = (String)values.nextElement();
         String value = req.getParameterValues(name)[0];
             if (name.equals("ID"))
              userid = value;         
             else
             if (name.equals("PASS"))
                passwd = value;
        }

      try
        {
          res.setContentType("text/html");
      ServletOutputStream out = res.getOutputStream();

             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection con = DriverManager.getConnection("jdbc:odbc:dsn", null,null);
               // DSN is your data source name in your database
           Statement stmt = con.createStatement();
           ResultSet rs = stmt.executeQuery("SELECT PASSWD FROM LOGIN WHERE UID='"+userid+"'");
              // change this query to suite your need
         if (rs.next())
           {
                String pas = rs.getString("PASSWD");       
                  if (pas.equals(passwd)) Send_Valid(out);
                  else Send_InValid(out);
              }
             else Send_InValid(out);
        catch (Exception e)
         {
          // what ever handler
         }
   }

   public void Send_Valid(ServletOutputStream o)
    {
        out.println("<HTML> ... </HTML>");
        out.close();
      }

   public void Send_InValid(ServletOutputStream o)
    {
        out.println("<HTML> ... Invalid login ... </HTML>");
        out.close();
      }
-----------
Hope this helps

technoman
0
 
technomanCommented:
Oh... here is the explanation,

1. First is that you have to have your database setup first (i assume you already have)

2. Next is to code the webpage as in my sample
3. Code the servlet

    - Create a connection to the DB which is the Class.forname(driver) and        Connection
    - then create a statement for your sql command and get the results
    - check if the result is the same as the input from the webpage to see if the user is valid then send appropriate page to the user.
    - close the connection.

oh... i forgot to close the connection.. you can do it by con.close();

Technoman
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
anhvuAuthor Commented:
Please explan clearly part 3 in your explaination

Where is the creating SQL statement and how to connect them together

You are explaning in correct follow my ideal
0
 
anhvuAuthor Commented:
Please explane clearly (in detail) part 3 in your explanation

your explanation is good (I like it)
0
 
technomanCommented:
anhvu,
   - Create a connection to the DB which is the Class.forname(driver) and            Connection

     The method Class.forname(driver) is to set what driver the database connection will be using. for your case the driver for MS Access is
"sun.jdbc.odbc.JdbcOdbcDriver" which is already available in JDK. Next is to connecte to the DB using the method DriverManager.getConnection(url, user,password); the url parameter is the url of your database for your case use "jdbc:odbc:"+ dsn
where dsn is your data source name (the one you use to create your database in odbc32). for the user and password of the db, just put null since MS Access do not have a user/password for the DB.
   
   - then create a statement for your sql command and get the results

     the method Statement.executeQuery(Query); returns a resultset which is the results produced by the db from the query.    
     the method Statement.executeUpdate(Query); is used to put/remove data from the DB.

     you have to create a statement that will query the database to check if the user trying to login is a valid user.
     I don't know how you have designed your database but here is my example:

     stmt.executeQuery("SELECT PASSWD FROM LOGIN WHERE UID='"+userid+"'");
     
     This code fragment, tells the DB that you want to get information from it. You want to access the table LOGIN and get the PASSWD for the user "userid".
     note: userid was retreived from the from in the webpage so that we can verify if the userid exist in your database.

     if ResultSet contains nothing, that shows that the userid that the user entered is not a valid user for your system.
     else if the resultset contains data, that would be the password of the user, you then check if the password from the database matches the one given to you in the webpage.

Hope this explaine it to you.

Also for more information, download JDK API DOC. There is a discussion on JDBC there.

Have fun with servlets  =)

Technoman
0
 
anhvuAuthor Commented:
Assume my database in c:\My Documents\My Databases\login.mdb (MSAccess) so what is my url for the database (jdbc:odbc:??????)

Thanks again, Bye
0
 
technomanCommented:
anhvu,

ok, your database file is login.mdb but what name have you specified during creation of the file? (the Data Source Name) check odbc32 and see what is your DSN.

now your url should be jdbc:odbc:yourDSN

technoman
0
 
anhvuAuthor Commented:
Hi

Please explan to me in detail the follow source code

Why when I compile this source then it's error that "unreported exception: java.io.IOException; must be caught or declare to be thrown"

Please send me your email so I can send to you the error picture ok?


// I just cut from here ok?

     String userid = "";
     String passwd = "";

  Enumeration values = req.getParameterNames();
  while(values.hasMoreElements())
  {
         String name = (String)values.nextElement();
         String value = req.getParameterValues(name)[0];
if (name.equals("ID"))
        userid = value;      
else
if (name.equals("PASS"))
    passwd = value;
  }

      try
  {
     res.setContentType("text/html");
      ServletOutputStream out = res.getOutputStream();

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection con = DriverManager.getConnection("jdbc:odbc:dsn", null,null);
   // DSN is your data source name in your database
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery("SELECT PASSWD FROM LOGIN WHERE UID='"+userid+"'");
  // change this query to suite your need
         if (rs.next())
     {
    String pas = rs.getString("PASSWD");    
if (pas.equals(passwd)) Send_Valid(out);
else Send_InValid(out);
        }
else Send_InValid(out);
  catch (Exception e)
   {
    // what ever handler
   }
   }

   public void Send_Valid(ServletOutputStream o)
    {
  out.println("<HTML> ... </HTML>");
  out.close();
}

   public void Send_InValid(ServletOutputStream o)
    {
  out.println("<HTML> ... Invalid login ... </HTML>");
  out.close();
}

     String userid = "";
     String passwd = "";

  Enumeration values = req.getParameterNames();
  while(values.hasMoreElements())
  {
         String name = (String)values.nextElement();
         String value = req.getParameterValues(name)[0];
if (name.equals("ID"))
        userid = value;      
else
if (name.equals("PASS"))
    passwd = value;
  }

      try
  {
     res.setContentType("text/html");
      ServletOutputStream out = res.getOutputStream();

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection con = DriverManager.getConnection("jdbc:odbc:dsn", null,null);
   // DSN is your data source name in your database
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery("SELECT PASSWD FROM LOGIN WHERE UID='"+userid+"'");
  // change this query to suite your need
         if (rs.next())
     {
    String pas = rs.getString("PASSWD");    
if (pas.equals(passwd)) Send_Valid(out);
else Send_InValid(out);
        }
else Send_InValid(out);
  catch (Exception e)
   {
    // what ever handler
   }
   }

   public void Send_Valid(ServletOutputStream o)
    {
  out.println("<HTML> ... </HTML>");
  out.close();
}

   public void Send_InValid(ServletOutputStream o)
    {
  out.println("<HTML> ... Invalid login ... </HTML>");
  out.close();
}  
0
 
anhvuAuthor Commented:
Please tell me your email ?
0
 
anhvuAuthor Commented:
Please tell me your email ?
mine is anhvuvnm@yahoo.com
     or anhvu77@hcm.vnn.vn    
0
 
anhvuAuthor Commented:
Please tell me your email ?
mine is anhvuvnm@yahoo.com
     or anhvu77@hcm.vnn.vn    
0
 
anhvuAuthor Commented:
I'm Waiting for you
0
 
technomanCommented:
Anhvu,

Did you get my 2nd email, i hope that has help you in your development. =)

Technoman
0
 
anhvuAuthor Commented:
I'm very sorry that my servlet still haven't run
when I compile it : OK but when I Submit it in the Webform it's appear a white page (there is nothing)
0
 
technomanCommented:
Send me your code and i'll check it out.

Technoman
0
 
anhvuAuthor Commented:

When I run it response "Khong chay" in the httpd (JWS Windows)
I think it be fault at the "try...catch" source code OK?
Please anwser me soon Thanks alot


package sunexamples;

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet
 {

   public void doPost(HttpServletRequest req, HttpServletResponse res)
   throws ServletException, IOException
   {

     String userid = "";
     String passwd = "";

  Enumeration values = req.getParameterNames();
  while(values.hasMoreElements())
  {
         String name = (String)values.nextElement();
         String value = req.getParameterValues(name)[0];
if (name.equals("Username"))
        userid = value;
else
if (name.equals("Password"))
    passwd = value;
  }

  try
  {
     res.setContentType("text/html");
      ServletOutputStream out = res.getOutputStream();

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection con = DriverManager.getConnection("jdbc:odbc:MyDB",null,null);

     Statement stmt = con.createStatement();
     String QuerySt = "SELECT Username FROM Danhsach WHERE Username ='"+userid+"'";
     ResultSet rs = stmt.executeQuery(QuerySt);
      if (rs.next())
      {
          String pas = rs.getString("Password");
       if (pas.equals(passwd)) Send_Valid(res);
       else Send_InValid(res);
      }
      else Send_InValid(res);
  }
  catch (Exception e)
   {
    System.out.println("Khong chay");
   }
   }

  public void Send_Valid(HttpServletResponse res) throws IOException
    {
    PrintStream ps = new PrintStream(res.getOutputStream());
      ps.println("<HTML><HEAD>");
      ps.println("<title>Thong bao1</title>");
      ps.println("</HEAD><BODY>");
      ps.println("<p style= margin-bottom: -10><font color= #FF0000>Wait a moment..., </font></p>");

      ps.close();
}

   public void Send_InValid(HttpServletResponse res) throws IOException
    {
    PrintStream ps = new PrintStream(res.getOutputStream());
      ps.println("<HTML><HEAD>");
      ps.println("<title>Thong bao2</title>");
      ps.println("</HEAD><BODY>");
      ps.println("<p style= margin-bottom: -10><font color= #FF0000>Invalid information, </font></p>");
      ps.println("<p><font color= #FF0000>Check username &amp; password then login again</font></p>");
      ps.close();
     }
}
0
 
technomanCommented:
Anhvu,

try this one:

                   import java.io.*;
                   import java.util.*;
                   import java.sql.*;
                   import javax.servlet.*;
                   import javax.servlet.http.*;

                   public class LoginServlet extends HttpServlet
                    {

                      public void doPost(HttpServletRequest req, HttpServletResponse res)
                      throws ServletException, IOException
                      {

                        String userid = "";
                        String passwd = "";

                     Enumeration values = req.getParameterNames();
                     while(values.hasMoreElements())
                     {
                            String name = (String)values.nextElement();
                            String value = req.getParameterValues(name)[0];
                   if (name.equals("Username"))
                           userid = value;
                   else
                   if (name.equals("Password"))
                       passwd = value;
                     }

                     try
                     {
                        res.setContentType("text/html");
                         ServletOutputStream out = res.getOutputStream();

                           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                            Connection con = DriverManager.getConnection("jdbc:odbc:MyDB",null,null);

                        Statement stmt = con.createStatement();
                        // String QuerySt = "SELECT Username FROM Danhsach WHERE Username ='"+userid+"'";
                  // Your not getting the password out of the database here, this one is better.
                  String QuerySt = "SELECT Password FROM Danhsach WHERE Username ='"+userid+"'";
                        ResultSet rs = stmt.executeQuery(QuerySt);
                         if (rs.next())
                         {
                             String pas = rs.getString("Password");
                          if (pas.equals(passwd)) Send_Valid(out);
                          else Send_InValid(out);
                         }
                         else Send_InValid(out);
                     }
                     catch (Exception e)
                      {
                       System.out.println("Khong chay ---"+e);
                      }
                      }

                     public void Send_Valid(ServletOutputStream ps) throws IOException
                       {
                         ps.println("<HTML><HEAD>");
                         ps.println("<title>Thong bao1</title>");
                         ps.println("</HEAD><BODY>");
                         ps.println("<p style= margin-bottom: -10><font color= #FF0000>Wait a moment...,
                   </font></p>");
                     ps.flush();
                         ps.close();
                   }

                      public void Send_InValid(ServletOutputStream ps) throws IOException
                       {
                         ps.println("<HTML><HEAD>");
                         ps.println("<title>Thong bao2</title>");
                         ps.println("</HEAD><BODY>");
                         ps.println("<p style= margin-bottom: -10><font color= #FF0000>Invalid information,
                   </font></p>");
                         ps.println("<p><font color= #FF0000>Check username &amp; password then login
                   again</font></p>");
                     ps.flush();
                         ps.close();
                        }
                   }
0
 
anhvuAuthor Commented:

Please check it again
It response In_Valid with any username,password

Please send me the comments of methods in HttpServlet Package

See you soon
0
 
anhvuAuthor Commented:
My servlet still reply that is In_Valid
when I give it right username & password

Check it for me and show me where the way to use all of methods in package HttpServlet not Servlet Package Ok?

See you soon
0
 
technomanCommented:
Send me your code and i'll check on it...
hmm. that's odd... i tested that and it worked.

Technoman
0
 
technomanCommented:
oh... send me the java file and the html file.

Technoman
0
 
anhvuAuthor Commented:
OK please wait me, I'll send it to you soon
0
 
anhvuAuthor Commented:
Hello Mr jackson

Now I have to write the servlet that get some fields form my form into the database so what're methods that I need to write it down.

Please show it to me
Can you send me the small source code for this sample

Thank you, Bye and See you
0
 
technomanCommented:
The login code already have a sample of getting data from the user from the HTML Form. For you to place the data in the db, you have to use Statement.executeUpdate(SQL) command where Statement is the statement you have created. and SQL is your SQL command.

Please read tutorial on JDBC it contains all your question.
Also read Servlet tutorial. All you need is there.  
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 14
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now