Solved

Servlet , jdbc, database, JWS2.0?

Posted on 2000-03-23
25
405 Views
Last Modified: 2013-11-24
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
Comment
Question by:anhvu
  • 14
  • 10
25 Comments
 
LVL 1

Expert Comment

by:dmaguillo
ID: 2648489
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
 
LVL 1

Accepted Solution

by:
technoman earned 200 total points
ID: 2648522
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
 
LVL 1

Expert Comment

by:technoman
ID: 2648532
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
 

Author Comment

by:anhvu
ID: 2651805
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
 

Author Comment

by:anhvu
ID: 2651812
Please explane clearly (in detail) part 3 in your explanation

your explanation is good (I like it)
0
 
LVL 1

Expert Comment

by:technoman
ID: 2651906
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
 

Author Comment

by:anhvu
ID: 2655290
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
 
LVL 1

Expert Comment

by:technoman
ID: 2655638
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
 

Author Comment

by:anhvu
ID: 2655741
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
 

Author Comment

by:anhvu
ID: 2655746
Please tell me your email ?
0
 

Author Comment

by:anhvu
ID: 2655748
Please tell me your email ?
mine is anhvuvnm@yahoo.com
     or anhvu77@hcm.vnn.vn    
0
 

Author Comment

by:anhvu
ID: 2655752
Please tell me your email ?
mine is anhvuvnm@yahoo.com
     or anhvu77@hcm.vnn.vn    
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:anhvu
ID: 2655956
I'm Waiting for you
0
 
LVL 1

Expert Comment

by:technoman
ID: 2660520
Anhvu,

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

Technoman
0
 

Author Comment

by:anhvu
ID: 2662372
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
 
LVL 1

Expert Comment

by:technoman
ID: 2662884
Send me your code and i'll check it out.

Technoman
0
 

Author Comment

by:anhvu
ID: 2663325

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
 
LVL 1

Expert Comment

by:technoman
ID: 2664091
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
 

Author Comment

by:anhvu
ID: 2671237

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
 

Author Comment

by:anhvu
ID: 2673432
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
 
LVL 1

Expert Comment

by:technoman
ID: 2675848
Send me your code and i'll check on it...
hmm. that's odd... i tested that and it worked.

Technoman
0
 
LVL 1

Expert Comment

by:technoman
ID: 2675851
oh... send me the java file and the html file.

Technoman
0
 

Author Comment

by:anhvu
ID: 2680637
OK please wait me, I'll send it to you soon
0
 

Author Comment

by:anhvu
ID: 2692851
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
 
LVL 1

Expert Comment

by:technoman
ID: 2695236
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

760 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

24 Experts available now in Live!

Get 1:1 Help Now