Zamples, Inc. logo
 Home   Search   Solutions   My Zamples   FAQ   News   Contact 
Zamples ID:
Password:
   
0 anonymous users;
34 users logged in.

Live Samples
Live APIs

HTML or JSP Frag
Java Servlet Frag
HTML & Applet
Bash
C# (Mono)
C++ (gcc)
Groovy
Haskell (Hugs98)
J2SE 1.4 Class
J2SE 1.4 Fragment
J2SE 5.0 Class
J2SE 5.0 Fragment
J2SE 6.0 Class
J2SE 6.0 Fragment
Perl
Python
Ruby
 

Inside Zamples®

Declaring Methods in JSPs • Declaring Inner Classes in JSPs Part 1 and Part 2.

Declaring Methods in JSPs

A scriptlet is declared within a <% %> or <%= %> tag. In order to declare a method, it should be defined within a <%! %> tag.  Here is a simple example of how to declare a method that writes the Unicode value of a character to the web page.  Note that within the <%! declaration %> a JspWriter is defined and set before the display() method is called.  We will see why this is necessary in a moment:

<%!
   JspWriter out = null;
   
   void setOut(JspWriter out) { this.out = out; }

   void display (int c) throws java.io.IOException {
      out.println(c);
   } 
%>
<%
   setOut(out);
   display('x');
%>

Output

120

Let's take a look at the JSP that is generated by the above code fragment:

<%@ page session="true" %><html>
<body>
<h2>Interpreted JSP/HTML output below</h2>
<pre><%!
   JspWriter out = null;

   void setOut(JspWriter out) { this.out = out; }

   void display (int c) throws java.io.IOException {
      out.println(c);
   }
%>
<%
   setOut(out);
   display('x');
%></pre>
</body>
</html>

Now let's look at the servlet that is generated from the JSP. The out variable that we defined above is highlighted in yellow. As you can see, our out variable has class scope, unlike the out variable defined in _jspService, which has request scope. What this means is that methods that you define in a JSP don't have access to the request, response, session and servletContext objects unless you make special provision, as we have done with the setOut() method..

package sessions;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Vector;
import org.apache.jasper.runtime.*;
import java.beans.*;
import org.apache.jasper.JasperException;
import com.mslinn.JspExplorer;


public class _sessionsjsp13bt6em2s1_jsp_0 extends HttpJspBase {

    // begin [file="D:\\webapp\\sessions\\13bt6em2s1.jsp";from=(6,8);to=(14,0)]

        JspWriter out = null;

        void setOut(JspWriter out) { this.out = out; }

        void x () throws java.io.IOException {
           out.println("asdf");
        }
    // end

    static {
    }
    public _sessionsjsp13bt6em2s1_jsp_0( ) {
    }

    private static boolean _jspx_inited = false;

    public final void _jspx_init() throws JasperException {
    }

    public void _jspService(HttpServletRequest request, HttpServletResponse  response)
        throws IOException, ServletException {

        JspFactory _jspxFactory = null;
        PageContext pageContext = null;
        HttpSession session = null;
        ServletContext application = null;
        ServletConfig config = null;
        JspWriter out = null;
        Object page = this;
        String  _value = null;
        try {

            if (_jspx_inited == false) {
                _jspx_init();
                _jspx_inited = true;
            }
            _jspxFactory = JspFactory.getDefaultFactory();
            response.setContentType("text/html;charset=8859_1");
            pageContext = _jspxFactory.getPageContext(this, request, response,
            "", true, 8192, true);

            application = pageContext.getServletContext();
            config = pageContext.getServletConfig();
            session = pageContext.getSession();
            out = pageContext.getOut();

            // HTML // begin [file="D:\\webapp\\sessions\\13bt6em2s1.jsp";from=(0,58);to=(6,5)]
                out.write("<html>\r\n<head>\r\n   <link rel=\"stylesheet\" type=\"text/css\" ");
                out.write("href=\"/StyleSheet.css\">\r\n</head>\r\n<body>\r\n<h2>Interpreted");
                out.write(" JSP/HTML output below</h2>\r\n<pre>");
            // end
            // HTML // begin [file="D:\\webapp\\sessions\\13bt6em2s1.jsp";from=(14,2);to=(15,0)]
                out.write("\r\n");
            // end
            // begin [file="D:\\webapp\\sessions\\13bt6em2s1.jsp";from=(15,2);to=(19,0)]

                setOut(out);

                x();
            // end
            // HTML // begin [file="D:\\webapp\\sessions\\13bt6em2s1.jsp";from=(19,2);to=(22,0)]
                out.write("</pre>\r\n</body>\r\n</html>\r\n");
            // end

        } catch (Exception ex) {
            if (out.getBufferSize() != 0)
                out.clearBuffer();
            pageContext.handlePageException(ex);
        } finally {
            out.flush();
            _jspxFactory.releasePageContext(pageContext);
        }
    }
}

Declaring Classes in a JSP, Part 1

Here is a simple example of how to define a class in a JSP.  Note that the class definition is enclosed in <%! %>

<%!
class MioBean {
  public String toString(){
    return "I am the bean!";
  }
}
%> <%
  MioBean mb = new MioBean();
  out.println(mb);
%>

Sample Output

I am the bean! 

Declaring Classes in a JSP, Part 2

A JSP is actually a class.  This means that if we define a class within a JSP, it is actually an inner class.  Remember that inner classes cannot have static methods, so you can't declare main() like this:

public static void main() { }

We know that the inner class won't have access to out, so we can either create an instance variable containing the JspWriter, or reassign output as shown above.

<%!
class PrintMe {
  private JspWriter out = null;
  public void setOut(JspWriter out) { this.out = out; }
  public void dog(int character) throws java.io.IOException {
    out.println(character+character);
  }
  // inner classes can't have static methods, so we can't declare main()
}
%>
<%
PrintMe pm = new PrintMe();
pm.setOut(out);
pm.dog('A');
%>

Output

130

Add New Code Samples Here

If you have code samples that don't fit into any of the topics above which you would like to contribute, please put them here.  We'll sort them out into their own sections as appropriate later.

0 Quality Tested Examples 0 Problems & Suggestions 0 Closed Issues
to add a new posting or reply to an existing posting.