How to call a function from Java to JSP

Hello,
I have a question about using tags.
I have a java file,which has a function. Now I want to call this function into my JSP page.
I'm using JSP 1.2 and TOMCAT 4.1 with Java2 SDK.
I search through the web and find a method to do this.Bu it requires JSP 2.0
But I try that in my machine(using JSP 1.2).It gives an error:
Did you know what is the error? Or is there any method to call a function into my JSP page?
Please, help me to solve this.
Here are my codes(part of them)
UserPassword.java file
package data;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UserPassword
     public static String verify(String username,String password){
          // some codes
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
     "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name>simple</short-name>
  <uri>http://jakarta.apache.org/tomcat/HRM/WEB-INF/lib</uri>
  <description>
     A  tab library for the login
  </description>
<function>
        <description>verify username and password</description>
        <name>verify</name>
        <function-class>data.UserPassword</function-class>
        <function-signature>String verify(java.lang.String,java.lang.String)
        </function-signature>
</function>
</taglib>I put this file into the webapps/HRM/WEB-INF/lib folder
Here is my JSP file.
<%@ page language="java" %>
<%@ page import="data.UserPassword" %>
<%@ page session="true" %>
<%@ taglib prefix="login" uri="/WEB-INF/lib/LoginVerify.tld" %>
<jsp:useBean id="useraccount" class="data.UserPassword"/>
<jsp:setProperty name="useraccount" property="*"/>
<%
String status = UserPassword.verify(String username,String password);
String nextPage = "MainForm.jsp";
if(status.equals("InvalidU")) nextPage ="InvalidUserName.jsp";
if(status.equals("InvalidP")) nextPage ="InvalidPassword.jsp";
if(status.equals("main")) nextPage ="MainForm.jsp";
%>
<jsp:forward page="<%=nextPage%>"/>
Here is the error:
org.apache.jasper.JasperException: XML parsing error on file /WEB-INF/lib/LoginVerify.tld: (line 18, col -1): Element "taglib" does not allow "function" here.
     at org.apache.jasper.xmlparser.ParserUtils.parseXMLDocument(ParserUtils.java:189)
     at org.apache.jasper.compiler.TagLibraryInfoImpl.parseTLD(TagLibraryInfoImpl.java:247)
     at org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:183)
     at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:354)
     at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:381)Please, help me to solve this trouble.
Thanks.

Yes. As serlank showed, you can just call the function easily in scriptlet tags
However the whole point of a tag library is to avoid the use of scriptlets.
Seeing as you can't use functions, is just to do it as a standard tag.
ie in your jsp
<login:verify name="<%= userName %>" password = "<%= password %>" resultVar = "status"/>
<c:choose>
  <c:when test="${status == 'InvalidU'}">
    <c:set var="nextPage" value="InvalidUserName.jsp"/>
  </c:when>
  <c:when test="${status == 'InvalidP'}">
    <c:set var="nextPage" value="InvalidPassword.jsp"/>
  </c:when>
</c:choose>In your case, this tag in the tld would possibly look something like this.
You would then have to write a tag handler class that would call the function you want.
<tag>
  <name>verify</name>
  <tagclass>com.tags.login.Verify</tagclass>
  <teiclass>com.tags.login.VerifyTEI</teiclass>  (if required)
  <bodycontent>JSP</bodycontent>
// name attribute 
<attribute>
      <name>name</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
// password attribute
    <attribute>
      <name>password</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
// result variable to return a response from the tag.
  <variable>
    <name-from-attribute >resultVar</name-from-attribute >
    <variable-class>java.lang.String</variable-class>
    <declare>true</declare>
    <scope>AT_END</scope>
  </variable>
</tag>Hope this helps some, and doesn't confuse too much :-)
Cheers,
evnafets

Similar Messages

  • How to call oracle function from ejb3

    i'm trying to call an oracle query-function from ejb3.
    The oracle function:
    create or replace FUNCTION getSecThreadCount(secId in NUMBER,avai in NUMBER)
    RETURN SYS_REFCURSOR is cur SYS_REFCURSOR;
    m_sql VARCHAR2(250);
    BEGIN
    m_sql:='select count(thrId) from thread where secId='|| secid||'
    and thrAvai='|| avai;
    open cur for m_sql;
    return cur;
    END;
    I'v tried several ways to call it,but all failed:
    1. the calling code:
    public Object getSectionThreadCount(int secId,int avai){
              Query query=manager.createNativeQuery("{call getSecThreadCount(?,?) }");     
              query.setParameter(1, secId);
              query.setParameter(2, avai);
              return query.getSingleResult();
    but i got the exception:
    Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query; nested exception is: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    Caused by: java.sql.SQLException: ORA-06550: row 1, col 7:
    PLS-00221: 'GETSECTHREADCOUNT' not procedure or not defined
    ORA-06550: row 1, col 7:
    PL/SQL: Statement ignored
    2. the calling code:
    @SqlResultSetMapping(name = "getSecThreadCount_Mapping")
    @NamedNativeQuery(name = "getSecThreadCount",
    query = "{?=call getSecThreadCount(:secId,:avai)}",
    resultSetMapping = "getSecThreadCount_Mapping",
    hints = {@QueryHint(name = "org.hibernate.callable", value = "true"),
              @QueryHint(name = "org.hibernate.readOnly", value = "true")})
    public Object getSectionThreadCount(int secId,int avai){
              Query query=manager.createNamedQuery("getSecThreadCount");     
              query.setParameter("secId", secId);
              query.setParameter("avai", avai);
              return query.getSingleResult();
    but i run into the exception:
    Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query; nested exception is: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    Caused by: java.sql.SQLException: lost in index IN or OUT parameter:: 3
    By the way, i have successfully called the function from hibernate. And i use oracle 11g, JBoss5 RC1.
    Could anyone tell me how to call the function from EJB3?
    Thanks.

    Here's a working model:
    package.procedure: (created in example schema scott)
    CREATE OR REPLACE package  body data_pkg as
      type c_refcursor is ref cursor;
      -- function that return all emps of a certain dept
      function getEmployees ( p_deptId in number
      return c_refcursor
      is
        l_refcursor c_refcursor;
      begin
         open l_refcursor
        for
              select e.empno as emp_id
              ,        e.ename as emp_name
              ,        e.job   as emp_job
              ,        e.hiredate as emp_hiredate
              from   emp e
              where  e.DEPTNO = p_deptId;
        return l_refcursor;
      end getEmployees;
    end data_pkg;
    /entity class:
    package net.app.entity;
    import java.io.Serializable;
    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedNativeQuery;
    import javax.persistence.QueryHint;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    @SuppressWarnings("serial")
    @Entity
    @Table (name="emp")
    @SequenceGenerator(name = "EmployeeSequence", sequenceName = "emp_seq")
    @NamedNativeQuery( name = "getEmpsByDeptId"
                   , query = "{ ? = call data_pkg.getEmployees(?)}"
                   , resultClass = Employee.class
                   , hints = { @QueryHint(name = "org.hibernate.callable", value = "true")
                          , @QueryHint(name = "org.hibernate.readOnly", value = "true")
    public class Employee implements Serializable
        @Id
        @Column(name="emp_id")
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EmployeeSequence")
        private int id;
        @Column(name="emp_name")
        private String name;
        @Column(name="emp_job")
        private String job;
        @Column(name="emp_hiredate")
        private Date hiredate;
        // constructor
        public Employee (){}
        // getters and setters
        public int getId()
         return id;
    etc...session bean:
    package net.app.entity;
    import java.util.ArrayList;
    import java.util.List;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    import net.app.entity.Employee;
    import net.app.iface.ScottAdmin;
    @Stateless
    public class ScottAdminImpl implements ScottAdmin
        @PersistenceContext
        private EntityManager entityManager;
        @SuppressWarnings("unchecked")
        public List<Employee> getEmployeesByDeptId(int deptId)
         ArrayList<Employee> empList;
         try
             Query query = entityManager.createNamedQuery("getEmpsByDeptId");
             query.setParameter(1, deptId);
             empList = (ArrayList<Employee>) query.getResultList();
             return empList;
         catch (Exception e)
             e.printStackTrace(System.out);
             return null;
    }client:
    package net.app.client;
    import java.util.List;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import net.app.entity.Employee;
    import net.app.iface.ScottAdmin;
    public class ScottClient
        public static void main(String[] args)
         try
             // create local interface
             InitialContext ctx = new InitialContext();
             ScottAdmin adminInterface = (ScottAdmin) ctx.lookup("ScottAdminImpl/remote");
             // select employees by deptno
             int deptno = 20;
             List<Employee> empList = adminInterface.getEmployeesByDeptId(deptno);
             // output
             System.out.println("Listing employees:");
             for (Employee emp : empList)
              System.out.println(emp.getId() + ": " + emp.getName() + ", " + emp.getJob() + ", " + emp.getHiredate());
         catch (NamingException e)
             e.printStackTrace(System.out);
    }Basically you just ignore the refcursor outbound parameter.
    This is a stored function, have yet to try outbound refcursor parameters in stored procedures...
    Edited by: _Locutus on Apr 2, 2009 2:37 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to call javascript function from PL/SQL procedure

    Can anybody advice me how to call javascript function from PL/SQL procedure in APEX?

    Hi,
    I have a requirement to call Javascript function inside a After Submit Process.
    clear requirement below:
    1. User selects set of check boxes [ say user want to save 10 files and ticks 10 checkboxes]
    2. user clicks on "save files" button
    3. Inside a After submit process, in a loop, i want to call a javascript function for each of the file user want to save with the filename as a parameter.
    Hope this clarify U.
    Krishna.

  • How to call gnuplot command from java

    Hi there,
    In our course, we are required to develop an GUI for gnuplot. In case you don't know about gnuplot, it's a plotting program and has lots of command. We want to use java and swing, but now we don't know how to call gnuplot command from java, or how to execute a shell command(script) from java.
    By the way, since we need read in files with several columns of data and allow user to select a column, we want to use JTable. Is that reasonable?
    Thanks a lot for any suggestions!
    Jack

    Hi, there:
    Will using JTable add much overhead? I may have to use several JTables and switch among them. I can add scroll bar to or edit JTables, right?
    BTW, do you have experience about gnuplot? Can I find the command tree of gnuplot somewhere? Or do you know a better place to post question about gnuplot? unix/linux group, maybe.
    Thanks,
    Jack
    P.S. Would you guys answer my question after I use up my duke dollars? :- )

  • How to call a function from asp

    Hi!, I'd like to know how to call a function from an asp page. I've written:
    set rs = server.createobject("Adodb.recordset")
    rs.open "call dbo.sf_Obt_Des_Producto ('0000161')",Conn
    if err.description <> "" then
    response.write ("No se pudo! :(")
    else
    response.write ("rs: " & rs(0))
    end if
    rs.close
    set rs = nothing
    but there is an error:
    ORA-06576: not a valid function or procedure name
    Please is very urgent!!!
    Thanks.
    Angie.

    You need to use the syntax "{call <procedure_name>}".
    The {call } syntax tells the OLE DB provider that it needs to translate the call into whatever the database's procedure calling syntax is. This means that even though different databases have different syntax for calling stored procedures, your OLE DB code can be run against any of them without changing.
    Justin

  • Call DLL function from JAVA

    HI!
    What's the best way (and simple) to call DLL function from JAVA.
    DLL function (developed in C) has two input parameters (string) and return an integer.
    Could you help with an example?
    Thanks a lot.

    Do a google search for 'JNI tutorial' and it will turn up hundreds of examples.

  • Calling c function from java!!

    hi all,
    I want to call c function from java . I have gone through the link http://java.sun.com/docs/books/tutorial/native1.1/stepbystep/index.html for JNI.
    According to this link we need to write the native method implementation in such a way that the method signature should exactly match the method signature created in the header file.
    My problem is that i have a c application which i cannot modify in any ways i.e., i cannot change its code. But i want to call its function from my java code.
    Please suggest me appropriate solution for this. Please let me know whether it can be done using JNI or is there any other method for this.
    thanks

    This link is amazing since those sources were wrote in 1998 and I started to develop JNative in 2004. I did not found them when I started.
    Since JNative can deal with callbacks and probably COM in a near future, I expect to see it living to Dolphin at least.
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • ORA-00911: invalid character - Calling a function from Java..

    Hi to all.. I have an issue when calling an oracle function from Java..
    This is my Java code:
    final StringBuffer strSql = new StringBuffer();
    strSql.append("SELECT GET_TBL('II_2_1_6_5') AS TABLA FROM DUAL;");
    st = conexion.createStatement();
    rs = st.executeQuery(strSql.toString());
    and in the executeQuery a SQLException is throwed:
    java.sql.SQLException: ORA-00911: invalid character
    I paste the query in TOAD and it works.. :S
    anybody knows how can I solve this?

    Remove the Semicolon after Dual.
    strSql.append("SELECT GET_TBL('II_2_1_6_5') AS TABLA FROM DUAL");
    Sushant

  • Calling OCI functions from Java

    Is it possible to call OCI's API functions from Java and create a Lightweight Session ?
    Please help me out.

    I too would like to know how this can be accomplished. I have
    seen several posts that claim it is possible with Oracle91.

  • How to call external files from java?

    How to call external files in java. For example how to call a *.pdf file to open in its default editor(say Acrobat), or a *.html file to open in the default browser or a *.txt file in a notepad etc..,
    In my program i have *.chm (Compiled Windows HTML Help) help file. how to open it in its default editor it?

    Jayarathina_Madharasan wrote:
    no one answered my questionHi what wrong did i do...basically insulted all the volunteers here who took the time to consider your question and try to offer you help. Other than that, you did nothing wrong.
    From JavaRanch :
    And even if an answer doesn't solve your problem, even if it should totally miss the point - the best thing to do to motivate others to continue trying to help you is showing respect and gratitude for the investment of time that was put into dealing with your issue.
    Edited by: Encephalopathic on Apr 14, 2008 10:01 AM

  • How to Call C++ Method from Java

    I need to call C++ method from Java.
    I have gone through the JNI tuorial , but was not able to pin point things.
    I read that :
    You have to write JNI c functions which then call your C++ member functions.You need to write a JNI function which will call new on your C++ class.
    Now i have java class :
    Java Code JavaClass.java ---->
    class JavaClass{
    public native void nativeMethod();
        static
            System.loadLibrary("NativeCppCode");
         private void callCppMethod()
              //call C++ method
                    JavaClass jvc = new JavaClass();
                    jvc.nativeMethod()
    }Cpp Code:
    NativeCppCode.h---->
    class NativeCppCode
    public:
        getValue();
        setValue();
    private:
       int a;
    JNIEXPORT void JNICALL Java_JavaClass_nativeMethod(JNIEnv *env
                   ,jobject obj);NativeCppCode.C---->
    NativeCppCode::getValue()
       return a;
    NativeCppCode::setValue()
       a = 1;
    JNIEXPORT void JNICALL Java_JavaClass_nativeMethod(JNIEnv *env
                   ,jobject obj)
    NativeCppCode* nativeInstabce = new NativeCppCode();
    NativeCppCode.setValue();
    }Is this the correct way to do it.
    Any suggestion would be a great help to me

    tryit wrote:
    I need to call C++ method from Java.Not possible.
    JNI uses C methods.
    Is this the correct way to do it.Same way you would do it in any C/C++ method (not java)
           MyClass* p = ....
           p->doit();
    Common idiom for the pointer in the above is to pass it back and forth to your java code as a java long. You cast it it and from your class pointer. Provide an explicit java method to free it when done. Besides providing the explicit method also implement a finalizer to free it as well (however that is a fail safe and should not be relied upon.)

  • ADF: Can i call javascript function from java clsss method in ADF?

    Hi,
    I want to call javascript function in Java class method, is it possible in ADF? , if yes then how?
    or I need to use Java 6 feature directely?
    Regards,
    Deepak

    private void writeJavaScriptToClient(String script)
    FacesContext fctx = FacesContext.getCurrentInstance();
    ExtendedRenderKitService erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
    erks.addScript(fctx, script);
    }usage
    StringBuilder script = new StringBuilder();
    script.append( "var popup = AdfPage.PAGE.findComponentByAbsoluteId('p1');");
    script.append("if(popup != null){"); script.append("popup.show();"); script.append("}");
    writeJavaScriptToClient(script.toString());Timo

  • How to Call .XDO file From Java Program

    Hi,
    I have developed a report in using BI Publisher version 10.1.3.
    I created the report and it only created XDO files. If I want to call XDO file from Java program how I can do that.
    What are the APIs available to do that.
    Thanks
    -Ashutosh

    Hi,
    the JavaAPI didn't work with the xdo-Files. But you can create a proxy stub for the Web Service API of BI Publisher which uses the xdo's in the repository.
    regards
    Rainer

  • How to call  F4 functionality from R/3 to SRM

    hi,
    I need to call F4 functionality from R/3 field  "AFDAT" , to SRM field "INVDATE" .
    please suggest me  regarding this.The field is INVOICE DATE.
    Thanks&Reagrds,
    Basava Sridhar.

    Go to IMG > Define Backend Systems - and in entry for backend logical system add entry on the end of line in the second "RFC-Destination" field.
    Notice that RFC user in that conenction must not have SAP_ALL authorizations but per note 642202
    TIA
    Gordan

  • How to call c++ code from java

    i have a third party dll written in c++. I want to call its methods in java. I searched web and found that I have to use JNI for this. I have seen examples on web writing c++ code and then using it from java through JNI, but can anybody please point to me the example where i have a predefined library or dll in c++ and i have to call it in java. I think that I may have to declare methods in library as native in java and then write a wrapper implementation (dll) in c++ which actually calls the library or dll functions. But, then how will I call methods of dll from my wrapper code.
    Any examples, please point
    Regards,
    Farooq

    There's a JNI forum here that may be a better place for this question; though given the general nature of the question, I suspect that they'll refer you to a tutorial. good luck.

Maybe you are looking for

  • How to reassign a budget type which has been assigned

    hi, i wanted to know how to reassign the budget type assigned for psoting period ending 30.09.2008. i want to change the key figure assigned to the budget type so i am trying to delete the budget type for that purpose. i cannot delete key figure for

  • Ipod 5th Gen not recognised on any computer - will charge via usb

    Hi, Does anyone have a fix for my ipod which is not recognised by any computer. Have tried the software reset, putting into disk mode, but no computer will see it as a device. The ipod will however charge by the usb. I have tried another 5th Gen on t

  • Need accessories for Zen Micro-can anyone he

    Hello Everyone, I purchased ny zen micro a couple of months ago and already i am keen to get accessories. Does anyone know where to get accessories (from a proper shop like John Lewis etc.). If you do please send a reply as soon as possible Thank you

  • Outlook to solution manager 3.2

    we have solution manager 3.2 installed  i want to use service desk from outlook 1) outlook mail should create support desk ticket ticket raised from outlook should create in solution manager is it posisble i heard few companies done this kind of conf

  • How do I print a booklet from a non-duplex printer in InDesign 5?

    I want to print a 16-page, 2-up Saddle Stitch booklet, so I need to print odd spreads and then flip them over and print even spreads. I can't select which spreads to print in the print dialogue box though.