Prathap
Prathap

Reputation: 85

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?.

Upvotes: 2

Views: 26595

Answers (4)

Bimalesh Jha
Bimalesh Jha

Reputation: 1504

Above comments are all valid. However, if you must do this, I would improve it a bit by putting all functions in a separate file and call it methods.inc and then include it in jsp file like

<%@include file="methods.inc" %>

This will help you to know the intention clearly and look somewhat cleaner too.

Upvotes: 0

Waqas Memon
Waqas Memon

Reputation: 1249

Above comments are all valid. Do not do this. Its a bad design. But, if you just what to know any possible way of doing this, it can be using static includes of the JSP.

You can use <%@include %> directive to include JSP fragments

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

in A.jsp

The good design would be for you to create a Class in java and write all your methods in it, include it in all ur JSPs, and use the methods.

Other people are confused with similar questions, like how to call a JS function in one JSP/HTML to another JSP/HTML, the answer remains same. The good design would be to use a .js file to write all JS Methods.

Upvotes: 0

commit
commit

Reputation: 4807

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 = ... >?

Upvotes: 6

Prasad Kharkar
Prasad Kharkar

Reputation: 13566

You should not create a function in Jsp file. JSP's are meant for view purpose only .

You can write the function in separate java class and call that class from whatever Jsp pages you want.

Upvotes: 6

Related Questions