Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Java certification success, Part 2: SCWCD

Seema Manivannan (seema@whizlabs.com), Java developer and trainer, Whizlabs
Seema Manivannan has a Bachelor of Technology degree in Electrical and Electronics Engineering and a PG in Advanced Computing from C-DAC. Her work experience includes software development, teaching, and content development in Java programming and related technologies. She holds SCJP, SCWCD, and SCBCD certifications. She has been with Whizlabs for over two years, where she has co-authored the Sun certification exam simulators. She is an experienced corporate trainer and conducts Instructor-led online training for the SCJP, SCWCD, and SCBCD certification exams for Whizlabs. She is also the moderator of the Whizlabs SCBCD discussion forum. You can reach her at seema@whizlabs.com.

Summary:  Sun Certified Web Component Developer (SCWCD) is one of most coveted certifications in the J2EE domain. If you're considering the SCWCD certification, you need to be aware that it takes more than just learning the servlet and JSP technologies. It requires in-depth knowledge of the topics specified in the exam objectives, and Java programmer and certification trainer, Seema Manivannan of Whizlabs offers just that in this comprehensive tutorial. Seema covers the 13 main objectives of the SCWCD exam and provides a Q&A section to ensure you understand the concepts.

Date:  04 May 2004
Level:  Introductory PDF:  A4 and Letter (243 KB | 80 pages)Get Adobe® Reader®

Activity:  14615 views
Comments:  

The JavaServer pages technology model

JavaServer Pages

JavaServer Pages (JSP) technology is an extension of the Java Servlet API. JSP pages are typically comprised of static HTML/XML components, custom JSP tags, and Java code snippets known as scriptlets.

Even though JSP pages can contain business processing logic, they are mainly used for generating dynamic content in the presentation layer. Separation of business logic from presentation logic is one of the main advantages of this technology.

JSP tag types

JSP syntax can be classified into directives, declarations, scriptlets, expressions, standard actions, and comments.

Directives
A JSP directive provides information about the JSP page to the JSP engine. The types of directives are page, include, and taglib (a directive starts with a <%@ and ends with a %> ):

  • The page directive is used to define certain attributes of the JSP page:

    <%@ page import="java.util.*, com.foo.*" %>

  • The include directive is used to include the contents of a file in the JSP page:

    <%@ include file="/header.jsp" %>

  • The taglib directive allows us to use the custom tags in the JSP pages:

    <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>

Declarations
JSP declarations let you define variables and supporting methods that the rest of a JSP page may need.

To add a declaration, you must use the <%! and %> sequences to enclose your declarations, starting with a <%! and ending with a %>:

<%! int sum=0; %>

Here the variable sum is initialized only once when the JSP page is loaded.

Scriptlets
Scriptlets are fragments of code that are embedded within <% ... %> tags. They get executed whenever the JSP page is accessed:

<% 
int count=0;
count++;
out.println("Count is "+count);
%>

Expressions
An expression is a Java expression that is evaluated when the JSP page is accessed and its value gets printed in the resultant HTML page. JSP expressions are within <%= ... %> tags and do not include semicolons:

<%=  count %>

The above expression prints out the value of the variable count.

Standard actions
JSP actions are instructions that control the behavior of the servlet engine. The six standard JSP actions are jsp:include, jsp:forward, jsp:useBean, jsp:setProperty, jsp:getProperty, and jsp:plugin. We will discuss actions in more detail in the following sections.

Comments
A JSP comment is of the form <%-- Content to be commented --%>. The body of the content is ignored completely.


JSP documents

JSP files can now use either JSP syntax or XML syntax within their source files. However, you cannot intermix JSP syntax and XML syntax in a source file.

JSP files using XML syntax are called JSP documents. All JSP documents have a <jsp:root> element within which all the other elements are enclosed:

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:prefix1="URI-for-taglib1" 
	xmlns:prefix2="URI-for-taglib2" ...version="1.2">
    // contents of the JSP page
</jsp:root>

Let's view a sample JSP document:

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
  <jsp:directive.page errorPage="error.jsp" /> 
  <jsp:directive.include file="test.jsp"/>
  <jsp:declaration> int count=10; </jsp:declaration>
  <jsp:text> Hello </jsp:text>
  <jsp:expression> count * 10 </jsp:expression>
  <jsp:scriptlet>
	  int i=100;
	  int j=11;
	  out.println(i+j);
  </jsp:scriptlet>
</jsp:root>

You can see that the <jsp:scriptlet> tag is used for scriptlets, the <jsp:expression> tag is used for expressions, the <jsp:declaration> tag is used for declarations, and the <jsp:text> tag is used to embed text within a JSP document. The page directive is represented as <jsp:directive.page> and the include directive is represented as <jsp:directive.include>.

It is important to note that all the tags are case sensitive.


Page directive attributes

As discussed before, the page directives are used to define attributes that apply to the JSP page as a whole. These are passed onto the JSP container at translation time. Let's discuss the important page attributes that are relevant for the SCWCD exam.

import
The import attribute of a page directive is used to import a Java class into the JSP page. For instance:

<%@ page import="java.util.*, java.io.*,com.whiz.MyClass" %>
<%@ page import="com.whiz.TestClass" %>

It can appear multiple times in a translation unit.

session
The session attribute can have a value of true or false. It specifies whether the page should take part in an HttpSession. The default value is true. For instance:

<%@ page session="false" %>

errorPage
The errorPage attribute can be used to delegate the exception to another JSP page that has the error handling code. For instance:

<%@ page errorPage="error.jsp" %>

isErrorPage
The isErrorPage attribute specifies whether the current page can be the error handler for other JSP pages. The default value is false. For instance:

<%@ page isErrorPage="true" %>

language
The language attribute specifies the language used by the JSP page; the default value is "java." For instance:

<%@ page language="java" %>

extends
The extends attribute specifies the superclass of the generated servlet class of the JSP page. The default value of this attribute is vendor-specific. For instance:

<%@ page extends="mypackage.MyServlet" %>

buffer
The buffer attribute gives the minimum size of the output buffer before the content is sent to the client. For instance:

<%@ page buffer="32kb" %>

autoFlush
The autoFlush attribute specifies whether the data in the buffer should be sent to the client as soon as the buffer is full. The default value is true. For instance:

<%@ page autoFlush="false" %>


JSP lifecycle

When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests.

A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:

  • Translation
  • Compilation
  • Loading the class
  • Instantiating the class
  • jspInit() invocation
  • _jspService() invocation
  • jspDestroy() invocation

Translation
In this phase, the JSP page is read, parsed, and validated. If there are no errors, a Java file containing the servlet class is created.

Compilation
The Java file created in the translation phase is compiled into a class file. All the Java code is validated and syntax errors are reported in this phase.

Loading and instantiating
The servlet class is loaded into memory and instantiated, if the compilation is successful.

jspInit()
The jspInit() method is called only once in the life of the servlet. It is this method that we perform any initializations required for the servlet.

_jspService
The request and response objects are passed to this method when each client request is received for the JSP page. JSP scriptlets and expressions are processed and included in this method.

jspDestroy()
The jspDestroy() method is called when the servlet instance is taken out of service by the JSP engine. Any cleanup operation, such as releasing resources, can be performed in this method. After this method is called, the servlet is unable to serve any client requests.


JSP implicit objects

The JSP container makes available nine implicit objects that can be used within scriptlets and expressions because they are defined in the _jspService() method of the generated servlet.

The nine implicit objects in the JSP API and their purpose are listed in the following table:

Table 2. Implicit objects

Object Class Purpose
application javax.servlet.ServletContext Refers to the Web application's environment in which the JSP is executed.
config javax.servlet.ServletConfig The initialization parameters given in the deployment descriptor can be retrieved from this object.
exception java.lang.Throwable Available for pages that set the page directive attribute isErrorPage to true. It can be used for exception handling.
Out javax.servlet.jsp.JspWriter Refers to the output stream of the JSP page.
page java.lang.Object Refers to the current instance of the servlet generated from the JSP page.
pageContext javax.servlet.jsp.PageContext Provides certain convenience methods and stores references to the implicit objects.
request Subtype of javax.servlet.ServletRequest Refers to the current request passed to the _jspService() method.
response Subtype of javax.servlet.ServletResponse Refers to the response sent to the client. It is also passed to the _jspService() method.

Conditional and iterative statements

For generating dynamic content based on conditions, we can use conditional statements, such as if/else blocks. For performing repetitive tasks, there are iterative statements using for or while loops. Conditional and iterative statements can span across multiple scriptlets, so that we can include HTML code in between.

For instance, the following scriptlet code uses a conditional statement to check whether a user's password is valid. If it is valid, the marks are printed using an iterative statement.

<% if(passwordValid)
	    {
	%>
         Welcome, <%= username  %>
	<%
         for(int i=0; i<10; i++)
		 {
	%>
           Printing <%=marks[i] %>
	<% 
         }
        }

	%>

Be careful not to leave out the curly braces at the beginning and end of the Java fragments.


JavaServer Pages summary

In this section, you saw the basics of the JavaServer Pages (JSP) model. You learned about the various tag types and their purposes, and the various page directive attributes. Next, you identified the different phases in the JSP page lifecycle, followed by the nine implicit objects in the JSP API and the purpose of each of them. Finally, we saw how conditional and iteration statements can span across multiple scriptlets.


Sample questions 9

Question 1:

What will be the result of accessing the following JSP page, if the associated session does not have an attribute named str?

<%!
    String str;
    public void jspInit()
    {
     str = (String)session.getAttribute("str");
    }
%>

The string is: <%= str %>.

Choices:

  • A. "null" is printed
  • B. NullPointerException is thrown
  • C. Code does not compile
  • D. None of the above

Correct choice:

  • C

Explanation:

The JSP engine declares and initializes nine objects in the _jspService() method. These implicit object variables are application, session, request, response, out, page, pageContext, config, and exception. Because they are declared locally to the _jspService() method, they are not accessible within the jspInit() method, which means this code will not compile. If this code was within the jspService() method, it would have compiled without errors and printed "null." Hence choices A, B, and D are incorrect, and choice C is correct.

Question 2:

What will be the result of an attempt to access this JSP page?

<% x=10;% >
<% int x=5;% >
<%! int x; %>
x= <%=x%>
x= <%=this.x%>

The string is <%= str %>.

Choices:

  • A. Code does not compile because x is used before declaration
  • B. Prints x=5 followed by x=10
  • C. Prints x=10 followed by x=5
  • D. Prints x=10 followed by x=0
  • E. None of the above

Correct choice:

  • B

Explanation:

This declaration will create an instance variable x and initialize it to 0. Then in the service() method, you modify it to 10. Then you declare a local variable named x and give it the value 5. When you print x, it prints the local version of value 5. When you say this.x, you refer to the instance variable x, which prints 10. Hence choices A, C, and D are incorrect, and choice B is correct.

9 of 17 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=132293
TutorialTitle=Java certification success, Part 2: SCWCD
publish-date=05042004
author1-email=seema@whizlabs.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).