• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Creating methods in JSP

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can we create methods in a JSP page? If yes then how?
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh! Thanks for correcting me Nathan
 
reply
    Bookmark Topic Watch Topic
  • New Topic