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
Related videos on Youtube
Comments
-
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 about 11 yearsim 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 about 11 yearsis it ok to create a instance of
showString()
in the JSP file? the java code should be seperated from jsp code right? -
orique about 11 yearsYou 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 about 11 yearsThanks 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 about 11 yearsThe<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 about 11 yearsThanks for the explanation :)
-
MayurB about 11 yearsprofesores.elo.utfsm.cl/~agv/elo330/2s03/projects/Tomcat/doc/… This link will help you to understand more