Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating methods in JSP

 
Yogender Butola
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we create methods in a JSP page? If yes then how?
 
Atul Prabhu
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Yes

<HTML>
<HEAD>
<TITLE>Creating a Method</TITLE>
</HEAD>

<BODY>
<H1>Creating a Method</H1>
<%!
int addem(int op1, int op2)
{
return op1 + op2;
}
%>

<%
out.println("2 + 2 = " + addem(2, 2));
%>
</BODY>
</HTML>

---
Atul
 
Vijayendra V Rao
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Yogender Butola:
Can we create methods in a JSP page? If yes then how?


In a JSP, you can include normal Java code by enclosing it in the <% %> tags. For example, if you wish to have a method insode your JSP page, then you can have it the following way:



Once you have a method, you can call it from anywhere (that is, after the method implementation ofcourse) with the following syntax:

 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, but if you're going to declare new methods in a JSP they have to be put in declaration tags (<%! %>). Code inside declaration tags gets added to the resulting servlet at the class level, where you would want a method declaration. If you use the scriptlet tags (<% %>) the code is inserted inside the _jspService() method of the resulting servlet, which would cause an error if you tried to declare a method there.
 
Vijayendra V Rao
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh! Thanks for correcting me Nathan
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!