?
Solved

Servlet , jdbc, database, JWS2.0?

Posted on 2000-03-23
25
Medium Priority
?
426 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 600 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
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

 

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
 

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

Certified OpenStack Administrator Course

We just refreshed our COA course based on the Newton exam.  With 14 labs, this course goes over the different OpenStack services that are part of the certification: Dashboard, Identity Service, Image Service, Networking, Compute, Object Storage, Block Storage, and Orchestration.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
A solution for Fortify Path Manipulation.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month7 days, 21 hours left to enroll

765 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