Calling public class method  from the servlet dopost() implementation

Hi!
My application is a simple application where i wrote a JSP page to enter the USERNAME and PASSWORD. And this JSP will call a HttpServlet
with in which i am calling another Java class ValidateUser which will check aginst the Oracle Database table whether that Username and password combination exists and returns the user's name.
But when i am trying to call that method is throwing me an error. here is the typical code i wrote.
servlet
package isispack;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class Login extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res)
               throws ServletException,IOException{
String userId = req.getParameter("user_id");
String password = req.getParameter("user_pass");
// if uName is null .. user is not authorized.
String uName = Validate(userId, password);
and
Validate class
package isispack;
import java.sql.*;
import java.util.*;
import java.lang.*;
public class ValidateUser
public String ValidateUser(String inputUserid, String inputPwd) throws
SQLException{
     String returnString = null;
     String dbUserid = "isis"; // our Database user id
     String dbPassword = "isisos" ; // our Database password
     Connection con = DriverManager.getConnection("jdbc:odbc:JdbcOdbcDriver","isis","osiris");
     Statement stmt = con.createStatement();
     String sql= "select user_id from isis_table where user_id = '" inputUserid + "' and user_pass= '" + inputPwd +"' ;" ;
     ResultSet rs = stmt.executeQuery(sql);
     if (rs.next())
     returnString = rs.getString("user_id");
     stmt.close();
     con.close();
     return returnString ;
The ERROR
Error(18,18): method ValidateUser(java.lang.String, java.lang.String) not found in class isispack.Login
One more thing i forgot to tell you. I am trying to run this application on JDeveloper. Please helpme out if you can . Thank you.
-Sreekanth

OK! I made it static method
and tried to call the method as follows
String uName = ValidateUser.ValidateUser(userId, password);
even if i create the instence and
ValidateUser Validate;
then call
String uName= Validate.ValidateUser(userId,password)
In either case is giving me the following error.Tarun, am new to Java programming, please help me out. And can you please tell me where can i find things in consise to brush up my fundamentals?.
Error(18,43): unreported exception: java.sql.SQLException; must be caught or declared to be thrown

Similar Messages

  • Call enhancement class method from Bus. workflow task

    Hi all,
    I recently enhanced a global class from SAP (add a new method). Now I would like to call it from a workflow task (ABAP Class object used in the task). So it seems that only "native" methods from the class itself can be selected for the object method of the task.
    Same issue if I try to call it via secondary methods options...
    Last idea I have before the repair is: retrieve the instance saved into the WF container via a custom class interfacing IF_IFS_SWF_CONTAINER_EXIT (program exit) and call the enhanced method from the method proposed in this interface.
    Maybe someone had the same issue? Anyone could help or propose solution?
    Many thanks in advance for your help,
    KR,
    Olivier

    I think it might qualify for an OSS message.
    There was simmilar note for BADIs which was corrected: https://service.sap.com/sap/support/notes/1156392
    CL_SWF_UTL_DEF_SERVICES which is used in PFTC to determine callable methods doesn't include enhancements when calling  function SEO_CLASS_TYPEINFO_GET (parameter WITH_ENHANCEMENTS is default FALSE)

  • Calling the super class method from the subclass

    Hi all,
    I have a question about inheritence and redefinition of methods. Is it possible to call the superclass implementation of a method which is redefined in the subclass in another method of the subclass?There are possbilities like creation of an explicit super class instance or delegating the super class method implementation to another method which is also protected etc. What i mean is, is there a direct way of calling it?We have ,me,   as the reference for the instance we have(which is the subclass instance in this case), is there also a way of pointing the superclass implementation(with super we can reference in the subclass redefinition, my question is if we have such a parameter in other methods of the subclass too)
    Thanks in advance
    Sukru

    Hi,
    The super reference can only be used in redefined methods to call superclass implementation . So probably what you can do is use upcasting and access the required superclass implementation. I can think of only this way...;-)
    Ex data lr_super type ref to cl_superclass
    lr_super = lr_subclass.
    lr_super->method().
    ~Piyush Patil

  • Accessing a java class method from the jsp page.

    Hi im a beginner with jsp and im trying to find a way to access a method of my java class file in jsp page. After searching through the forums i tried to use the usebean tag. Im using apache to host the jsp file.Below is an excerpt of my code and the error message i got. What am i doing wrong? anyone know?
    <%@ page language="java" %>
    <jsp:useBean id="movies" class="movie.Movie" />
    <jsp:setProperty name="movies" property="*"/>
    <%
    movies.getStart("file:///C:/Video/Applications2/sun.mpg");
    response.setContentType("text/xml");
    %>
    exception
    org.apache.jasper.JasperException: Exception in JSP: /View.jsp:7
    4: <jsp:setProperty name="movies" property="*"/>
    5: <%
    6:
    7: movies.getStart("file:///C:/Video/Applications2/sun.mpg");
    8: response.setContentType("text/xml");
    9: %>
    Stacktrace:
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:504)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    javax.servlet.ServletException: javax/media/ControllerListener

    Hi thanks for responding. Ok i did look through and it was opening some gui. I still need the program to do server side processes so cant use an applet.but i dont need the gui so i revised it and removed the gui. also im using a servlet to call the class now yet i still have the same error. Any ideas?
    Below is the vid2jpg code minus the gui.
    import java.io.*;
    import java.awt.*;
    import javax.media.*;
    import javax.media.control.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class vid2jpg implements ControllerListener
         Processor p;
         Object waitObj = new Object();
         boolean stateOK = true;
         DataSourceHandler handler;
    int imgWidth;int imgHeight;
         Image outputImage;
         String sep = System.getProperty("file.separator");
         int[] outvid;
         int startFr = 1;int endFr = 1000;int countFr = 0;
         boolean sunjava=true;
         * Static main method
         public static void main(String[] args)
              if(args.length == 0)
                   System.out.println("No media address.");
                   new vid2jpg("file:///C:/Video/applications2/sun.mpg");     // or alternative "vfw://0" if webcam
              else
                   String path = args[0].trim();
                   System.out.println(path);
                   new vid2jpg(path);
         * Constructor
         public vid2jpg(String path)
              MediaLocator ml;String args = path;
              if((ml = new MediaLocator(args)) == null)
                   System.out.println("Cannot build media locator from: " + args);
              if(!open(ml))
                   System.out.println("Failed to open media source");
         * Given a MediaLocator, create a processor and start
         private boolean open(MediaLocator ml)
              System.out.println("Create processor for: " + ml);
              try
                   p = Manager.createProcessor(ml);
              catch (Exception e)
                   System.out.println("Failed to create a processor from the given media source: " + e);
                   return false;
              p.addControllerListener(this);
              // Put the Processor into configured state.
              p.configure();
              if(!waitForState(p.Configured))
                   System.out.println("Failed to configure the processor.");
                   return false;
              // Get the raw output from the Processor.
              p.setContentDescriptor(new ContentDescriptor(ContentDescriptor.RAW));
              TrackControl tc[] = p.getTrackControls();
              if(tc == null)
                   System.out.println("Failed to obtain track controls from the processor.");
                   return false;
              TrackControl videoTrack = null;
              for(int i = 0; i < tc.length; i++)
                   if(tc.getFormat() instanceof VideoFormat)
                        tc[i].setFormat(new RGBFormat(null, -1, Format.byteArray, -1.0F, 24, 3, 2, 1));
                        videoTrack = tc[i];
                   else
                   tc[i].setEnabled(false);
              if(videoTrack == null)
                   System.out.println("The input media does not contain a video track.");
                   return false;
              System.out.println("Video format: " + videoTrack.getFormat());
              p.realize();
              if(!waitForState(p.Realized))
                   System.out.println("Failed to realize the processor.");
                   return false;
              // Get the output DataSource from the processor and set it to the DataSourceHandler.
              DataSource ods = p.getDataOutput();
              handler = new DataSourceHandler();
              try
                   handler.setSource(ods);     // also determines image size
              catch(IncompatibleSourceException e)
                   System.out.println("Cannot handle the output DataSource from the processor: " + ods);
                   return false;
         //     setLayout(new FlowLayout(FlowLayout.LEFT));
    //          currPanel = new imgPanel(new Dimension(imgWidth,imgHeight));
         //     add(currPanel);
         //     pack();
              //setLocation(100,100);
         //     setVisible(true);
              handler.start();
              // Prefetch the processor.
              p.prefetch();
              if(!waitForState(p.Prefetched))
                   System.out.println("Failed to prefetch the processor.");
                   return false;
              // Start the processor
              //p.setStopTime(new Time(20.00));
              p.start();
              return true;
         * Sets image size
         private void imageProfile(VideoFormat vidFormat)
              System.out.println("Push Format "+vidFormat);
              Dimension d = (vidFormat).getSize();
              System.out.println("Video frame size: "+ d.width+"x"+d.height);
              imgWidth=d.width;
              imgHeight=d.height;
         * Called on each new frame buffer
         int nextframetime = 0;
    private void useFrameData(Buffer inBuffer)
    try
    if(inBuffer.getData()!=null) // vfw://0 can deliver nulls
    if(sunjava) // and with import javax.imageio.*;
    int frametimesecs = (int)(inBuffer.getTimeStamp()/1000000000);
    if(frametimesecs%10 == 0 && frametimesecs==nextframetime)
    nextframetime+=10;
    BufferedImage bi = new BufferedImage(outputImage.getWidth(null), outputImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    ImageIO.write(bi, "png", new File("images"+sep+"image_"+(inBuffer.getTimeStamp()/1000000000)+".png"));
    catch(Exception e){}
         * Tidy on finish
         public void tidyClose()
              handler.close();
              p.close();
         * Block until the processor has transitioned to the given state
         private boolean waitForState(int state)
              synchronized(waitObj)
                   try
                        while(p.getState() < state && stateOK)
                        waitObj.wait();
                   catch (Exception e)
              return stateOK;
         * Controller Listener.
         public void controllerUpdate(ControllerEvent evt)
              if(evt instanceof ConfigureCompleteEvent ||     evt instanceof RealizeCompleteEvent || evt instanceof PrefetchCompleteEvent)
                   synchronized(waitObj)
                        stateOK = true;
                        waitObj.notifyAll();
              else
              if(evt instanceof ResourceUnavailableEvent)
                   synchronized(waitObj)
                        stateOK = false;
                        waitObj.notifyAll();
              else
              if(evt instanceof EndOfMediaEvent || evt instanceof StopAtTimeEvent)
                   tidyClose();
         * Inner classes
         * A DataSourceHandler class to read from a DataSource and displays
         * information of each frame of data received.
         class DataSourceHandler implements BufferTransferHandler
              DataSource source;
              PullBufferStream pullStrms[] = null;
              PushBufferStream pushStrms[] = null;
              Buffer readBuffer;
              * Sets the media source this MediaHandler should use to obtain content.
              private void setSource(DataSource source) throws IncompatibleSourceException
                   // Different types of DataSources need to handled differently.
                   if(source instanceof PushBufferDataSource)
                        pushStrms = ((PushBufferDataSource) source).getStreams();
                        // Set the transfer handler to receive pushed data from the push DataSource.
                        pushStrms[0].setTransferHandler(this);
                        // Set image size
                        imageProfile((VideoFormat)pushStrms[0].getFormat());
                   else
                   if(source instanceof PullBufferDataSource)
                        System.out.println("PullBufferDataSource!");
                        // This handler only handles push buffer datasource.
                        throw new IncompatibleSourceException();
                   this.source = source;
                   readBuffer = new Buffer();
              * This will get called when there's data pushed from the PushBufferDataSource.
              public void transferData(PushBufferStream stream)
                   try
                        stream.read(readBuffer);
                   catch(Exception e)
                        System.out.println(e);
                        return;
                   // Just in case contents of data object changed by some other thread
                   Buffer inBuffer = (Buffer)(readBuffer.clone());
                   // Check for end of stream
                   if(readBuffer.isEOM())
                        System.out.println("End of stream");
                        return;
                   // Do useful stuff or wait
                   useFrameData(inBuffer);
              public void start()
                   try{source.start();}catch(Exception e){System.out.println(e);}
              public void stop()
                   try{source.stop();}catch(Exception e){System.out.println(e);}
              public void close(){stop();}
              public Object[] getControls()
                   return new Object[0];
              public Object getControl(String name)
                   return null;
    below is the servlet code.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class ShowMovie extends HttpServlet {
    String rootURL="http://127.0.0.1:8080/Video/";
    public void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
         //String movie=request.getParameter("movie");
         String movie ="son";
         getStart(movie);
              response.sendRedirect(rootURL+"View.jsp");
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
         public void getStart(String url){
              new vid2jpg(url);
    this is the error from the server. Im using tomkat 5
    exception
    javax.servlet.ServletException: Servlet execution threw an exception
    root cause
    java.lang.NoClassDefFoundError: javax/media/ControllerListener
         java.lang.ClassLoader.defineClass1(Native Method)
         java.lang.ClassLoader.defineClass(Unknown Source)
         java.security.SecureClassLoader.defineClass(Unknown Source)
         org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1812)
         org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:866)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1319)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1198)
         java.lang.ClassLoader.loadClassInternal(Unknown Source)
         ShowMovie.getStart(ShowMovie.java:31)
         ShowMovie.processRequest(ShowMovie.java:14)
         ShowMovie.doGet(ShowMovie.java:22)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.17 logs.

  • Calling Stateful & Statless Methods from the same Entity Bean[EJB2.0]?

    Dear All,
    We using EJB2.0........
    Regarding segregation of stateless and stateful methods..These methods are defined in Session bean.Now my question is
    Is it a good practice to call Stateful and Stateless business methods from same single entity bean("EntityBean") defined at program level by extending MainBean..
    The architecture is like
    public class EntityBean extends MainBean
    Public Methodxyz
    stfobj.MakeConn();
    stlobj.getXyz();
    stfobj.CloseConn();
    Public Class MainBean{lookup("stl");lookup(stf) ;stl_obj=home.create;stf_obj=home.create()............}
    ejb-jar.xml
    { <session>
              <description>Entity Bean Employee Example</description>
              <ejb-name>stl</ejb-name>
              <local-home>com.packg.stlHome</local-home>
              <local>com.packg.stl</local>
              <ejb-class>com.packg.stlBean</ejb-class>
              <session-type>Stateless</session-type>
              <transaction-type>Container</transaction-type>
         </session>
         <session>
              <description>Entity Bean Employee Example for stateful</description>
              <ejb-name>stf</ejb-name>
              <local-home>com.packg.stfHome</local-home>
              <local>com.packg.ejbeans.stf</local>
              <ejb-class>com.packg.stfBean</ejb-class>
              <session-type>Stateful</session-type>
              <transaction-type>Container</transaction-type>
         </session>
         <session>
              <description>Session bean for System Parameters</description>
              <ejb-name>SysParam</ejb-name>
              <local-home>com.packg.Home</local-home>
              <local>com.packg.Param</local>
              <ejb-class>com.packg.Bean</ejb-class>
              <session-type>Stateless</session-type>
              <transaction-type>Bean</transaction-type>
              <ejb-local-ref>
              <ejb-ref-name>stl</ejb-ref-name>
              <ejb-ref-type>Session</ejb-ref-type>
              <local-home>com.packg.stlHome</local-home>
              <local>com.packg.ejbeans.stl</local>
              <ejb-link>stl</ejb-link>
         </ejb-local-ref>
              <ejb-local-ref>
              <ejb-ref-name>stf</ejb-ref-name>
              <ejb-ref-type>Session</ejb-ref-type>
              <local-home>com.packg.stfHome</local-home>
              <local>com.packg.stf</local>
              <ejb-link>stf</ejb-link>
         </ejb-local-ref>
         </session>
    Thanks !!
    Edited by: user9052593 on Jun 18, 2012 2:20 AM
    Edited by: user9052593 on Jun 18, 2012 2:25 AM

    All Business logic resides in session beans[Stateful or Stateless]..For stateful beans we are opening connections in entity bean ,calling business methods and closing connection in entity bean itself..Problem is
    I am doing lookup for stateful and stateless both since both objects are called by extending MainBean in same entity bean else will give null pointer exception..
    So whenever i call a Stateful or Stateless method from entity bean Which ultimately extends/calling MainBean and thereby calling home.create methods of stateful and stateless both..creating objects..Is this way fine or it will affect the performance?
    Do i need to segregate the Calls/invokation to Stateful / Stateless methods at entity bean level too..
    For ex:- Whenever i call Methodxyz() method ..at the same time it create 2 objects as its extending MainBean...i want to extend/create 1 object either of stateful or stateless one for stateful and stateless methods call respectively..
    See the code in entity bean is like
    public class EntityBean extends MainBean
    Public Methodxyz
    stfobj.MakeConn(); call to stateful method defined in stateful bean
    stlobj.getXyz();// call to stateless method defined in stateless bean
    stfobj.CloseConn(); call to stateful method defined in stateful bean
    ------------------------------------------------------------

  • How to call a class method from a jsp page?

    Hi all,
    i would like to create a basic jsp page in jdev 1013 that contains a button and a text field. When clicking the button, i would like to call a method that returns a string into the text field.
    The class could be something like this:
    public class Class1 {
    public String getResult() {
    return "Hello World";
    How do i go about this?
    Thanks

    Here is a sample:
    HTML><HEAD><TITLE>Test JDBC for Oracle Support</TITLE></HEAD><BODY>
    <%@ page import="java.sql.*, oracle.jdbc.*, oracle.jdbc.pool.OracleDataSource" %>
    <% if (request.getParameter("user")==null) { %>
    <FORM method="post" action="testjdbc.jsp">
    <H1>Enter connection Parameters</H1>
    <H5>Please enter host name:</H5><INPUT TYPE="text" name="hostname" value="localhost" />
    <H5>Please enter port number:</H5><INPUT TYPE="text" name="port" value="1521" />
    <H5>Service nanme:</H5><INPUT TYPE="text" name="service" value="XE" />
    <H5>Please enter username: </H5><INPUT TYPE="text" name="user" />
    <H5>Please enter password</H5><INPUT TYPE="password" name="password" />
    <INPUT TYPE="submit" />
    </FORM>
    <% } else { %>
    <%
    String hostName = request.getParameter("hostname");
    String portNumber = request.getParameter("port");
    String service = request.getParameter("service");
    String user = request.getParameter("user");
    String password = request.getParameter("password");
    String url = "jdbc:oracle:thin:" + user + "/" + password + "@//" + hostName + ":" + portNumber + "/" + service;
    try {
    OracleDataSource ods = new OracleDataSource();
    ods.setURL(url);
    Connection conn = ods.getConnection();
    // Create Oracle DatabaseMetaData object
    DatabaseMetaData meta = conn.getMetaData();
    // gets driver information
    out.println("<TABLE>");
    out.println("<TR><TD>");
    out.println("<B>JDBC Driver version</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getDriverVersion());
    out.println("</TD>");
    out.println("</TR>");
    out.println("<TR><TD>");
    out.println("<B>JDBC Driver Name</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getDriverName());
    out.println("</TD>");
    out.println("</TR>");
    out.println("<TR><TD>");
    out.println("<B>JDBC URL</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getURL());
    out.println("</TD>");
    out.println("<TABLE>");
    conn.close();
    } catch (Exception e) {e.printStackTrace(); }
    %>
    <%-- end else if --%>
    <% } %>
    </BODY>
    </HTML>

  • Can we call super class method from Overwrite method using SUPER keyword

    Hi All,
    For one of our requirement , I need to overwrite "Process Event" method of a feeder class  ,where process event is present is protected method. so when we are making a call , then its saying
    "Method  "process event"  is unknown or Protected  or PRIVATE ".
        But we are just copied the source code in the "Process Event" method to the Overwrite method.
    Can anyone provide me the clarification , why system behaving like this.
    Thanks
    Channa

    Hi,
    I think you can not.
    Because, only public attributes can be inherited and they will remain public in the subclass.
    for further detail check,
    http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
    regards,
    Anirban

  • Calling ABAP class methods from JAVA application

    Hi All,
    I want to fetch ITS related information (SITSPMON Tcode) in my JAVA application. But i didnt find much BAPIs for the same. While debugging I came accross few class methods with help of which I can get the required information. So is there any way we can call and execute methods of ABAP classes through java application?
    for e.g. I want to call GET_VERSION method of CL_ITSP_UTIL class.
    Thanks,
    Arati.

    Hi,
    Yes, as per my knowledge the only way to interact is using BAPI exposed as RFCs. So try to invoke those class methods in one CUSTOM BAPI and expose that BAPI as RFC and consume that RFC to get those details.
    Regards,
    Charan

  • Calling sub class method from superclass constructure

    hi all
    i have seen a program in which a super class constructure class methods of sub class before initialization of fields in subclass ,i want how this is posibble ?
    thanks in advance

    Hear is the code n other thing i have used final variable without initialization n compiler dosen't report error
    abstract class Test
    public Test()
    System.out.println("In DemoClass Constructer");
    this.show();
    public void show()
    System.out.println("In DemoClass Show() method");
    class Sub1 extends Test
    private final float number;
    public Sub1(float n)
    this.number=n;
    System.out.println((new StringBuilder()).append("Number is==").append(number).toString());
    int j;
    public void show()
    System.out.println("In Sub1 Class Show method ");
    public class DemoClass
    public static void main(String s[])
    Sub1 obj1=new Sub1(5);
    Sub1 obj2=new Sub1(6);
    thanks for reply

  • Calling a class method from another class

    how can i call a method / function of one class without extending that class in another class.
    and one thing more i want want o check wether any Swing gui is open or closed.

    how can i call a method / function of one class without extending that class in another class.What?... Umm... You just call it... as in Foo.bar("doe ray me");
    i want want to check if any Swing gui is open or closed.Ummm, what? I don't understand the question. Do you mean find out if a particular java programming is allready running, of do you mean is the JPanel visible, or something else?

  • Calling up class methods

    I suffer problems understanding how to call up class methods from within my programs and would like to see further examples of coding and a lending hand with the problem below, program one ProductClass works out stock item lines of a product, the program then needs to ask for the StaticProduct Class(the second program attached) to check for a valid barcode length and for how many odds and even numbers are within it a valid barcode would be 5000127062092
    I would very much appreciate some help:
    * This is a program to Enter and check product codes and prices
    * and give a summary of values at the end
    * @author (Jeffrey Jones)
    * @version (version 2 5th April 2003)
    public class ProcessProduct
    public static void main(String args[])
    StaticProduct Product = new StaticProduct();
    //declare variables
    String manuf;
    String name;
    int sLength;
    String p;
    String barcode;
    int price;
    int quantity;
    int totalPrice=0;
    int transactions=1;
    int totalQuantity=0;
    int totalValue=0;
    int averageCost=0;
    //Input Details
    System.out.print("Enter Product Manufacturer : ");
    manuf = UserInput.readString();
    //start of while loop checking for 0 to exit loop
    while (!manuf.equals("0"))
    System.out.print("Enter Product Name : ");
    name = UserInput.readString();
    System.out.print("Enter Bar Code : ");
    barcode = UserInput.readString();
    //check for invalid data
    if (StaticProduct.isValidBarcode(barcode))
    {barcode = new code();
                        p = new Product("manuf","name","quantity","price");
                        }//closing bracket of if
    else
    {//error handling
    }//closing bracket of if
    //check for quantity input and errors
    System.out.print("Enter Quantity : ");
    quantity = UserInput.readInt();
    if (quantity<=0)
    { System.out.print(" Error, invalid value ");
    System.exit(0);
    }// check for invalid entries
    System.out.print("Enter Price :");
    price = UserInput.readInt();
    //check for price input and errors
    if (price<=0)
    { System.out.print(" Error, invalid value ");
    }// check for invalid entries
    //total price value
    totalPrice=price*quantity;
    //Output of correctly inputted data
    System.out.println(manuf+":"+name+":"+barcode+":"+price);
    System.out.println(quantity+" @ "+price+" = "+totalPrice);
    //update variables quantities
    //update total quantity
    totalQuantity = (totalQuantity + quantity);
    //keep count of total value
    totalValue = (totalValue + totalPrice);
    //keep count of totqal no of transactions
    transactions = (transactions++);
    //Input Details
    System.out.print("Enter Product Manufacturer : ");
    manuf = UserInput.readString();
    }//closure of loop
    //display final totals
    System.out.println("Transactions: "+transactions);
    System.out.println("Total quantity: "+totalQuantity);
    System.out.println("Total value: "+totalValue);
    System.out.println("Average Cost: "+totalValue/totalQuantity);
    System.exit(0);
    }//closing bracket input and output of data
    }//end class
    * Write a description of class StaticProduct here.
    * @author Jeffrey Jones
    * @version 1 1st April 2003
    public class StaticProduct
    * isValidBarcode method - to check for correct barcode and length
    * @return boolean
    public static boolean isValidBarcode(String barcode) {
    barcode = new barcode();
    // validateBarcode length
    if ( barcode.length() != 13 ) {
    System.out.println("Invalid barcode " + barcode + " not 13 characters");
    return false;
    }//if
    for ( int i = 0; i < barcode.length(); i++ ){// Check every char a digit
    if ( ! Character.isDigit( barcode.charAt(i) ) ){
    System.out.println("Invalid barcode " + barcode + " not all digits");
    return false;
    }//if
    }//endfor
    int sum1 = 0; // Sum first + third + etc.
    for ( int i = 0; i < barcode.length() - 1; i += 2 ){
    sum1 += barcode.charAt(i) - '0';
    }//endfor
    int sum2 = 0; // Sum second + fourth + etc.
    for ( int i = 1; i < barcode.length() - 1; i += 2 ){
    sum2 += barcode.charAt(i) - '0';
    }//endfor
    int check = sum1 + 3 * sum2; // 1st sum + three times 2nd sum.
    check = check % 10; // Remainder on division by 10.
    if ( check != 0 ){
    check = 10 - check;
    }//endif
    if (check != barcode.charAt(12) - '0'){
    System.out.println("Invalid barcode " + barcode + " check digit error");
    }//endif
    return ( check == barcode.charAt(12) - '0' );
    }//end isValidBarcode
    public static void main(String[] argv) {
    System.out.println(isValidBarcode("1234567890123"));
    System.out.println(isValidBarcode("123"));
    System.out.println(isValidBarcode(""));
    System.out.println(isValidBarcode("5018374496652"));
    }//end main
    }//end class

    Read through your text book or some java tutorials from this site to understand what classes are, what are methods, etc.
    Your program is full of wrong initializations (as you rightly said you dont understand how to call up class method I would add that you dont understand how to call classes and what do they return e.g.
    You have declared
    String p;
    then you go ahead and do this
    p = new Product("manuf","name","quantity","price"); This is syntax for calling a class is this class returning a String? :s
    Please go through the basics of Object Oriented Programming and then start with the coding part else you will face such very many difficulties and waste more time of yours in just coding with no results.
    Look for the tutorials on this site and read through them and do example as given in them.

  • How to call a method in the servlet from an applet

    I want to get the data for the applet from the servlet.
    How to call a method that exits in the servlet from the applet? I want to use http protocol to do this.
    Any suggestions? Please help.
    thanks

    Now that Web Services is around, I'd look at possibly implement a Web Service call in your applet, which can then be given back any object(s) on return. Set up your server side to handle Web Service calls. In this way, you can break the applet out into an application should you want to (with very little work) and it will still function the same

  • I want to send a response from the servlet and then call another servlet.

    Hi,
    I want to send a response from the servlet and then call another servlet. can this happen. Here is my scenario.
    1. Capture all the information from a form including an Email address and submit it to a servlet.
    2. Now send a message to the browser that the request will be processed and mailed.
    3. Now execute the request and give a mail to the mentioned Email.
    Can this be done in any way even by calling another servlet from within a servlet or any other way.
    Can any one Please help me out.
    Thanks,
    Ramesh

    Maybe that will help you (This is registration sample):
    1.You have Registration.html;
    2.You have Registration servlet;
    3.You have CheckUser servlet;
    4.And last you have Dispatcher between all.
    See the code:
    Registration.html
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <HTML>
      <HEAD>
        <TITLE>Hello registration</TITLE>
      </HEAD>
      <BODY>
      <H1>Entry</H1>
    <FORM ACTION="helloservlet" METHOD="POST">
    <LEFT>
    User: <INPUT TYPE="TEXT" NAME="login" SIZE=10><BR>
    Password: <INPUT TYPE="PASSWORD" NAME="password" SIZE=10><BR>
    <P>
    <TABLE CELLSPACING=1>
    <TR>
    <TH><SMALL>
    <INPUT TYPE="SUBMIT" NAME="logon" VALUE="Entry">
    </SMALL>
    <TH><SMALL>
    <INPUT TYPE="SUBMIT" NAME="registration" VALUE="Registration">
    </SMALL>
    </TABLE>
    </LEFT>
    </FORM>
    <BR>
      </BODY>
    </HTML>
    Dispatcher.java
    package mybeans;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Dispatcher extends HttpServlet {
        protected void forward(String address, HttpServletRequest request,
                               HttpServletResponse response)
                               throws ServletException, IOException {
                                   RequestDispatcher dispatcher = getServletContext().
                                   getRequestDispatcher(address);
                                   dispatcher.forward(request, response);
    Registration.java
    package mybeans;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Registration extends Dispatcher {
        public String getServletInfo() {
            return "Registration servlet";
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext ctx = getServletContext();
            if(request.getParameter("logon") != null) {          
                this.forward("/CheckUser", request, response);
            else if (request.getParameter("registration") != null)  {         
                this.forward("/registration.html", request, response);
    CheckUser.java
    package mybeans;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class CheckUser extends Dispatcher {
        Connection conn;
        Statement stat;
        ResultSet rs;
          String cur_UserName;
        public static String cur_UserSurname;;
        String cur_UserOtchestvo;
        public String getServletInfo() {
            return "Registration servlet";
        public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            try{
                ServletContext ctx = getServletContext();
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:oci:@eugenz","SYSTEM", "manager");
                stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
               String queryDB = "SELECT ID, Login, Password FROM TLogon WHERE Login = ? AND Password = ?";
                PreparedStatement ps = conn.prepareStatement(queryDB); 
               User user = new User();
            user.setLogin(request.getParameter("login"));
            String cur_Login = user.getLogin();
            ps.setString(1, cur_Login);
            user.setPassword(request.getParameter("password"));
            String cur_Password = user.getPassword();
            ps.setString(2, cur_Password);
         Password = admin");
            rs = ps.executeQuery();
                 String sn = "Zatoka";
            String n = "Eugen";
            String queryPeople = "SELECT ID, Surname FROM People WHERE ID = ?";
           PreparedStatement psPeople = conn.prepareStatement(queryPeople);
                      if(rs.next()) {
                int logonID = rs.getInt("ID");
                psPeople.setInt(1, logonID);
                rs = psPeople.executeQuery();
                rs.next();
                       user.setSurname(rs.getString("Surname"));
              FROM TLogon, People WHERE TLogon.ID = People.ID";
                       ctx.setAttribute("user", user);
                this.forward("/successLogin.jsp", request, response);
            this.forward("/registration.html", request, response);
            catch(Exception exception) {
    }CheckUser.java maybe incorrect, but it's not serious, because see the principe (conception).
    Main is Dispatcher.java. This class is dispatcher between all servlets.

  • How to call a specific method in a servlet from another servlet

    Hi peeps, this post is kinda linked to my other thread but more direct !!
    I need to call a method from another servlet and retrieve info/objects from that method and manipulate them in the originating servlet .... how can I do it ?
    Assume the originating servlet is called Control and the servlet/method I want to access is DAO/login.
    I can create an object of the DAO class, say newDAO, and access the login method by newDAO.login(username, password). Then how do I get the returned info from the DAO ??
    Can I use the RequestDispatcher to INCLUDE the call to the DAO class method "login" ???
    Cheers
    Kevin

    Thanks for the reply.
    So if I have a method in my DAO class called login() and I want to call it from my control servlet, what would the syntax be ?
    getrequestdispatcher.include(newDAO.login())
    where newDAO is an instance of the class DAO, would that be correct ?? I'd simply pass the request object as a parameter in the login method and to retrieve the results of login() the requestdispatcher.include method will return whatever I set as an attribute to the request object, do I have that right ?!!!!
    Kevin

  • Getting error while calling ejb business methods from servlet

    Hi
    Iam getting error when i try to call a ejb method from servlet.Error is
    "com.netscape.server.eb.UncheckedException: unchecked exception nested exception is:java.lang.NullPointerException".
    I build the application and deployed it successfully.Iam using IAS 6.O with windows NT 4.0.
    This is just a method which takes values from database and return as an array of bean to servlet.
    Any help on this.Thanks Shank

    Hi
    I was using the session bean.Your suggestion helped me a lot.Perfect.
    I debug my program and found that from ejbCreate()exception is getting.
    I was getting the datasource object thro ejb create() initialisation.
    Somehow the look up jndi which i mentioned was not interpretting from ejb-jar.xml ias-ejb-jar.xml and datasource ref .Due to this iam getting jndi Namenotfound exception which in turns to null pointer as datasource is getting null.
    when i hardcoded in the ejb the the jndi name for datasource it is working fine.Bit worried all the existing ejbs working with the xml referenced datasource and jndi,but when i added a new ejb with same properties it is failing to get the jndi name.
    Piece of code from ias-ejb-jar.xml
    <resource-ref>
              <res-ref-name>myDataSource</res-ref-name>
              <jndi-name>jdbc/nb/myData</jndi-name>
    </resource-ref>
    Piece of code from ejb-jar.xml
    <resource-ref>
              <res-ref-name>myDataSource</res-ref-name>
              <res-type>javax.sql.DataSource</res-type>
              <res-auth>Container</res-auth>
    </resource-ref>
    Thanks a lot meka

Maybe you are looking for

  • Problem on LDB

    Hai  Gurus,   I had a problem while checking an Logical DataBase Program.   I have created One Structure(SE36) name ZCVTEST and I have taken two Nodes   First One is LFA1 and brach node is LFB1. and i have write in selctions  :   SELECT * FROM LFA1  

  • Running L_TO_CONFIRM getting Error Message L3 025

    All; I am running L_TO_CONFIRM for confirming a TO.    CALL FUNCTION 'L_TO_CONFIRM'     EXPORTING       i_lgnum                              = gv_lgnum       i_tanum                              = gv_tanum     TABLES       t_ltap_conf                

  • Component number demand in MD04 missing

    A packaging number in a material bom has stopped generating demand in MD04.  It is still in the BOM and has all of the settings that other material’s packaging numbers have.  When a MD41 is ran for the material a summary of components is listed, and

  • White Screen - Troubleshooting not working.. help?

    Well, my 4G iPod Touch just recently white screened on me. I was in the middle of using an app, and it froze and turned white. I've tried all the troubleshooting suggestions, but none of them worked. When I tried to connect it to my computer, iTunes

  • Dead link on Grid Control white paper page

    On the following page: http://www.oracle.com/technology/products/oem/htdocs/oem_wps.html the paper entitled "Monitoring Forms with Oracle Enterprise Manager Grid Control May 2006" is a dead link.