Chamara Keragala
Chamara Keragala

Reputation: 5777

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

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

Upvotes: 3

Views: 14392

Answers (2)

MayurB
MayurB

Reputation: 3649

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

Upvotes: 7

orique
orique

Reputation: 1303

showString is not a method but a class. You cannot "call" classes. If you want to call setSection method, then you can try ${objectYouCreated.setSection()}

Also note you code does not follow case conventions in Java (The name of the class should start with an uppercase letter), and I'm not 100% sure if that semicolon at the end is valid Java syntax but looks really strange to me.

Upvotes: 0

Related Questions