Search code examples
javajspjakarta-ee

create java function in a jsp file and call it from another jsp file


We generally create methods in a java class, import them into a jsp file and call those methods in our jsp files.

But we are working in a client environment, we do not have access to create or modify .java files. So we desperately need to create a function in a jsp file and call it from another jsp file.

For example:

A.jsp

.....
<jsp:include page="B.jsp"/>
....
<%= getName(); %>

B.jsp ....

<%!
public String getName()
{
 return "Hello";
}
>%

Is there any way to do this?.


Solution

  • Yes you can, instead of

    <jsp:include page="B.jsp"/>
    

    Use

    <%@include file="B.jsp"%>
    

    Including page will just embed two jsp code so you are not getting that function but including file using directives will embed code first and then compile so you will get your function.

    You can find difference here

    What is the difference between <jsp:include page = ... > and <%@ include file = ... >?