Solved

passing values from servlet to a nother

Posted on 2002-04-03
21
243 Views
Last Modified: 2013-11-24
i have an html code that send the id and password to servlet code to check user id and password if valid or not.

suppose the password is ok , i want to send the id and password from this servlet to another servlet to display
employees records from access 2000 which i connected to using jdbc:odbc  how to do so.
 
explaining by given a code is better.

thanks.
0
Comment
Question by:star5
  • 10
  • 6
  • 4
  • +1
21 Comments
 
LVL 19

Expert Comment

by:cheekycj
ID: 6915920
You can do a forward to the other servlet after adding the userID and password to request.

request.setAttribute("userid", useridvar);
request.setAttribute("password", passwordvar);
request.getRequestDispatcher("relative path to next servlet").forward(request, response);


Now in the next servlet you can get the two vars by
String userID = (String) request.getAttribute("userid");
String password = (String) request.getAttribute("password");

HTH,
CJ
0
 
LVL 3

Expert Comment

by:msterjev
ID: 6915954
Let suppose that we have two servlets: logger and presenter.

Into the logger servlet after succesfull autorization write this:

HttpSession session=req.getSession(true);
session.putValue("username",username);
session.putValue("password",password);
res.sendRecirect("/servlet/presenter");

At the presenter servlet write the oposite:

String username;
String password;

HttpSession session=req.getSession(true);
username=(String) session.getValue("username");
password=(String) session.getValue("password");

if((username!=null) && (password!=null)
{
     //  ...............................
     // Do the database logic here: SELECT * FROM WHERE ....
}

P.S.

You should increase the points for coding examples!
0
 
LVL 19

Expert Comment

by:cheekycj
ID: 6915966
msterjev: you should not propose answers when the solution you gave is not the 110% absolute way of doing it.  There are other options.. which means you should not lock the question down from other expert participation.

please refer to the bottom of this page about comments vs answers.

Also: for a session solution, the web.xml must be updated too.  Why use the overhead of storing stuff in session and worrying about cleaning it up.. if you can just add attributes to the request and do a forward?
0
 
LVL 3

Expert Comment

by:msterjev
ID: 6917272
He should use the Session because I don't think his site is consisted with only two servlets with dispatching from one to the other. That is not a way for building sites. The user with such kind of loggin and database reports would travel across site servlets. He must present his credentals everywhere he goes, so it must use session variables. Another thing! In the session he can store objects (Collections,Hashmaps==shooping carts). On the contrary, req.setAttribute(...) is a plain HTTP. And at the end, i must advise star5(I gave him the previous solution with the loggin)) the session object must be active all the time, so it se alreday used. Why it must be alredy present? Because when the user is authenticated, you must put some variable into the session to indicate his is alredy logged on. ("Session.putValue("logged","true")). This way ,you can't directly access second servlet without authenticating done by the first. Or, authenticated user navigated to the first servlet(authenticator-logger) can be automatically redirected to the other page.
P.S.
If you don't want to use Session you need to implement the old CGI form hidden fields.
0
 

Author Comment

by:star5
ID: 6917380
i tried what u are saying but small errors exist that i did not find it .
in  code 1 :

it shows an error pointing to if (username !=null)
the other error is variable rsl

the second code shows error pointing to userid  :
session.putValue("username",userid);
                            ^
==================================================
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class TrainingServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                                     throws ServletException, IOException {
 
         Connection con = null;          
         
         res.setContentType("text/html");
         PrintWriter out=res.getWriter();
       
       try {
       
            String strSQL ;
            ResultSet rsl;
            Statement stmt;
           
             String username;
             

           HttpSession session=req.getSession(true);
           username=(String) session.getValue("username");
           
                  
            Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:db1");
            stmt = con.createStatement();
            strSQL = "select * from Training " +
                 "where EmpID like '" + username + "'";
            rsl = stmt.executeQuery(strSQL);
                 
           rsl.close();
               stmt.close();  
             

       } catch (Exception e)
         {
           e.printStackTrace();
       }
         finally
         {
            if (con != null)
               {
                 try
                     {
                      con.close();
                 } catch (SQLException se) {
                      se.printStackTrace(System.err);
                 }
            }
       }
       


if(username != null)
             {
                 out.println("<TABLE CELLSPACING=\"0\" CELLPADDING=\"6\" BORDER=\"1\">");        

                 out.println("<TR><TD>Emp NO.</TD><TD>Course Name</TD><TD>Start Date</TD><TD>End

Date</TD><TD>Place</TD></TR>");
                 while(rsl.next())                                                      
                  {                                                                      
                     out.println("<TR>");                                                        
                     out.println("<TD>" + rsl.getString("EmpNO") + "</TD>");              
                     out.println("<TD>" + rsl.getString("Course_name") + "</TD>");
                 out.println("<TD>" + rsl.getString("Start_Date") + "</TD>");
                     out.println("<TD>" + rsl.getString("End_Date") + "</TD>");
                     out.println("<TD>" + rsl.getString("Place") + "</TD>");
                     out.println ("</TR>");                                              
                  }                                                
            }
        else
            {
      res.sendRedirect("http://www.omania.net");
             }
  }    

}
================================


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

public class CheckLogin2 extends HttpServlet {
  public void doPost(HttpServletRequest req, HttpServletResponse res)
                                     throws ServletException, IOException {
 
       Connection con = null;          
         boolean logged = false;
         res.setContentType("text/html");
         PrintWriter out=res.getWriter();
       // check userID and password
       try {
       
            String strSQL, userid, password;
            ResultSet rs;
            Statement stmt;
           
            // get parameters passed from html
            userid = req.getParameter("username");
            password = req.getParameter("password");              
             
                  
            Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:db1");
            stmt = con.createStatement();
            strSQL = "select * from LoginTable " +
                 "where EmpID like '" + username + "' and " +
                 "Password like '" + password + "'";
            rs = stmt.executeQuery(strSQL);
                 
            if (rs.next())
                  {
                  logged = true;
                  }         
             else
                   {  
                          logged = false;
                  }      
             rs.close();
               stmt.close();

       } catch (Exception e)
         {
           e.printStackTrace();
       }
         finally
         {
            if (con != null)
               {
                 try
                     {
                      con.close();
                 } catch (SQLException se) {
                      se.printStackTrace(System.err);
                 }
            }
       }
        if(logged)
             {
           HttpSession session=req.getSession(true);
           session.putValue("username",userid);
               res.sendRedirect("http://student/servlet/TrainingServlet");

            }
        else
            {
                  res.sendRedirect("http://www.omania.net");
             }
  }    

}

========================================
0
 
LVL 3

Expert Comment

by:msterjev
ID: 6917428
The problem is variable declaration. You should declare variables outside the try-catch. Also you try to scroll closed ResultSet. (rsl).

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

public class TrainingServlet extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res)
                                    throws ServletException, IOException {
 
         String strSQL;
         ResultSet rsl=null;
         Statement stmt=null;
         String username=null;
             String outStr=null;
             Connection con = null;          
         res.setContentType("text/html");
         PrintWriter out=res.getWriter();
            try {
          HttpSession session=req.getSession(true);
          username=(String) session.getValue("username");
              if(username!=null)
              {
                  Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
                  con = DriverManager.getConnection("jdbc:odbc:db1");
                  stmt = con.createStatement();
                  strSQL = "select * from Training where EmpID like '" + username + "'";
                  rsl = stmt.executeQuery(strSQL);
            outStr="<HTML><BODY><TABLE CELLSPACING=\"0\" CELLPADDING=\"6\" BORDER=\"1\">";        
            outStr+="<TR><TD>Emp NO.</TD><TD>Course Name</TD><TD>Start Date</TD><TD>End Date</TD><TD>Place</TD></TR>";
                  while(rsl.next())                                                      
            {                                                                      
                outStr+="<TR>";                                                        
                outStr+="<TD>" + rsl.getString("EmpNO") + "</TD>";              
                outStr+="<TD>" + rsl.getString("Course_name") + "</TD>";
                outStr+="<TD>" + rsl.getString("Start_Date") + "</TD>";
                outStr+="<TD>" + rsl.getString("End_Date") + "</TD>";
                outStr+=("<TD>" + rsl.getString("Place") + "</TD>");
                outStr+="</TR>";                                              
            }
                  outStr+="</TABLE></BODY></HTML>";
                  rsl.close();
                  stmt.close();
          }
      } catch (Exception e)
        {
          e.printStackTrace();
      }
        finally
        {
           if (con != null)
              {
                try
                    {
                     con.close();
                } catch (SQLException se) {
                     se.printStackTrace(System.err);
                }
           }
      }
       


            if(username != null)
                  out.println(outStr);                                        
       else
     res.sendRedirect("http://www.omania.net");
 }    

}

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

public class CheckLogin2 extends HttpServlet {
 public void doPost(HttpServletRequest req, HttpServletResponse res)
                                    throws ServletException, IOException {
 
      Connection con = null;          
      boolean logged = false;
        ResultSet rs=null;
      Statement stmt=null;
        String strSQL;
        String userid=null;
        String password=null;
      res.setContentType("text/html");
      PrintWriter out=res.getWriter();
      // check userID and password
      try {
         
           // get parameters passed from html
           userid = req.getParameter("username");
           password = req.getParameter("password");              
           Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
           con = DriverManager.getConnection("jdbc:odbc:db1");
           stmt = con.createStatement();
           strSQL = "select * from LoginTable " +
                "where EmpID like '" + userid + "' and " +
                "Password like '" + password + "'";
           rs = stmt.executeQuery(strSQL);
                 
           if (rs.next())
               {
                 logged = true;
               }        
            else
                {  
                      logged = false;
               }    
            rs.close();
              stmt.close();

      } catch (Exception e)
        {
          e.printStackTrace();
      }
        finally
        {
           if (con != null)
              {
                try
                    {
                     con.close();
                } catch (SQLException se) {
                     se.printStackTrace(System.err);
                }
           }
      }
       if(logged)
       {
          HttpSession session=req.getSession(true);
          session.putValue("username",userid);
          res.sendRedirect("http://student/servlet/TrainingServlet");

       }
       else
       {
           res.sendRedirect("http://www.omania.net");
       }
 }    

}


P.S.

Such questions are worth more points!
0
 
LVL 19

Expert Comment

by:cheekycj
ID: 6917917
Also putValue() is deprecated in Servlet 2.3 spec.  You are supposed to use session.setAttribute().  Which servlet engine are you using?

msterjev:  The reason why I suggested request.setAttribute is b/c the question stated to pass userid and password to the next servlet not indicate that a user is logged in and track it.  I assumed that something specific was needed in the second servlet.. not just tracking whether user is logged in or not.. if that is the case why even set userid and password in session.. just set a flag that says loggedin=true and store userid for DB lookups. Right?

CJ

0
 
LVL 19

Expert Comment

by:cheekycj
ID: 6917922
On a side note: Experts-Exchange is not about points.. its about helping out regardless of the points.  the points just make it fun :-)
0
 

Author Comment

by:star5
ID: 6918403
msterjev i tried it and it compiles with no error,
but it prints the word "null" .
what is the problem?????

on this case the training srvlet prints the tables immediately , i don't want to print from training servlet
but i want to call it by clicking on a link and then it prints a fter calling it from the link .

the other thing can i call many servlets from one servlet to do similar things.
0
 
LVL 3

Expert Comment

by:msterjev
ID: 6918585
Where it prints null?
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:star5
ID: 6918719
it prints the word null in a white page!!!
i don't know where this word come from ?
0
 

Author Comment

by:star5
ID: 6918741
it prints the word null in a white page!!!
i don't know where this word come from ?
0
 

Author Comment

by:star5
ID: 6920501
still not working
0
 

Author Comment

by:star5
ID: 6920503
still not working
0
 

Author Comment

by:star5
ID: 6920504
still not working
0
 

Author Comment

by:star5
ID: 6920506
still not working
0
 
LVL 19

Expert Comment

by:cheekycj
ID: 6920725
star5: What servlet engine are you using.. tomcat/resin/orion.. which one.. and what version of it?
0
 

Author Comment

by:star5
ID: 6922469
iplanet web server 6.0
0
 

Author Comment

by:star5
ID: 6923072
it works msterjev but the problem i don't want it to display the values immediately , i want them to be displayed after clicking on a link from a web page .

the idea :
getting user id ,password ,using a servlet it checks its validity if ok send user id to a nother servlets but don't display the employee table it just process there, it displays the employee table after clicking on a link from a web page that goes to that servlet.  
0
 
LVL 19

Accepted Solution

by:
cheekycj earned 30 total points
ID: 6925371
     if(logged)
      {
         HttpSession session=req.getSession(true);
         session.putValue("username",userid);
         res.sendRedirect("http://student/servlet/TrainingServlet");

      }
      else
      {
          res.sendRedirect("http://www.omania.net");
      }

This is the part that redirects.. immediately.. maybe you want it to send the user to a page where they will have to click on a link?
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6956457
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
 
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.20284495.html
http://www.experts-exchange.com/questions/Q.20284978.html
http://www.experts-exchange.com/questions/Q.20286874.html
http://www.experts-exchange.com/questions/Q.20288082.html
http://www.experts-exchange.com/questions/Q.20287488.html
http://www.experts-exchange.com/questions/Q.20288869.html


To view your locked questions, please click the following link(s) and evaluate the proposed answer.
http://www.experts-exchange.com/questions/Q.20285624.html
http://www.experts-exchange.com/questions/Q.20286675.html

*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations if this item remains inactive another seven (7) days.  If you are interested in the cleanup effort, please click this link http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643
POINTS FOR EXPERTS awaiting comments are listed here -> http://www.experts-exchange.com/commspt/Q.20277028.html
 
Moderators will finalize this question if in @7 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thank you everyone.
 
Moondancer
Moderator @ Experts Exchange
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

705 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

20 Experts available now in Live!

Get 1:1 Help Now