What is a scriptlet?

Alex Chaffee

A scriptlet is a little chunk of raw Java code embedded directly inside a JSP. For example:

x times y = <%
  int x = Integer.parseInt(request.getParameter("x"));
  int y = Integer.parseInt(request.getParameter("y"));
  out.print(x * y);
Some details:
  • Theoretically, you can use languages other than Java, but this depends on your servlet engine. For instance, Resin supports JavaScript.

  • There are three other types of scriptlets: <%= %> can contain any Java expression, such as a variable or method invocation, and embeds its value into the output stream (as if it were surrounded with out.print()). <%! %> can contain a Java declaration, such as an instance variable or method. And <%@ %> can contain a directive such as <%@page import="java.util.*" %>

  • Scriptlets are very powerful, but also very controversial, since they allow you to write really sloppy code that blurs the distinction between presentation (HTML tags) and business logic (Java code). It's usually cleaner to use JavaBeans or custom tags, but these can require much more work, both in writing the beans/tags, and in writing the JSP code to access them. For these reasons, scriptlets are more appropriate during prototyping, when you want a "quick and dirty" way to get functionality into a page. Eventually, when you clean up your app and get it ready for productions, you should migrate scriptlets to the abovementioned options.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact