Invoking a method from a java class to a jsp file

Maybe i'm going through a very basic error, but as i've looked for in some forums and nothing found decided to post. So let's go to the problem.
Well, i have a form in a jsp file, it's basicaly html, but as i need some select boxes populated with data from the database i decided to create some methods in java classes. This is the point.
My method receive some attributes, like the table and colums names, the name of the select box and the HttpServletResponse object.
So after making all the database process. The method is supposed to write the result through the out.println(); object
It goes everything all right except that the method seems to be called first than the html code coz' my select boxes comes above the head in the begin of the page and was supposed to come in the middle.
part of the code:
package pacote;
import java.packages.*
public class Class{
public void metodo(HttpServletResponse response, String tableName, String column name, String selectName){
PrintWriter out = response.getWriter();
openConnection();
//After making the query stuff
//caso n�o haja nada na consulta
     if(rst == null)
     out.println("N�o h� registros.");
     else{
     out.println( "<select name='" +SelectName + "' id='" +SelectName + "' class=\"input_ob\" >");
     out.println( "<option value=''>Escolha: "+objeto+"</option>");
     //fill the select body with options; A while that sweap the resultSet and use the out object to write the results          
     getSelectBody(out,rst, selectValue);
}This method is called this way:
<tr valign="baseline">
    <td nowrap align="right">Grupo</td>
    <jsp:useBean id="m" scope="page" class="pacote.Class" />
        <td>
          <%
          try{
               m.metodo(response, "tabela","grupo","id_grupo);
          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
                    %></td>I'd like to know what i'm missing here. why the answer doesn't go in the place It's supposed to go.
any answer will be greatly apreciated

The issue is caused because you are using the response to get the writer directly.
The JSP has gotten the same writer, but has wrapped it in a JSPWriter class. That class has got a buffer.
So it writes the beginning html to the JSPWriter buffer.
You write your stuff to the response writer - gets sent to the output.
It writes more stuff to the JSPWriter buffer, then flushes that buffer - at which point all the text written into the JSP writer now gets added to the response.
You see how your code is coming out first?
Solution - instead of getting the writer from the response, pass the writer into your method (maybe instead of response if you don't use response for anything else)
public void metodo(Writer jspWriter, String tableName, String column name, String selectName){
  PrintWriter out = new PrintWriter(jspWriter);
  ...That means that you will be writing to the same writer, and the text should come out in sequence.
Cheers,
evnafets

Similar Messages

  • Unable to import a java class in a jsp file

    Hi,
    I am trying to import a java class in my jsp.
    ------------------jsp---------------
    <jsp:useBean id="form" class="com.company.portlets.searchApps.object.SearchOBJ" scope="request" />
    <jsp:setProperty name="form" property="*" />
    <input type="TEXT" name="projectID" value='<%= form.getProjectID() %>'>
    When I run the above JSP, it says that class 'com.company.portlets.searchApps.object.SearchOBJ' cannot be found.
    Why?
    My project structure looks like this:
    Project
    +Application Sources
    ++com.company.portlets.searchApps.object
    +++SearchOBJ.java
    +Web Content
    ++htdocs
    +++searchappsportlet
    ++++SearchAppsPortletShowPage.jsp
    ++WEB-INF
    +++index.jsp
    +Resources
    ++SearchApps.deploy
    Please advice...thanks!

    The way that JDeveloper organized the files was like this:
    C:\jdev1012\jdev\mywork\WksSearchApps\Project\classes\com\company\portlets\searchAPPS\object\SearchOBJ.class
    I am assuming that JDeveloper puts the file where they are suppose to be...if not, how do I change that?
    thanks,
    hussain

  • Using main class's methods from a different class in the same file

    Hi guys. Migrating from C++, hit a few snags. Hope someone can furnish a quick word of advice here.
    1. The filename is test.java, so test is the main class. This code and the topic title speak for themselves:
    class SomeClass
         public void SomeMethod()
              System.out.println(test.SomeOperation());
    public class test
         public static void main(String args[])
              SomeClass someObject = new SomeClass();
              someObject.SomeMethod();
         public static String SomeOperation()
              return "SomeThing";
    }The code works fine. What I want to know is, is there some way to use test.SomeOperation() from SomeClass without the test.?
    2. No sense opening a second topic for this, so second question: Similarly, is there a good way to refer to System.out.println without the System.out.? Like the using keyword in C++.
    Thanks.

    pfiinit wrote:
    The code works fine. What I want to know is, is there some way to use test.SomeOperation() from SomeClass without the test.?Yes you can by using a static import, but I don't recommend it. SomeOperation is a static method of the test class, and it's best to call it that way so you know exactly what your code is doing here.
    2. No sense opening a second topic for this, so second question: Similarly, is there a good way to refer to System.out.println without the System.out.? Like the using keyword in C++.Again, you could use static imports, but again, I don't recommend it. Myself, I use Eclipse and set up its template so that when I type sop it automatically spits out System.out.println(). Most decent IDE's have this capability.
    Also, you may wish to look up Java naming conventions, since if you abide by them, it will make it easier for others to understand your code.
    Much luck and welcome to this forum!

  • Calling a java class in a JSP file

    Hello,
    I have a jsp file in which I call a java class.
    I work with Tomcat 4.0.1
    If I modify the java class and then I execute my JSP, it still be the old version of my class that is executed.
    I don't understand why since if I creates a main function and I execute it, it works correctly!
    Do you know what is the problem?
    Thanks

    i also have this problem.when i modify jsp file,it didn't execute inmediately. Then i restart tomcat,but problem also exist.
    a few minute age,i execute jsp file again,it can appear the modified jsp.i don't down why
    i work tomcat 5.0 windowxp

  • Can't find the imported java class when run .jsp file

    Hi,
    I want to run a jsp web application using tomcat. I put all my .jsp files under "TOMCAT_HOME/webapps/junmin" directory, and put all .class files under "TOMCAT_HOME/webapps/junmin/WEB-INF/classes" directory. I set up TOMCAT_HOME AND JAVA_HOME already. But when I type in the address like below:
    http://db1.acad.emich.edu:8080/junmin/login.jsp
    The IE will give me error msg indicating that it can't find all the .class files which I imported them in login.jsp file.
    So, does anyone know that if I miss some configuration in order to let the .jsp file recognize the .class files. Thanks a lot!
    Sincerely, Junmin

    Ha, this might be the reason.
    Can I add sth like this:
    <Context path="/junmin" docbase="junmin" debug=0 reloadable=true>
    </Context>
    But in my local computer, I didn't add this <Context> either. It works well.
    Thanks a lot! I will ask the administrator to try this.
    And will write down the reason.
    Sincerely, Junmin

  • Invoke beanshell methods from java

    Hello
    I'm learning beanshell and using it to write scripts that are ran in JDK 6.
    My question is how to invok beanshell methods from java source codes.
    My codes is:
    import javax.script.*;
    public class InvokeFunctions {
    public static void main (String[] args)throws ScriptException, NoSuchMethodException
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine bshEngine = sem.getEngineByName("beanshell");
    String script = "public void sayHello()"+"{print (\"sayHello() is a method in bsh script\");}";
    bshEngine.eval(script);
    Invocable inbshEngine = (Invocable)bshEngine;
    inbshEngine.invokeFunction("sayHello");
    I defined a method "sayHello()" using beanshell, but i just can't invoke it in Java.
    I got an error msg said:
    Exception in thread "main" java.lang.IllegalAccessError: tried to access method bsh.NameSpace.getThis(Lbsh/Interpreter;)Lbsh/This; from class bsh.engine.BshScriptEngine
    Any one has any idea about it?
    Thanks

    Look at the Javadoc documentation of IllegalAccessError. It says:
    Thrown if an application attempts to access or modify a field, or to call a method that it does not have access to.
    Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
    Maybe recompiling all your sources (make sure you delete all existing *.class files) will help?

  • Problems invoking a method from a web service

    Am using netbeans 6.1 and my problem is when i invoke a method from a web service that has a custom class as a return type.
    When I debug the client that consumes my web service, It get Stack in this line:
    com.webservice.WebServiceInfoBean result = port.getWebServiceInfo(nameSpace, serviceName, portName, wsdlURL);
    i don't get any error on the console.
        static public void function1() {
            try { // Call Web Service Operation
                com.webservice.WebServiceMonitorService service = new com.webservice.WebServiceMonitorService();
                com.webservice.WebServiceMonitor port = service.getWebServiceMonitorPort();
                // TODO initialize WS operation arguments here
                java.lang.String nameSpace = "NameSpaceHere";
                java.lang.String serviceName = "WebServicePrueba";
                java.lang.String portName = "Soap";
                java.lang.String wsdlURL = "http://localhost/Prueba/WebServicePrueba.asmx?wsdl";
                // TODO process result here
                com.webservice.WebServiceInfoBean result = port.getWebServiceInfo(nameSpace, serviceName, portName, wsdlURL); // <--- here it stack
                System.out.println("getWebServiceInfo");
                Iterator i = result.getMethods().iterator();
                while (i.hasNext()) {
                    MethodBean method = (MethodBean) i.next();
                    System.out.print("Nombre: " + method.getname());
                    System.out.print(" Returns: " + method.getreturnType());
                    Iterator j = method.getparameters().iterator();
                    while (j.hasNext()) {
                        ParameterBean parameter = (ParameterBean) j.next();
                        System.out.print(" ParameterName: " + parameter.getname());
                        System.out.print(" ParameterType: " + parameter.gettype());
                    System.out.print("\n");
                    System.out.print(method.getfirma());
                    System.out.print("\n");
                    System.out.print("\n");
            } catch (Exception ex) {
                ex.printStackTrace();
        }Web Service side
         * Web service operation
        @WebMethod(operationName = "getWebServiceInfo")
        public WebServiceInfoBean getWebServiceInfo(@WebParam(name = "nameSpace")
        String nameSpace, @WebParam(name = "portName")
        String portName, @WebParam(name = "serviceName")
        String serviceName, @WebParam(name = "wsdlURL")
        String wsdlURL) throws Throwable {
            //TODO write your implementation code here:
            webservicemonitor instance = new webservicemonitor();
            return instance.getWebServiceInfo(nameSpace, serviceName, portName, wsdlURL);
        }I have tested my internal code from the web service side and everything works fine. The problem occurs when i invoke it from a client side. probably I did not made the right serialization form my class WebServiceInfoBean? or am missing something. here it is:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package com.beans;
    import java.util.ArrayList;
    * @author Tequila_Burp
    public class WebServiceInfoBean implements java.io.Serializable {
         * Holds value of property wsdlURL.
        private String wsdlURL;
         * Getter for property wsdlURL.
         * @return Value of property wsdlURL.
        public String getwsdlURL() {
            return this.wsdlURL;
         * Setter for property wsdlURL.
         * @param wsdlURL New value of property wsdlURL.
        public void setwsdlURL(String wsdlURL) {
            this.wsdlURL = wsdlURL;
         * Holds value of property namespace.
        private String namespace;
         * Getter for property namespace.
         * @return Value of property namespace.
        public String getnamespace() {
            return this.namespace;
         * Setter for property namespace.
         * @param namespace New value of property namespace.
        public void setnamespace(String namespace) {
            this.namespace = namespace;
         * Holds value of property serviceName.
        private String serviceName;
         * Getter for property serviceName.
         * @return Value of property serviceName.
        public String getserviceName() {
            return this.serviceName;
         * Setter for property serviceName.
         * @param serviceName New value of property serviceName.
        public void setserviceName(String serviceName) {
            this.serviceName = serviceName;
         * Holds value of property wsdlURL.
        private String portName;
         * Getter for property wsdlURL.
         * @return Value of property wsdlURL.
        public String getportName() {
            return this.portName;
         * Setter for property wsdlURL.
         * @param wsdlURL New value of property wsdlURL.
        public void setportName(String portName) {
            this.portName = portName;
         * Holds value of property methods.
        private ArrayList methods = new ArrayList();
         * Getter for property methods.
         * @return Value of property methods.
        public ArrayList getmethods() {
            return this.methods;
         * Setter for property methods.
         * @param methods New value of property methods.
        public void setmethods(ArrayList methods) {
            this.methods = methods;
        public MethodBean getMethod(int i) {
            return (MethodBean)methods.get(i);
    }by the way, everything has been worked on the same PC.

    Hi Paul,
    This sound familiar, but I cannot at the moment locate a reference to
    the issue. I would encourage you to seek the help of our super support
    team [1].
    Regards,
    Bruce
    [1]
    http://support.bea.com
    [email protected]
    Paul Merrigan wrote:
    >
    I'm trying to invoke a secure 8.1 web service from a 6.1 client application and keep getting rejected with the following message:
    Security Violation: User: '<anonymous>' has insufficient permission to access EJB:
    In the 6.1 client, I've established a WebServiceProxy and set the userName and password to the proper values, but I can't seem to get past the security.
    If there something special I need to do on either the 8.1 securing side or on the 6.1 accessing side to make this work?
    Any help would be GREATLY appreciated.

  • Is it possible to invoke JEB method from thread?

    Hello everybody!
    I have problem creating EJB from the thread. Here is the part of code below:
    public void email() throws Exception {
    class MailThread implements Runnable {
    public MailThread() {
    public void run() {
    try {
    String jndiName "java:comp/env/ejb/PROG/Mail";
    IMailHome mailHome;
    IMail mail;
    InitialContext context = new InitialContext();
    Object objref = context.lookup(jndiName);
    mailHome = (IMailHome) PortableRemoteObject.narrow(objref, IMailHome.class);
    // Exception here:
    // java.rmi.RemoteException: Exception Substitute; nested exception is:
    // java.lang.NullPointerException mail = mailHome.create();
    // business metods
    // mail.method1();
    } catch (Exception e) {
    System.out.println("Exception:" + e);
    MailThread mt = new MailThread();
    Thread thread = new Thread(mt);
    thread.start();
    Exception:
    java.rmi.RemoteException: Exception Substitute; nested exception is:
    java.lang.NullPointerException
    I am not able to create EJB instance from the thread. The same code works well in servlet. Am I doing something wrong?
    May be there are some different approaches to implement some operations asynchronously at EJB level do not using JMS and MDB? J2EE specification prohibits to use threads inside EJB so the only way I see is to create different thread on servlet side and invoke EJB methods from it. But it seems that this doesn't work too. Could anyone help me?
    Thanks in advance,
    Vadim Lotarev

    If the passcode will not work, the only alternative is to restore the phone as new. You cannot change the passcode from the lock screen.

  • How can I call a pop up window from a java class ?

    Hi,
    I am developing a web app. I would like to call a windoz pop up from a java class.
    How can i do that ?
    Thanks

    user504072 wrote:
    It was possible to do it in ASP .NET even from the server side with the method Page.ClientScript. What do you think what Page.ClientScript stands for?
    I's an encapsulation for the JavaScript code required and hides the separation between frontend and backend. There was a reason why so many developers stick to the MVC-pattern wich ist violated here.
    I did not know it is not possible to do the same thing in Java.I'ts not a task of the backend to layout the user interaction GUI.
    bye
    TPD

  • How to call a Java class from another java class ??

    Hi ..... can somebody plz tell me
    How to call a Java Class from another Java Class assuming both in the same Package??
    I want to call the entire Java Class  (not any specific method only........I want all the functionalities of that class)
    Please provide me some slotuions!!
    Waiting for some fast replies!!
    Regards
    Smita Mohanty

    Hi Smita,
    you just need to create an object of that class,thats it. Then you will be able to execute each and every method.
    e.g.
    you have developed A.java and B.java, both are in same package.
    in implementaion of B.java
    class B
                A obj = new A();
                 //to access A's methods
                 A.method();
                // to access A's variable
                //either
               A.variable= value.
               //or
               A.setvariable() or A.getvariable()

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • How to pass a "object" as a prameter from one java class to another java

    hi experts, I want to know "How to pass and get object as a parameter from one java class to another java class". I tried follwoing code just check it and give suggetions..
    import Budget.src.qrybean;
    public class ConfirmBillPDF extends HttpServlet
    qrybean db = new qrybean();
    SimplePDFTable pdfTable = new SimplePDFTable();
    pdfTable.simplePDFTableShow("2010","2011","1","2","1","131","102");
    }Here i want to pass db with simplePDFTableShow method. simplePDFTableShow is in another java class. So how can i do this.
    And also i want to know, how this obj will get.
    please help me.
    Edited by: andy_surya on Jul 14, 2010 7:51 AM

    Hi andy_surya
    what is this i am not understand
    pdfTable.simplePDFTableShow("2010","2011","1","2","1","131","102");but i am try to solve your problem try this
    qrybean db = new qrybean();
    SimplePDFTable pdfTable = new SimplePDFTable();
    pdfTable.simplePDFTableShow(db);and access like this in SimplePDFtable class update your method
    simplePDFTable(qrybean tempDB)
    // write your code
    }

  • Call Bean from normal java class

    Dear Friends,
    Is it ok to call an entity bean or session bean frm normal Java class.
    (Java class is in the same application as the beans).
    Is there a special way to lookup the beans from normal java classes.
    Thanking You,
    Chamal.

    it is ok and very commonly done.
    Note that the simple java program must be running in the same local network. You cannot have the java program and EJBs distributed over internet. (I m not certain of it, but mostly I shoudl be correct. If you have the resources, try it out and let me know)
    In most of the cases, EJBs are called by
    1. A servlet
    2. Another EJB
    3. a simple java program.
    In the first 2 cases, you can go for Local Interfaces (more so in the second case than the first). The reason being that the the client and server will be in the same JVM (typically the Application server). Thus, in the first case, if the Web container and the ejb container are in the same app server, EJBs can be local.
    However, in the third case, it is unlikey that you will have the client runnng and the same jvm as the server, because the app server has its own jvm.
    sample code (this method is being called from the main method of a simple java program. it is self explanatory):
    public  void processRequestForSessionBean()
             System.out.println("REQUEST RECEIVED");
             try
                   Hashtable nameHashtable = new Hashtable();
                   nameHashtable.put( Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory" );
                   nameHashtable.put( Context.PROVIDER_URL, "t3://localhost:7001" );
                   InitialContext context = new InitialContext(nameHashtable);
                   System.out.println("created initial context");
                   Object lookupObject = context.lookup("CustomerBean");
                   System.out.println("Got the lookup object");
                   CustomerDataHome home = (CustomerDataHome) PortableRemoteObject.narrow(lookupObject,
                             Class.forName("com.shiv.business.CustomerDataHome"));
                   System.out.println("Home interface");
                   customerData = home.create();
                   System.out.println("Remote Interface");
                   addDataToSB(customerData);
                   ArrayList namesList = customerData.getNames();
                   System.out.println(namesList.toString());
                   //customerData.remove();             
              catch (Exception exception)
                   System.out.println("FATAL ERRORS");
                   exception.printStackTrace();
              }

  • Calling another java class from a java class

    Hi Friends,
    I have a class tht works in 2 modes,depending upon which mode i am passing (gui or text) on the command line eg:
    java myclass [mode]
    I want to call this command from another java class,and i wrote this code:
    try
             Process theProcess =
                Runtime.getRuntime().exec("java myclass  "+args[0]);
          catch(IOException e)
             System.err.println("Error on exec() method");
             e.printStackTrace();
          }When i pass "gui" it works fine,but when i pass"text", the class completes and nothing shows up on the command prompt window,so can please somebody tell me how to make this work.
    Thanks

    As aniseed just pointed out, you could do something like this:
    import javax.swing.*;
    class Test extends JFrame {
         public Test(String title) {
              this.setTitle(title);
              this.pack();
              this.setSize(300, 300);
              this.setLocationRelativeTo(null);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
         public static void main(String[] argv) { new Test(argv[0]).setVisible(true); }
    public class Test2 {
         public static void main(String[] argv) {
              Test.main(argv);
    }Run it by executing this command:
    java Test2 "Title of Frame"See if that's not what you're looking for ...

  • How to execute a jsp instruction from a java class?

    How to execute a jsp instruction from a java class?
    Any help please.
    Thank's

    I'll detail my problem:
    Supposing that I have a jsp file called: start.jsp
    In the start.jsp I instanciated an object called global from the class Global ( for example ).
    Then, I called a custom taglib:
    <ix:mytag/>
    In the suitable tld file: the mytag is defined:
    <tag>
    <tag class>Tag1<.....
    The java file Tag1 has method:
    doStartTag(){
    // here is the problem
    global.doSomeFunctions();
    Okay, the problem is that the object gobal is not defined in the class Tag1. what to do?
    I think that I have to pass the object global as a parameter to the class Tag1. How to do that?
    Actually, the problem was to insert the follwoing in the doStartTag method:
    doStartTag(){
    pageContext.getOut().print("<%= hello world %>");
    The output is <%= hello world %> not hello world.
    Okay, the new problem is how to pass an object as a parameter to a class called from a tld file.
    Any help please.
    Thank's too much

Maybe you are looking for

  • No shared memory

    hi in BW PRD while executing a report we are getting an error error  message  " AN EXCEPTION WITH TYPE CX_SY_EXPORT_NO_SHARED_MEMORY  OCCURED, NO  SPACE  LEFT IN SHARED MEMORY" Edited by: sarat chandra bomma reddy on Apr 1, 2008 8:45 AM

  • Excise invoice creation problem

    Dear All, In the SAP Standard settings it is made in such away that during J1IS (creating excise invoice for return delivery) entry passed is CENVAT Input - Cr CENVAT Suspense - Dr. Now I have changed the settings from CENVAT Suspense to CENVAT Clear

  • Taking snapshot of oracle tables to sql server using transactional replication is taking a long time

    Hi All, I am trying to replicate around 200 oracle tables onto sql server using transaction replication and it taking a long time i.e the initial snapshot is taking more than 24 hrs and it still going on. Is there any way to replicate those these tab

  • Imported Excel Sheet Rows won't UNHIDE

    Imported basic checkbook type spreadsheet from Excel into Numbers. In original, left column has dates, but not every row -- some dates had multiple entries so several cells in column A were blank. When I imported all seemed to go okay... but then I n

  • Legacy Data Extraction; iWay Adapters;

    Back in September at Tech Ed Vegas, I attended an XI presentation during which it was stated that it is not a good idea to use XI for first-time data load into SAP. Does everyone agree with this statement?  Is it better to use the LSMW? What about us