18.3 Expressions and Declarations

Java Servlet Programming, 2nd Edition > 18. JavaServer Pages > 18.3 Expressions and Declarations

 
< BACKCONTINUE >

18.3 Expressions and Declarations

In addition to scriptlets, JavaServer Pages allows code to be placed into a page using expressions and declarations. A JSP expression begins with <%= and ends with %>. Any Java expression between the two tags is evaluated, the result is converted to a String, and the text is included directly in the page. This technique eliminates the clutter of an out.println( ) call. For example, <%= foo %> includes the value of the foo variable.

A declaration begins with <%! and ends with %>. In between the tags, you can include any servlet code that should be placed outside the servlet's service method. You may declare static or instance variables or define new methods. Example 18-3 demonstrates with a JSP page that uses a declaration to define the getName( ) method and an expression to print it. The comment at the top of the file shows that JSP comments are surrounded by <%-- --%> tags.

Example 18-3. Saying "Hello" Using a JSP Declaration
<%-- hello2.jsp --%> <HTML> <HEAD><TITLE>Hello</TITLE></HEAD> <BODY> <H1> Hello, <%= getName(request) %> </H1> </BODY> </HTML> <%! private static final String DEFAULT_NAME = "World"; private String getName(HttpServletRequest req) {   String name = req.getParameter("name");   if (name == null)     return DEFAULT_NAME;   else     return name; } %>

This JSP behaves the same as hello1.jsp.

The special methods jspInit( ) and jspDestroy( ) can be implemented within a declaration. They are called by the background servlet's init( ) and destroy( ) methods and give the JSP page an opportunity to declare code to be executed on initialization and destruction. A JSP page cannot override the standard init( ) and destroy( ) methods because the methods are declared final by the background servlet.


Last updated on 3/20/2003
Java Servlet Programming, 2nd Edition, © 2001 O'Reilly

< BACKCONTINUE >


Java servlet programming
Java Servlet Programming (Java Series)
ISBN: 0596000405
EAN: 2147483647
Year: 2000
Pages: 223

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net