2009-07-22

Implementing an interface in a JSP

I've scoured the net, but apparently it's not possible to make a Java Server Page implement an interface. Not directly, anyway.

What is possible is to extend a class. The directive is:

<%@ page extends="package.class"%>


One reference for JSP page directives is: http://java.sun.com/products/jsp/tags/11/syntaxref11.fm7.html .

The class generated from a JSP usually extends HttpServlet. If you really want to have your JSP implement an interface, you could do something like

public abstract class
my.package.MyJSP extends HttpServlet implements MyInterface {

}

... and then use "my.package.MyJSP" in a "page extends" directive as shown above.

The caveat to this is that some Web containers will generate their own subclasses of HttpServlet, presumably for some kine of optimization, and using the "page extends" directive will sabotage this scheme. It should still work, it just won't include the fancy footwork your Web container intended to do.

No comments: