JSP/SERVLET
2015.06.17 / 24:14

JSP: How to Declare Methods and Inner Class in JSP

¸Þ¸®¾ß½º
Ãßõ ¼ö 358

JSP itself is just a plaint text and will be translated into Java source file (actually a servlet), compiled into class file and only interpreted at the end during runtime. All these happen at the backend.

When the whole JSP is translated into Java source file, all the HTML codes will be translated and source lines in <% %> tag will be included in a function of the translated servlet source file.

Therefore we can¡¯t simply declare methods and classes in JSP, even within the <% %> clause because we can¡¯t declare a function or class within a function.

To declare Java methods and classes in JSP, you need to write the declaration in the <%! %> clause so the the translator know which part of the code should be handled differently.

For example declaring a method in JSP:

<body>
<h2>Declare function in JSP</h2>
<%!
  int hello(JspWriter out, String name) {
    out.print("Hello");
  } 
%>
<%
  // Call the hello() function in JSP
  hello(out, " world");
%>
</body>

For example declaring a inner class in JSP:

<body>
<h2>Declare class in JSP</h2>
<%!
  class Hello {
    JspWriter out;
    public Hello(JspWriter out) {
      this.out = out;
    }

    public void greet(String name) {
        out.print("Hello " + name);
    }
  }
%>
<%
  // Use the Hello class in JSP
  Hello hello = new Hello(out);
  hello.greet("Christine");
%>
</body>