How to call a java method inside a .jsp page using JSTL

13,838

You can try <jsp:usebean> to call the method of the java bean.. Check the example below

package my;
public class MyBean {

  private String name=new String();

  public String getName() {
  return name;
  }
  public void setName(String name) {
  this.name = name;
  }
  } 

To call the setname method in jsp

<jsp:useBean id="mybean" class="my.MyBean" scope="session" >
<jsp:setProperty name="mybean" property="name" value=" Hello world" />
</jsp:useBean>

To call the getname method in jsp

<jsp:getProperty name="mybean" property="name" />

The main requirement is your method name should be start from get and set appended by property name

Share:
13,838

Related videos on Youtube

Chamara Keragala
Author by

Chamara Keragala

Sysadmin/Developer

Updated on July 11, 2022

Comments

  • Chamara Keragala
    Chamara Keragala almost 2 years

    Below is my java code:

    package employees;  
    public class showString{    
        public String setSection(){
            String myStr = "Hello";
            return myStr ;
        }
    };
    

    How do i call setSection() method in my jsp page using JSTL? I've tried several methods but none of them worked.

    I've already checked this page How to avoid Java Code in JSP-Files? but don't understand how to call my method on the jsp file

    This will be a great help. Thanks

  • Chamara Keragala
    Chamara Keragala about 11 years
    im sorry.. I have mistakenly added showString() as method instead of setString() in the description. i've tried to call setSection method but it didnt work
  • Chamara Keragala
    Chamara Keragala about 11 years
    is it ok to create a instance of showString() in the JSP file? the java code should be seperated from jsp code right?
  • orique
    orique about 11 years
    You need to create an instance of showString somewhere and make it available to the JSP in some way. If you use Struts2 you could create the instance anywhere in your Java code and then expose it to the JSP via an Action class field.
  • Chamara Keragala
    Chamara Keragala about 11 years
    Thanks for the reply. Can you please explain what each line of code means on To call the setname method in jsp and To call the getname method in jsp? will be a great help for me as well as others :)
  • MayurB
    MayurB about 11 years
    The<jsp:usebean> is used to locate or instantiates a java bean component The <jsp:useBean> element contains a <jsp:setProperty> element that is used to sets property values in the Bean The <jsp:getProperty> element that is used to get the value of property.
  • Chamara Keragala
    Chamara Keragala about 11 years
    Thanks for the explanation :)
  • MayurB
    MayurB about 11 years