Class.forname (help please)

Hello,
I would like to load a class with class.forname. BUT, I just know the package and the path to the class. This class its not on class-path...
What I know is:
class: myClass
package: org.java
location: c:\myClases
current class path: c:\myClassPath
Class.forName("org.java.myClass");
this above does not works because org.java.myClass its not on classpath
Any ideas?

URL directory = new URL("file:/location where your package is/"); // dont forget to end it with /
URL[] classPath = new URL[] {directory};
ClassLoader loader = URLClassLoader.newInstance(classPath);     
Class youClass = Class.forName("org.java.myClass", true, loader);

Similar Messages

  • Help with loading dynamic classes ..need help please

    i'm trying to design a program where by i can load dynamic classes
    the problem i'm getting is that only one class is loading.
    classes are loaded by their names,and index numbers of public methods from a linklist
    .When the program runs only the first class is ever loaded and only the methods of that class ..
    help please
    //class loader
    import java.lang.reflect.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test2 extends Thread
         public Class c;
         public Class Ray;
         public Class[] x;
         public static Object object = null;
         public Method[] theMethods;
         public static Method[] method,usemethod;
         public int methodcount;
         public static int MethodCt;     
         public static JList list;
    public Method[] startClass(String SetMethodName)
         try
              c = Class.forName(SetMethodName);
              object = c.newInstance();
              theMethods = c.getDeclaredMethods();
              // number of methods
              //methodcount = theMethods.length;
         catch (Exception e)
              e.printStackTrace();
    // return the array then invoke the particular method later
    return theMethods ;
    public void RunMethod(Method[] SomeMethod, int methodcount)
         try
              SomeMethod[methodcount].invoke( object,null );
         catch (Exception e)
              e.printStackTrace();
    // end class loader
    //main calling program
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing .*;
    import java.lang.reflect.*;
    public class JFMenu extends JFrame
         public static JMenu pluginMenu;
         public static JMenuBar bar;
         public static final Test2 w = new Test2();
    public static Method[] setmethod;
    private static ClassLinkList startRef = null;
    private static ClassLinkList linkRef3 = null;
    private static ClassLinkList startRef2 = null;
    private String ClassName,ShortCut;
    private int MethodNumber;
    private JMenuItem PluginItem;
         JFMenu()
              super (" JFluro ");     
              JMenu fileMenu = new JMenu("File");
              fileMenu.setMnemonic('F');
              JMenuItem exitItem = new JMenuItem("Exit");
              exitItem.setMnemonic('X');
              fileMenu.add(exitItem);
              exitItem.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             System.exit(0);
              JMenu pluginMenu = new JMenu("Plugins");
              pluginMenu.setMnemonic('P');
              startRef = new ClassLinkList ("Hello","Hello ",2,1926,"Painter");
              addToList("Foo","Foo ",0,1930,"Author");
              while (startRef.linkRef5 != null)
                   //pluginMenu.addSeparator();
                   ClassName = startRef.linkRef5.className;
                   ShortCut = startRef.linkRef5.shortcutName;
    MethodNumber = startRef.linkRef5.methodNumber;
    AddMenuItem(pluginMenu,ShortCut,ClassName,MethodNumber);
                   startRef.linkRef5 = startRef.linkRef5.next;
              // create menu bar and add JFMenu window to it
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              bar.add(fileMenu);
              bar.add(pluginMenu);
              //attributes for JFMenu frame
              setSize(500,200);
              setVisible(true);
         }// end JFMenu constructor
         public void AddMenuItem(JMenu MainMenu, String shortcut,String className, final int methodCount )
              if (MainMenu==null)
                   return;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              setmethod = w.startClass(className);
              item.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         public JMenuItem AddMenuItem2(JMenu MainMenu, String shortcut)
              //if (MainMenu==null)
              //     return Main;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              //setmethod = w.startClass(className);
              //item.addActionListener(this);
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         return item;
         public void ReloadMenu(JMenuBar Bar, JMenu PluginMenu)
              if (Bar==null)
                   return;
              //     setJMenuBar(Bar);
              Bar.add(PluginMenu);
              //item.addActionListener(ij);
    public static void main (String args[])
              JFMenu menapp = new JFMenu();
    public static void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description) {
         // Create instance of class ClassLinkList
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);
    // end main calling program
    class Hello extends Thread
    public int getNum()
    System.out.println("I can be ");
    return 5;
    public void rayshowName()
    System.out.println("anything i want ");
    public void rayshowName3()
    System.out.println("to be ");
    class Foo extends Thread
    public int getNum()
    System.out.println("IMHOFF");
    return 5;
    public void rayshowName()
    System.out.println("raYMOND");
    // FAMOUS PERSONS LINKED LIST EXAMPLE
    // Frans Coenen
    // Saturday 15 January 2000
    // Depaertment of Computer Science, University of Liverpool
    class ClassLinkList {
    /* FIELDS */
    public String className;
    public String shortcutName;
    public int methodNumber;
    public int yearOfDeath;
    public String occupation;
    public ClassLinkList next = null;
    public ClassLinkList linkRef5 = this;
    public ClassLinkList startRef = null;
    /* CONSTRUCTORS */
    /* FamousPerson constructor */
    public ClassLinkList(String classname, String shortcutname, int methodnumber, int year2,
                                  String description) {
         className = classname;
         shortcutName = shortcutname;
         methodNumber = methodnumber;
         yearOfDeath = year2;
         occupation = description;
         next = null;
    /* METHODS */
    /* Output famous person linked list */
    public void outputClassLinkedList()
         //public ClassLinkList outputClassLinkedList() {
         ClassLinkList linkRef = this;
         // Loop through linked list till end outputting each record in turn
    while (linkRef != null)
         //System.out.println(linkRef5);
         System.out.println(linkRef.className + ", " + linkRef.shortcutName +
                   " (" + linkRef.methodNumber + "-" + linkRef.methodNumber +
                   "): " + linkRef.occupation);
         linkRef = linkRef.next;     
    //return linkRef;
    //public String ShowCasname()
    //return String ;     
    /* Add a new record to the linked list */
    public ClassLinkList addRecordToLinkedList(ClassLinkList newRef) {
         ClassLinkList tempRef, linkRef;
         // Test if new person is to be added to start of list if so return
    if (newRef.testRecord(this) ) {
         newRef.next = this;
         return(newRef);
         // Loop through remainder of linked list
         tempRef = this;
         linkRef = this.next;
         while (linkRef != null) {
         if (newRef.testRecord(linkRef)) {
         tempRef.next = newRef;
              newRef.next = linkRef;
              return(this);
         tempRef = linkRef;
         linkRef = linkRef.next;
    // Add to end
    tempRef.next = newRef;
         return(this);
    /* Delete a record from the linked list given the first and last name. Four
    posibilities:
    1) Record to be deleted is at front of list
    2) Record to be deleted is at end of list
    3) Record to be deleted is in middle of list
    4) Record not found. */
    public ClassLinkList deleteRecord(String lName, String fName) {
    ClassLinkList tempRef, linkRef;
    // Record at start of list
    if ((this.className == lName) & (this.shortcutName == fName))
         return(this.next);
         // Loop through linked list to discover if record is in middle of list.
         tempRef = this;
    linkRef = this.next;
    while (linkRef != null) {
         if ((linkRef.className == lName) & (linkRef.shortcutName == fName)) {
    tempRef.next = linkRef.next;
    return(this);
    tempRef = linkRef;
    linkRef = linkRef.next;
    // Record at end of list, or not found
    if ((linkRef.className == lName) & (linkRef.shortcutName == fName))
                        linkRef = null;
         else System.out.println("Record: " + lName + " " + fName + " not found!");
         return(this);
    /* TEST METHODS */
    /* Test whether new record comes before existing record or not. If so return
    true, false otherwise. */
    private boolean testRecord(ClassLinkList existingRef) {
         int testResult = className.compareTo(existingRef.className);
         if (testResult < 0) return(true);
         else {
         if ((testResult == 0) & (shortcutName.compareTo(existingRef.shortcutName) < 0 ))
                             return(true);
         // Return false
         return(false);
         public void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description)
         // Create instance of class Famous Person
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);

    I have a similar problem. I am writing a program to read the class names from database and instantiate several classes which extends from ServiceThread (an abstract class extending from Thread).
    rs = pStmt.executeQuery();
    while(rs.next()) {
    String threadclassname = rs.getString("classname").trim();
    try{
    ServiceThread threadinstance = (ServiceThread)Class.forName(threadclassname).newInstance();
    }catch ...
    So far, only the first class is ever instantiated and runs fine. But subsequent classes do not even get pass the "... ... Class.forName(...).newInstance();" line.
    Funny thing is that there are also no exceptions. The JVM just seem to hang there.

  • E3200 quit working, I already tried factory reset, out of ideas...help please?

    I've had the E3200 for 3 weeks now and it has been running perfectly until last night. It's broadcasting its SSID and when I open network properties on my computer, it says I'm connected to the internet. However, when I troubleshoot with windows and cisco connect they both recognize that I'm not connected to the internet. Tried with 2 other laptops, an andriod phone, and an iphone with the same results. I live in an apartment building and the only thing we need to set up is a router for wifi (modem   connection is taken care of in the basement) so there's no issues with a modem because the other tenants have internet, and when I connected my laptop directly to the wall I had internet access so I'm pretty certain it's an issue with the router. I tried a factory reset and went through the installation again but had the same result as before. I called customer support but they had me on hold until I had to leave for class. HELP PLEASE!

    You may need to reconfigure the router. What is the IP address that your computer is getting if it’s directly connected to the wall? If using the setup cd to reconfigure the router didn’t work, try doing it manually. These links will guide you thru in doing the reconfiguration manually: Setting up a Linksys router with Cable Internet service & Setting up a Linksys router for DSL Internet connection.

  • Where we define Class.forName("drivername")

    Hi all,
    anybody please tell me where we define Class.forName("drivername").
    please answer with details.
    please reply soon.
    Thanks
    amitindia

    private void loadDrivers(Properties props) {
    String driverClasses = props.getProperty("drivers");
    StringTokenizer st = new StringTokenizer(driverClasses);
    while (st.hasMoreElements()) {
    String driverClassName = st.nextToken().trim();
    try {
    Driver driver = (Driver)
    Class.forName(driverClassName).newInstance();
    DriverManager.registerDriver(driver);
    drivers.addElement(driver);
    catch (Exception e) {
    log(".... " +
    driverClassName + ", ..: " + e);
    }

  • Help Please ....  Unable to load Driver Class

    Hi There:
    When I try to connect to the Oracle 8i via this applet , I get the following run time error.
    Any help will be appreciated.
    I am using j2sdkee1.3.1, jdk1.3.1_02 and Oracle8.
    I also need your suggestion please. I have inserted some BLOB data in the Oracle table. I will need to display the BLOB data to the end users. I plan to convert this BLOB data into string format so that my applet can display the same. Further the string will have to be edited by the end users. I will then convert this modified string back to byte array so that I can insert the same as BLOB.
    Please let me know applet or the servlet? Which is better option.
    Users are reluctant to use any kind of WebServer because it will introduce the additional layer of complexity.
    Any help will be greatly appreciated.
    Thanks in advance.
    C:\>AppletViewer JdbcApplet.html
    Unable to load Driver Class
    java.lang.ClassNotFoundException: java.io.FileNotFoundException: C:\oracle\jdbc\
    driver\OracleDriver.class (The system cannot find the path specified)
    The following code snippet fails because it is unable to find the suitable driver.
    if (conn == null)
         //make a connection to the db
         try {     
              // conn = DriverManager.getConnection ("jdbc:oracle:thin:@"+"localhost:1521:sys", "system", "manager");
              // conn = DriverManager.getConnection ("jdbc:oracle:thin:system/manager@(description=(address_list= (address=(pro tocol=tcp)(host=localhost)(port=1521)))(source_route=yes)(connect_data=(sid=sys)))" );
              Class.forName("oracle.jdbc.driver.OracleDriver");
              String conurl="jdbc:oracle:thin:@localhost:1521:sys";
              Connection con=DriverManager.getConnection(conurl,"system","manager");
         } catch ( Exception e ) {
              System.out.println ("Unable to load Driver Class");
              e.printStackTrace (System.out);
              // add send email notification about this fact
              return false;
    } // End of if Statement from conn...

    Hi,
    maybe I'm too late but try the following :
    It seems that Your IDE doesn't check the path to Your classesxxx.zip file.
    Or Your classesxxx.zip file is corrupt.
    We had this error after downloading the classes12.zip for Oracle versions
    higher 8.1.6.
    The original size of this file is 1.888kB.
    Remember Windows FTP is downloading in ascii mode per default.
    Or Your classpath isn't correct
    ( the Exception souns like this )
    Regards

  • Need Help Loading Sqlbase Driver Using Class.forName(...

    I'm having trouble connecting to a Sqlbase database on my PC. The problem seems to be with loading the driver with the "Class.forName" method. My source code (listed below) is in the "C:\My Documents\java" folder. I installed the Sqlbase driver in "C:\com\centurasoft\java\sqlbase" folder. The driver installation modified my autoexec.bat file to include the line "SET CLASSPATH=C:\com\centurasoft\java\sqlbase".
    The epdmo database is in a folder on my D:\ drive.
    It seems to find the SqlbaseDriver.class file, but for some reason it can't load it. I would greatly appreciate any suggestions as to how I can fix this.
    With the line -- Class.forName("centura.java.sqlbase.SqlbaseDriver");
    The SqlbaseEx.java program will compile, but I get the following error
    when I try to run it:
    Exception in thread "main" java.lang.NoClassDefFoundError: SqlbaseDriver (wrong name: com/centurasoft/java/sqlbase/SqlbaseDriver)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    ... [several more lines like these]
    at SqlbaseEx.main(SqlbaseEx.java:25)
    With the line -- DriverManager.registerDriver(new SqlbaseDriver());
    The SqlbaseEx.java program will NOT compile. I get the following error:
    SqlbaseEx.java:21: cannot access SqlbaseDriver
    bad class file: C:\com\centurasoft\java\sqlbase\SqlbaseDriver.class
    class file contains wrong class: com.centurasoft.java.sqlbase.SqlbaseDriver
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    Also, does the line -- String url = "jdbc:sqlbase:epdmo";
    look OK? I've seen numerous examples and they all have some values separated by slashes //. Am I
    missing something here that will bite me when I get past this driver loading error?
    import java.sql.*;
    // Create the ...
    public class SqlbaseEx {
    public static void main(String args[]) {
    String url = "jdbc:sqlbase:epdmo";
    Connection con;
    String createString;
    createString = "create table COFFEES " +
    "(COF_NAME varchar(32), " +
    "SUP_ID int, " +
    "PRICE float, " +
    "SALES int, " +
    "TOTAL int)";
    Statement stmt;
    try {
    Class.forName("centura.java.sqlbase.SqlbaseDriver");
    // DriverManager.registerDriver(new SqlbaseDriver());
    } catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(e.getMessage());
    try {
    con = DriverManager.getConnection(url, "SYSADM", "SYSADM");
    stmt = con.createStatement();
    stmt.executeUpdate(createString);
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());

    Thanks for the reply.
    Upon further testing, I think my original post was slightly incorrect: if I use either of the following lines --
    Class.forName("com.centurasoft.java.sqlbase.SqlbaseDriver");
    or
    Class.forName("centura.java.sqlbase.SqlbaseDriver");
    I get the following error at runtime:
    ClassNotFoundException: com.centurasoft.java.sqlbase.SqlbaseDriver
    or
    ClassNotFoundException: centura.java.sqlbase.SqlbaseDriver
    It is when I use the line -- Class.forName("SqlbaseDriver");
    that I get the long error message in my original post.
    I don't understand why it can't find/load the driver. I feel like I've covered all the bases -- I've tried numerous variations of the driver name in the Class.forName method, my classpath variable seems to be set correctly. Does it matter what folder I compile my program in? Right now, I've just been compiling it in the same folder as the driver file -- c:\com\centurasoft\java\sqlbase.

  • Help! JSP w/ struts can't find Class.forName("com.mysql.jdbc.Driver")

    I think this is just a directory structure issue but I can't figure it out. I am writing a JSP / Struts / MYSQL web application which uses the mysql JDBC connector. The connector (mysql-connector-java-5.1.6-bin.jar) is in the referenced libraries. If I write the line of code:
    Class.forName("com.mysql.jdbc.Driver");
    To load up the driver, it works in JSP files in the folder /projectname/webroot/web-inf just fine and I can go on to execute MySQL queries. However, I need to load up the driver in an action (.java action) with the directory structure /projectname/src/action and it throws the exception "class not found", I believe, it can no longer seem to get to the driver. Can anyone tell me how to resolve this problem?
    Thanks in advance, I hope this is the correct place (I have done my best to find the right one).
    Edited by: Arkanin on Apr 24, 2008 4:39 PM

    Arkanin wrote:
    I think this is just a directory structure issue but I can't figure it out. I am writing a JSP / Struts / MYSQL web application which uses the mysql JDBC connector. The connector (mysql-connector-java-5.1.6-bin.jar) is in the referenced libraries. Nope, it's not. I don't know what "referenced libraries" means. It has to be in CLASSPATH, and that isn't an environment variable.
    If I write the line of code:
    Class.forName("com.mysql.jdbc.Driver"); No, wrong.
    The JAR file for the Driver class might go in the WEB-INF/lib of your web app. If you're using Tomcat 5.5.26, put it in common/lib.
    %

  • Scholar92 - Strange error Need help please

    Lecori Salutem
    The program I have a problem with is supposed to extract info from a DB. It extracts the info perfectly but I cannot access the info with my get commands from other classes.
    When i fire the program it says " [Ljava.lang.String;@1ba34f2 ". Can anyone help me to solve this problem please.
    ////////CODE STARTS HERE
    import java.sql.*;
    import javax.swing.*;
    /** Description:
    *  Die program word gebruik om al die metadata en paths wat getabuleer is
    *  op die Music DB te access en te stoor.
    *  @author Benni( [email protected])
    public class SQLImport
        private Connection connSQL;
            int tel = 2; // ID in SQL tabel begin by "2"
            String [] tName = new String [100];
    String [] tArtist = new String [100];
    String [] tGenre = new String [100];
    String [] tMood = new String [100];
    String [] tPath = new String [100];
    String [] tJavaPath = new String [100];
    String [] tID = new String [100];
    String [] tTime = new String [100];
    public SQLImport( )
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    connSQL = DriverManager.getConnection("jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=Music.mdb");
    JOptionPane.showMessageDialog(null, "Connection Successfully Established", "Notification",JOptionPane.INFORMATION_MESSAGE);
    catch (Exception sqlConnectionFailed)
    JOptionPane.showMessageDialog(null, sqlConnectionFailed, "ERROR:",JOptionPane.ERROR_MESSAGE);
    Statement statement = null;
    try
    statement = connSQL.createStatement( );
    catch (SQLException statementERROR)
    JOptionPane.showMessageDialog(null,statementERROR, "ERROR:",JOptionPane.ERROR_MESSAGE);
    char optionChoice;
    do
    optionChoice = getMenuChoice();
    if(optionChoice == 'A')
    try
    String querySQL = "SELECT * FROM tbl_ListedMusic ORDER BY ID ;";
    System.out.println(querySQL);
    ResultSet resultSet = statement.executeQuery(querySQL);
    while (resultSet.next( ))
    tID[tel] = resultSet.getString("ID");
    tName[tel] = resultSet.getString("TrackName");
    tArtist[tel] = resultSet.getString("TrackArtist");
    tTime[tel] = resultSet.getString("TrackTime");
    tGenre[tel] = resultSet.getString("TrackGenre");
    tMood[tel] = resultSet.getString("TrackMood");
    tJavaPath[tel] = resultSet.getString("TrackJavaPath");
    tPath[tel] = resultSet.getString("TrackPath");
    tel++;
    catch (SQLException infoImportError)
    JOptionPane.showMessageDialog(null,infoImportError, "ERROR:",JOptionPane.ERROR_MESSAGE);
    while (optionChoice != 'X');
    //NB! Strings are " " chars are ' '
    public String[ ] gettID( )
    return tID;
    public String[ ] gettName( )
    return tName;
    public char getMenuChoice( )
    String menu = "A) Import .mp3 info \n X) Exit";
    char choice = JOptionPane.showInputDialog(menu).toUpperCase( ).charAt(0);
    return choice;
    public static void main (String [ ] args)
    SQLImport sql = new SQLImport( );
    String [ ] blah = new String [10];
    blah = sql.gettID();
    System.out.println(blah);
    //Code ENDS
    How do I resolve the " [Ljava.lang.String;@1ba34f2   "  ? Much apreciated
    Regards,
    Bennu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    This forum is about the Messaging Server email server and related products. I think you have posted this question in the wrong forum.

  • I can't insert my data into the table - help please

    Hello everyone,
    I have a trouble about JSP. I'm using Java2 SDK,JSP 1.2,Mysql and TOMCAT.
    I want to do this. A user has to enter the nicno,into the html form(EnterNicInter.jsp),to verify if it is already exist or not. If it is exist in the db, an error msg(Record already exist) must be displayed. If not, then the page "InterviewForm.jsp" displayed. This part is working.
    But, I can't save these details into the db by clicking submit button int the InterviewForm.jsp.
    I wrote a javaBean for this task. Here is it.
    CandidateMgr.java
    package hrm;
    import java.io.*;
    import java.sql.*;
    public class CandidateMgr
         private String nicno;
            private String title;
            private String firstName;
         private String civilStatus;
            private String tele;
            private String eduQua;
         // Constructor
         public CandidateMgr()
              this.nicno = nicno;
              this.title = title;
              this.firstName = firstName;
              this.civilStatus= civilStatus;
              this.tele = tele;
              this.eduQua = eduQua;
              //getters & setters.
               // Initializes the connection and statements
            public void initConnection() {
                    if (connection == null) {
                 try {
                          String sql;
                          // Open the database
                          Class.forName(DRIVER).newInstance();
                          connection = DriverManager.getConnection(URL);
                          //Verify nicno
                          sql="SELECT * FROM Candidate where nicNo= ?";          
                   pstmt1 = connection.prepareStatement(sql);
                   sql ="INSERT INTO Candidate                               
                   VALUES(?,?,?,?,?,?)";
                   pstmt2 = connection.prepareStatement(sql);
             catch (Exception ex) {
                System.err.println(ex.getMessage());
         public boolean verifyNicNo(){
              boolean nic_no_select_ok = false;
              String nic="xxxx";
              initConnection();
                    try {
                       pstmt1.setString(1, nicno);
                   ResultSet rs1 = pstmt1.executeQuery();               
                                if(rs1.next()){
                        nic=rs1.getString("nicNo");
                               if(nic=="xxxx")
                        nic_no_select_ok = true;
                   } else{
                        nic_no_select_ok = false;     
                   rs1.close();
                           pstmt1.close();
                    catch (Exception ex) {
                      System.err.println(ex.getMessage());
              return nic_no_select_ok;
         public boolean addInter(){
              boolean add_inter_ok = false;
              try{
                      //assign values for the object
                   pstmt2.setString(1, nicno);   //      ERROR(java:652)
                   pstmt2.setString(2, title);
                   pstmt2.setString(3, firstName);
                   pstmt2.setString(4, civilStatus);
                   pstmt2.setString(5, tele);     
                   pstmt2.setString(6, eduQua);
                   if(pstmt2.executeUpdate()==1) add_inter_ok=true;
                   pstmt2.close();  
                  catch(SQLException e2){
                           System.err.println(e2.getMessage());
              return add_inter_ok;
    IntreviewForm.jsp (used to submit data into the db)
    <form method="POST" action="InterviewCtrl.jsp">
         //codes
    <input type="text" name="nicno" size="14" style="border:1px solid #0000FF;           
    color: #FF0000; font-weight: bold">
    <input type="text" name="title" size="14" style="border:1px solid #0000FF;           
    color: #FF0000; font-weight: bold">
    <input type="text" name="firstName" size="14" style="border:1px solid #0000FF;           
    color: #FF0000; font-weight: bold">
    <input type="text" name="civilStatus" size="14" style="border:1px solid #0000FF;           
    color: #FF0000; font-weight: bold">
    <input type="text" name="tele" size="14" style="border:1px solid #0000FF;           
    color: #FF0000; font-weight: bold">
    <input type="text" name="eduQua" size="14" style="border:1px solid #0000FF;           
    color: #FF0000; font-weight: bold">
    </form>.......................................................................
    Here is the "InterviewCtrl.jsp"
    <%@ page language="java" import="java.util.*"%>
    <%@ page import="hrm.CandidateMgr" %>
    <%@ page session="false" %>
    <jsp:useBean id="candidate" class="hrm.CandidateMgr" scope="request"/>
    <jsp:setProperty name="candidate" property="*"/>
    <%-- Execute the addInter() method on the bean and check if it is true or false.-- %>
    <%-- if it's true then display a confirmation message "InterConfirm.html" --%>
    <%-- else display InterError.html --%>
    <%
    String nextPage ="MainForm.jsp";
    if(candidate.addInter()){
         nextPage="InterConfirm.html";
         }else{
         nextPage="InterError.html";
    %>
    <jsp:forward page="<%=nextPage%>"/>.......................................................................
    Here is the error:(I mark it in my bean also)
    root cause
    java.lang.NullPointerException
         at hrm.CandidateMgr.addInter(CandidateMgr.java:652)
         at org.apache.jsp.InterviewCtrl_jsp._jspService(InterviewCtrl_jsp.java:66)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    I use JSP 1.2 , mySQL with TOMCAT. My table name is Candidate.It's fields are as follows:
    Candidate(nicNo,title,fName,civilStatus,tele,eduQua)
    Can anybody tell me whats going on, help me to solve this please.
    Thanks.

    you should try something different, since you are mixing up a lot of code.
    1) create a separate method just to connect and disconnect from a database;
    2) use the value entered and see if you can find a record in the table. If the record is there, then you should re-direct your jsp to a jspError, else goes to another form.
    the code below give you some idea
          if( sAction.equals("Add1") ) {
            sITEM = request.getParameter("parameter1");
            try {
              itemmaster.connect();
              itemmaster.viewitemmaster( sITEM );
              rs = itemmaster.getRs();
              if( rs.next() ) {
                sURL = "additemmaster1.jsp";
              else {
                request.setAttribute( "asITEM", sITEM );
                sURL = "additemmaster2.jsp";
            finally {
              rs.close();
              itemmaster.disconnect();
          }

  • Class.forName, how to use it in the case?

    we have a java application:
    c:\app\TestForName.class
    inside the app, there is a call:
    Class.forName("ClassLib");
    ClassLib.class is a simplest class for testing with no package.
    ClassLib.class can be in any directory except the app's directory
    c:\app
    because ClassLib.class stands for our library class for multiple projects and multiple uses, it is not allowed to be in a special app directory.
    and, ClassLoader and URLClassLoder are not suitable in our case.
    i tried following 3 ideas, none of them is OK, please help.
    1. put ClassLib.class in directory
    c:\lib\
    (that is c:\lib\ClassLib.class)
    call application with command -cp
    java -cp c:\lib;....; TestForName
    (method Class.forName("ClassLib") call is inside TestForName.class)
    2. put ClassLib.class in
    c:\jdk\bin\
    (VM says it is one of "java.library.path")
    java -cp ....; TestForName
    3. put ClassLib.class in
    c:\jdk\JAR\classes\
    (VM says if is one of "sun.boot.class.path")
    java -cp ....; TestForName
    i really wondering how to make Class.forName() call successfuf inside application TestForName.class
    1. which directory is right place for ClassLib.class
    2. how to change command line or java code inside TestForName.class
    thx for any help.

    Why don't u use a class loader. Try this code
    // loader class
    public class Loader  extends ClassLoader {
        String path;
        public Loader(String path) {
              this.path = path;
        public Class findClass(String name) {
            byte[] b = loadClassData(path+name+".class");
            return defineClass(name, b, 0, b.length);
        private byte[] loadClassData(String name) {
            File file = new File(name);
            byte[] data = null;
            try {
                InputStream in = new FileInputStream(file);
                data = new byte[ (int) file.length()];
                for (int i = 0; i < data.length; i++) {
                    data[i] = (byte) in.read();
            catch (IOException ex) {
            file = null;
            return data;
    // in your caller class use
       Loader loader = new Loader(libPath); // lib path may be taken from a command line arg
       Object main = loader.loadClass("ClassLib", true).newInstance();I think this is what u r looking for
    Uditha Nagahawatta

  • Error in Class.forName("com.mysql.jdbc.driver")

    Hi forum,
    Please help me to solve the issue.
    im using the following jsp code for genrating the reports using JASPER REPORTS
    the JSP FILE
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page import="java.io.*"%>
    <%@ page import="java.util.*"%>
    <%@ page import="java.sql.*"%>
    <%@ page import="javax.sql.DataSource"%>
    <%@ page import="javax.naming.InitialContext"%>
    <%@ page import="net.sf.jasperreports.engine.*"%>
    <%@ page import="net.sf.jasperreports.engine.design.JasperDesign"%>
    <%@ page import="net.sf.jasperreports.engine.xml.JRXmlLoader"%>
    <%@ page import="net.sf.jasperreports.engine.export.*" %>
    <%@ page import ="net.sf.jasperreports.engine.*"%>
    <%@ page import ="net.sf.jasperreports.engine.JasperFillManager"%>
    <%@ page import ="net.sf.jasperreports.engine.JRException"%>
    <%@ page import="net.sf.jasperreports.engine.JasperReport"%>
    <%@ page import="net.sf.jasperreports.engine.JasperPrint"%>
    <html>
    <body bgcolor="00ffcc">
    <%
    try{
    Connection con = null;
    String url="jdbc:mysql://localhost/customer";
    String username = "root";
    String password = "cmsadmin";
    InputStream input=new FileInputStream(new File("C:/Documents and Settings/user/My Documents/NetBeansProjects/jasperreports/web/helloworld.xml"));
    JasperDesign design = JRXmlLoader.load(input);
    JasperReport report = JasperCompileManager.compileReport(design);
    Map params = new HashMap();
    params.put("reportTitle", "helloworld");
    params.put("author", "Muthu Kumar");
    params.put("startDate", (new java.util.Date()).toString());
    params.put("ReportTitle", "PDF JasperReport");
    <img class="emoticon" src="images/emoticons/confused.gif" border="0" alt="" />Class.forName("com.mysql.jdbc.Driver");<img class="emoticon" src="images/emoticons/confused.gif" border="0" alt="" /><img src="images/emoticons/confused.gif" border="0" alt="" />
    con = DriverManager.getConnection(url,username,password);
    JasperPrint print = JasperFillManager.fillReport(report, params, con);
    OutputStream output=new FileOutputStream(new File("C:/Documents and Settings/user/My Documents/NetBeansProjects/jasperreports/helloreportworld.pdf"));
    JasperExportManager.exportReportToPdfStream(print, output);
    // JasperViewer.viewReport(print);
    catch(SQLException es) {
    out.println(es);
    catch(JRException ex){
    //ex.printStackTrace();
    out.println(ex);
    %>
    </body>
    </html>The error it is saying is in the line Class.forName(....) ;
    Please look for the emoctions with question mark
    i DOn know what to do.
    Please help
    Im comparin the below JRXML file as with the above code
    <?xml version="1.0"?>
    <!DOCTYPE jasperReport
    PUBLIC "-//JasperReports//DTD Report Design//EN"
    "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
    <jasperReport name="helloworld">
    <parameter name="reportTitle" class="java.lang.String"/>
    <parameter name="author" class="java.lang.String"/>
    <parameter name="startDate" class="java.lang.String"/>
    <queryString>
    <![CDATA[SELECT * FROM customer order by UserID ]]>
    </queryString>
    <field name="UserID" class="java.lang.String"/>
    <field name="UserName" class="java.lang.String"/>
    <field name="City" class="java.lang.String"/>
    <field name="State" class="java.lang.String"/>
    <title>
    <band height="60">
    <textField>
    <reportElement x="0" y="10" width="500" height="40"/>
    <textElement textAlignment="Center">
    <font size="24"/>
    </textElement>
    <textFieldExpression class="java.lang.String">
    <![CDATA[$P{reportTitle}]]>
    </textFieldExpression>
    </textField>
    <textField>
    <reportElement x="0" y="40" width="500" height="20"/>
    <textElement textAlignment="Center"/>
    <textFieldExpression class="java.lang.String">
    <![CDATA["Run by: " + $P{author}
    + " on " + $P{startDate}]]>
    </textFieldExpression>
    </textField>
    </band>
    </title>
    <columnHeader>
    <band height="30">
    <rectangle>
    <reportElement x="0" y="0" width="500" height="25"/>
    <graphicElement/>
    </rectangle>
    <staticText>
    <reportElement x="5" y="5" width="50" height="15"/>
    <textElement/>
    <text><![CDATA[UserID]]></text>
    </staticText>
    <staticText>
    <reportElement x="55" y="5" width="150" height="15"/>
    <text><![CDATA[UserName]]></text>
    </staticText>
    <staticText>
    <reportElement x="205" y="5" width="255" height="15"/>
    <text><![CDATA[City, State]]></text>
    </staticText>
    </band>
    </columnHeader>
    <detail>
    <band height="20">
    <textField>
    <reportElement x="5" y="0" width="50" height="15"/>
    <textElement/>
    <textFieldExpression class="java.lang.String">
    <![CDATA[$F{UserID}]]>
    </textFieldExpression>
    </textField>
    <textField>
    <reportElement x="55" y="0" width="150" height="15"/>
    <textElement/>
    <textFieldExpression class="java.lang.String">
    <![CDATA[$F{UserName}]]>
    </textFieldExpression>
    </textField>
    <textField>
    <reportElement x="205" y="0" width="255" height="15"/>
    <textElement/>
    <textFieldExpression class="java.lang.String">
    <![CDATA[$F{City} + ", " + $F{State}]]>
    </textFieldExpression>
    </textField>
    </band>
    </detail>
    </jasperReport>

    Glass_Fish wrote:
    I have set the classpath in the environment variables in the my computer properties.The web container has it's own properties. The "system" classpath means absolutely nothing to it. Read your server's documentation.

  • Question about Class.forName()

    I am trying to get an instance of a class by its name. Now, I have tried both creating it with the class's actual name and with the class's name including the package path and both times I got a java.lang.ClassNotFoundException: my/package/MyClass.
    I am reading the name out of a properties file and that's working just fine according to my logging information btu here is the code anyway:
    Properties prop = new Properties();
    try{
         java.io.FileInputStream in = new java.io.FileInputStream(inv.getPath());
         prop.load(in);
         String temp = prop.getProperty("myclass1");
         Class c = Class.forName(temp);
         rollen.put("user",c.newInstance());
         temp = prop.getProperty("myclass2");
         c = Class.forName(temp);
         rollen.put("admin",c.newInstance());
    }catch(Exception e){
         //I'm doing some more logging here, guess that's not very interesting
    }I deleted all the logging info from this code snippet to make it shorter. But I can tell you that the name does get read out as my.package.MyClass - and the package and class name are correct...
    The entries in the properties files look like this:
    myclass1=my.package.MyClass
    myclass2=my.package.MyOtherClass
    Can you help me fix this, please?

    Is your classpath okay? I tried this:
    pkg\MyClass.javapackage pkg;
    public class MyClass {
        public MyClass () {
            System.out.println ("Woohoo!");
    }Test.javapublic class Test {
        public static void main (String[] parameters) throws Exception {
            Class.forName ("pkg.MyClass").newInstance ();
    }This outputsWoohoo!as expected.
    Kind regards,
      Levi

  • Diffrence between Class.forName() and new Operator

    What is diffrence between class.forName() and new operator.Please tell in much detail.
    Also about classloader.loadclass.
    Suppose the class that we are tring to load with the help of class.forname is not compiled. Again if I make changes at runtime to that class will that get reflected.

    What is diffrence between class.forName() and new
    operator.Please tell in much detail.Class.forName loads a class. The new operator creates a new instance. Apple trees and apples.
    Also about classloader.loadclass.Read the API.
    Suppose the class that we are tring to load with the
    help of class.forname is not compiled.Then you can't load it and get an exception. Read the API.
    Again if I
    make changes at runtime to that class will that get
    reflected.Depends on the changes and when exactly you do them.

  • Jgalcambra/or any one i need ur help please...

    i have anew problem .......... very intresting one..
    in my project i use jsp as my front end , database is mssql , web server is apache tomcat........am also using servelts along with these jsp ....
    even tomcat is running i am able to open jsp files....
    in my project i mean in the front end there is login page for user id & pass word.....when i enter values in those fields i am not able to login..
    i am getting an errorpage sayin incorrect login which is designed by me only... i have already haviv these user name & password in my my database.... login page has to basically verify the input values whatever we give with these database values & go to next page but this is not happening....i am not gettin any sort of syntax error....can u please help me in fixin this problem

    i checked out all these things...the data is being retrieved from the database and the parameters being passed are also being assigned properly...the two values are not being compared properly and hence access is not allowed...the same code worked on a different system..here is the code....
    the following is the servlet:
    import java.io.IOException;
    import java.io.PrintStream;
    import java.sql.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ELogin extends HttpServlet
        public ELogin()
        public void service(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
            throws ServletException, IOException
            httpservletresponse.setContentType("text/html");
            java.io.PrintWriter printwriter = httpservletresponse.getWriter();
            String s  = httpservletrequest.getParameter("uid");
            String s1= httpservletrequest.getParameter("pw");
            String s2 = httpservletrequest.getParameter("dep");
            int i=1;       
            try
                HttpSession httpsession = httpservletrequest.getSession(true);
                Date date = new Date();
                SimpleDateFormat simpledateformat = new SimpleDateFormat("h:mm a");
                String s3 = simpledateformat.format(date);
                Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
                Connection connection = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:3413;DatabaseName=Project", "Product", "product");
                Statement statement = connection.createStatement();
                ResultSet resultset1 = statement.executeQuery(" select * from emp_log ");
                boolean flag = false;
                do
                    i++;
                    if(!resultset1.next())
                        break;
                    user1 = resultset1.getString(1);
                    pass1 = resultset1.getString(2);
                    Dep1  = resultset1.getString(3);
    /* i think the problem is in the following part of the code*/
                    if(s.equals(user1) && s1.equals(pass1) && s2.equals(Dep1))
                        javax.servlet.ServletConfig servletconfig = getServletConfig();
                        RequestDispatcher requestdispatcher = getServletContext().getRequestDispatcher("/Activity.jsp");
                        httpsession.setAttribute("Empname", s);
                        httpsession.setAttribute("Depname", s2);
                        httpsession.setAttribute("loginTime", s3);
                        httpsession.setMaxInactiveInterval(0x3938700);
                        requestdispatcher.forward(httpservletrequest, httpservletresponse);
                        flag = true;
                } while(true);
                if(!flag)
                    String s4 = "Wrong Password,Please retype!!!";
                    httpsession.setAttribute("DepError1", s4);
                    httpsession.setMaxInactiveInterval(0x3938700);
                    RequestDispatcher requestdispatcher2 = httpservletrequest.getRequestDispatcher("/ErrorPageForEmpLogin.jsp");
                    requestdispatcher2.include(httpservletrequest, httpservletresponse);
            catch(Exception exception)
                System.out.println((new StringBuilder()).append("SQLException: ").append(exception).toString());
        static String user1;
        static String pass1;
        static String Dep1;
        static String DepErrorInEmp;
        static String DepErr;
        static String user2;
        static String pass2;
        static String Dep2;
        static String DepErrorInAdmin;
        static String DepErr1;
    this is the login page:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <%@ page language="java" import="java.util.* ,java.text.SimpleDateFormat ,java.sql.*" %>
    <% java.util.Date  todayDate = new java.util.Date();
       int month = todayDate.getMonth()+1;
       int date = todayDate.getDate();
       int year = todayDate.getYear()+1900;
       int time = todayDate.getHours();
       String dateOnly = Integer.toString(month)+ "/" + Integer.toString(date)+ "/" +Integer.toString(year);%>
    <html>
    <html>
    <head>
    <title> Activity </title>
    <script language="javascript" >
    function showText()
      var thetime=new Date();
      var nhours = <%= todayDate.getHours()%>;
      var nmins = <%= todayDate.getMinutes()%>;
      var nsecn = <%= todayDate.getSeconds()%>;
      var AorP=" ";
    /*if (nhours>=12)
        AorP="P.M.";
    else
        AorP="A.M.";*/
    if (nhours>=25)
        nhours-=24;
    if (nhours==0)
    nhours=12;
    if (nsecn<10)
    nsecn="0"+nsecn;
    if (nmins<10)
    nmins="0"+nmins;
    if (nhours<10)
    nhours="0"+nhours;
      document.clockform.clockStart.value=nhours+":"+nmins+":"+nsecn+" "+AorP;
    document.getElementById("time").style.display = '';
    </script>
    <SCRIPT language="JavaScript">
    function startclock()
    var thetime=new Date();
    var nhours=thetime.getHours();
    var nmins=thetime.getMinutes();
    var nsecn=thetime.getSeconds();
    var AorP=" ";
    /*if (nhours>=12)
        AorP="P.M.";
    else
        AorP="A.M.";*/
    if (nhours>=25)
        nhours-=24;
    if (nhours==0)
    nhours=12;
    if (nsecn<10)
    nsecn="0"+nsecn;
    if (nmins<10)
    nmins="0"+nmins;
    document.clockform.clockEnds.value=nhours+":"+nmins+":"+nsecn+" "+AorP;
    setTimeout('startclock()',1000);
    </script>
    <script language="javascript" type="text/javascript">
    function submitAddfunction()
        var type = document.clockform.At;
             if(type.value == "Select")
           window.alert("Please select activity type");
           type.focus();
         else
           document.clockform.action="http://10.32.244.169:8082/Activity/Add";
              document.clockform.submit();
    function submitLogfunction() 
      { //if(i==2)
        var x = window.confirm("Do you want to logout?");
        if (x)
         document.clockform.action="http://10.32.244.169:8082/Activity/Logout";
         document.clockform.submit();
       else
          var type=document.clockform.At;
          type.focus();
    </script>
    </head>
    <body background="background1.JPG" onLoad="startclock()">
    <font face= "verdana" size="4" color=#804000>Version 1</font> <br><br>
    <%   String userName = (String)session.getAttribute("Empname");
         session.setAttribute("Empname",userName);
         String depName = (String)session.getAttribute("Depname");
         session.setAttribute("Depname",depName);
         String LoginTime = (String)session.getAttribute("loginTime");
         session.setAttribute("loginTime",LoginTime);
         session.setMaxInactiveInterval(60000000); %>
    <font face= "verdana" size="6" color=#804000>Welcome <%=userName%></font>
    <form name="clockform"><br><br>
    <font face= "verdana" size="4" color=#400000>
    <div  style="position:absolute; left:30px; top:120px; width:750px; height:323px;">
      Current Time:</font><font size="2" color=#400000> <%= todayDate %></font><br><br><br><br><br><br>
      '<%=depName%>'
    <INPUT TYPE="text" name="Dep"  size="12" value = '<%=depName%>'  style="visibility:hidden" ><br>
    <INPUT TYPE="text" name="user" size="12" value = '<%=userName%>' style="visibility:hidden" >
    <div  style="position:absolute; left:150px; top:100px; width:750px; height:323px;">
    <font face= "verdana" size="4" color=#400000>
    <center><table>
    <div  style="position:absolute; left:10px; top:10px; width:750px; height:323px;"> Login Time</div>
    <div  style="position:absolute; left:150px; top:10px; width:750px; height:323px;">
      <input type=text name="logintime" size="6" value='<%= LoginTime %>'  readonly ></div>
    <div  style="position:absolute; left:300px; top:10px; width:750px; height:323px;"> Date</div>
    <div  style="position:absolute; left:350px; top:10px; width:750px; height:323px;">
      <input type=text name="date" size="8" value='<%= dateOnly %>'  readonly > </div>
    <div  style="position:absolute; left:10px; top:50px; width:750px; height:323px;">Activity Type</div>
    <div  style="position:absolute; left:150px; top:50px; width:750px; height:323px;">
      <select name="At" onChange="showText()">
         <option value="Select">--Select--</option>
           <%
             Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
             Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:3413;DatabaseName=Project", "Product", "product");
             Statement st = con.createStatement();
             ResultSet rs = st.executeQuery(" select Activity_Type from Dep_names where Dep_name='"+depName+"'");%>
           <% while(rs.next())
                   String Activity=rs.getString(1);
                  StringTokenizer z = new StringTokenizer(Activity, ",");
                while(z.hasMoreTokens())
              {%>
                  <option><%=z.nextToken()%></option>
               <%}
             }%>
      </select></div>
    <div  style="position:absolute; left:10px; top:90px; width:750px; height:323px;">Started Time</div>
    <div  style="position:absolute; left:150px; top:90px; width:750px; height:323px;">
      <input type=text name="clockStart" id="time"   size="6" style="display:none" readonly></div>
    <div  style="position:absolute; left:10px; top:130px; width:750px; height:323px;">End Time</div>
    <div  style="position:absolute; left:150px; top:130px; width:750px; height:323px;">
      <INPUT TYPE="text" name="clockEnds" size="6"  readonly>
    </div>
    <div  style="position:absolute; left:10px; top:170px; width:750px; height:323px;">Comments</div>
    <div  style="position:absolute; left:150px; top:170px; width:750px; height:323px;">
      <textarea name="comment" cols="50" rows="6" > </textarea>
    </div><br><br><br>
    <div  style="position:absolute; left:145px; top:290px; width:750px; height:323px;">
      <input type=button TITLE="Click here to add ur record" name="add" value=" ADD "  onClick="submitAddfunction()" >
      <input type="button" TITLE="View Records" name="view" value="View"                onClick="javascript:window.open('http://10.32.244.169:8082/Activity/XlEmployeeReports.jsp');">
      <input type=button name="logout" value=" Logout "  onClick="submitLogfunction()">
    </div>
    </table>
    </center>
    </font>
    </div>
    </form>
    from the jsp page U R accessing servlet & in servlet comparision is taking place..............
    thanks in advance
    </body>
    </html>

  • Iterating through results help please

    H i have a Mysql database that contains and ID and a rating. I would like to iterate through the results of the query and display a number of stras that relates to the rating.
    JSP page code:
    <%@ page contentType="text/html; charset=utf-8" errorPage="errorPage.jsp" language="java" import="java.sql.*" import="java.util.Date.*" %>
    <%@ page language="java" import="java.sql.*" %>
    <%!
    // define variables
    String portfolio_id;
    int p_rating;
    String conn;
    %>
    <%
    Class.forName("com.mysql.jdbc.Driver");
    //get parameter to search by
    //String modelNO = request.getParameter("model_number");
    // create connection string
    //jdbc:mysql://host_name:port/dbname - MySQL Connector/J JDBC Driver.
    conn = "jdbc:mysql://server/md_portfolio?user=user&password=password";
    // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(conn);
    // query statement
    Statement SQLStatement = Conn.createStatement();
    // generate query
    String Query = "SELECT * FROM md_portfolio";
    // get result
    ResultSet SQLResult = SQLStatement.executeQuery(Query);
       while(SQLResult.next())
          portfolio_id = SQLResult.getString("portfolio_id");
           p_rating = SQLResult.getInt("p_rating");  
    out.println("ID: " + portfolio_id + "<br>");
    out.println("Rating: " + p_rating + "<br>");
    //////////i want the stars to be out put here/////////////
         /*int value = p_rating;
         int i = 0;
            while (value[i] > 5)
                out.println(" * ");
                   values[i++];
    // close connection
    SQLResult.close();
    SQLStatement.close();
    Conn.close();
    %>My final plan is change the * for an actual image of a star. Please help i should know how to do this but i cant. Thanks.
    Message was edited by:
    JamesMorgan

    Thankyou it has kinda given me what i want.
    I have chanegd the code slightly to output like this for testing purposes:
    out.println("ID: " + portfolio_id + "<br>");
    out.println("Rating: " + p_rating + "<br>");//to be reomved once completed
    while (p_rating < 5) {
                p_rating++;
                 out.println("* ");
              out.println("<br>");
              out.println("--------------------<br>");which output this
    ID: 1
    Rating: 2
    ID: 2
    Rating: 2
    ID: 3
    Rating: 2
    ID: 4
    Rating: 3
    --------------------However if you see it ouputs the number of stars left not the actual rating its self.
    Any idea. i have changed the operators of the loop i.e. <= >= etc and has no luck. if i change it to -- not ++ then the pages just continuously fills with stars.
    any ideas please.

Maybe you are looking for

  • Will Dell Venue 8 Pro work with photoshop?

    I was think about buy Dell Venue 8 Pro, but I want to use photoshop CC as sketchbook on my new-to-be portable tablet. I want use it on the go and in bed... I don't plan to use tablet as final look. Will it work? If you have used it.. How was it platf

  • How to make pdf non editable?

    Hi all, I need help of yours for solving the problem. My problem is:- 1.I have used the oledb connection for populating data in the editable form. For one Instance that form needs to be editable and for another instance or another time that form need

  • TelemetryClient.TrackException Does Not Include Method Name Or Call Stack (Windows Store App)

    We are attempting to use Application Insights (v0.12.0-build17386) for our Windows Store App.  When we use TelemetryClient.TrackException, no details appear in the azure portal.  The Failed Method is "Could Not Parse" and the Call Stack is empty. If

  • What is needed to read/use Cyrillic character sets?

    Hello all, I'm working with a friend in Russia who is sending me documents typed in Russian, but my computers here don't show anything but jibberish and any non-Cyrillic words included in the text. What do I need to do to view this on my computer? Do

  • Changing the AFP Port? or another solution?

    I have an AirPort Extreme Base Station with a hard drive attached with AFP sharing so I can access the drive over the Internet, but I want to also be able to access my OS X Server (10.5) which is behind this router. Is there any way I can change the