• No results found

JSP & Servlets

In document CoreJava_JSP_Servlet_Struts_EJB (Page 146-162)

JDBC Assignment(s) (Contd.)

Create program called DeleteEmployee as same as SearchEmployee written earlier, but instead of

retrieving, delete the employee.

JSP & Servlets

Chapter: 1 - JSP Basics What is a JSP Page ?

The JSP

A JSP page is a text-based document

It contains two types of text: static template data, which can be expressed in any text-based format,

such as HTML, WML, and XML; and JSP elements

It is the JSP elements that make up the dynamic content

The JSP elements also includes java code in scriplets (We will see scriplets in detail a bit later)

The java code is executed server side and if java code writes some contents to the response obect, the

contents written to response object is rendered to the client

The response object is an implicit object (instantiated by the server). What ever contents are written to response object are rendered to the client. This is the standard concept of Web-Apps and not just specific to JSP.

Your First JSP

JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its

extension to ".jsp" instead of ".html". In fact, this is the perfect exercise for your first JSP.

Create a html file which prints "Hello, world". Change its extension from ".html" to ".jsp". Now load

the new file, with the ".jsp" extension, in your browser.

You will see the same output, but it will take longer! But only the first time. If you reload it again, it

will load normally.

What is happening behind the scenes is that your JSP is being turned into a Java file, compiled and

loaded. This compilation only happens once, so after the first load, the file doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-compiled again.)

Creating Static & Dynamic Content

Creating Static Content

You create static content in a JSP page by simply writing it as if you were creating a page that

consisted only of that content.

Static content can be expressed in any text-based format, such as HTML, WML, and XML. The

default format is HTML

If you want to use a format other than HTML, you include a page directive with the contentType

attribute set to the format type at the beginning of your JSP page. For example, if you want a page to contain data expressed in the wireless markup language (WML), you need to include the following directive:

<%@ page contentType="text/vnd.wap.wml"%>

A registry of content type names is kept by the IANA at : ftp://ftp.isi.edu/in-notes/iana/assignments/media-types Adding Dynamic Content Via Expressions

What makes JSP useful is the ability to embed Java. Put the following text in a file with .jsp

extension (let us call it hello.jsp), place it in your JSP directory, and view it in a browser:

<HTML>

<BODY>

Hello! The time is now <%= new java.util.Date() %>

</BODY>

</HTML>

Notice that each time you reload the page in the browser, it comes up with the current time.

The character sequences <%= and %> enclose Java expressions, which are evaluated at run time

This is what makes it possible to use JSP to generate dyamic HTML pages that change in response to

user actions or vary from user to user.

Exercise:

Write a JSP to output the values returned by System.getProperty for various system properties such as java.version, java.home, os.name, user.name, user.home, user.dir

jsp:include

The jsp:include element is processed when a JSP page is executed. The include action allows you to

include either a static or dynamic resource in a JSP file

The results of including static and dynamic resources are quite different.

If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the

request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page.

The syntax for the jsp:include element is as follows:

<jsp:include page="includedPage" />

Transferring Control to Another Web Component (jsp:forward)

The mechanism for transferring control to another Web component from a JSP page uses the functionality provided by the Java Servlet API

You access this functionality from a JSP page with the jsp:forward element:

<jsp:forward page="/main.jsp" />

Param Element

When an include or forward element is invoked, the original request object is provided to the target page.

If you wish to provide additional data to that page, you can append parameters to the request object

with the jsp:param element:

<jsp:include page="..." >

<jsp:param name="param1" value="value1"/>

</jsp:include>

Life Cycle of JSP Page The Life Cycle of JSP

A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology.

When a request is mapped to a JSP page, it is handled by a special servlet that first checks whether

the JSP page's servlet is older than the JSP page.

If it is, it translates the JSP page into a servlet class and compiles the class.

During development, one of the advantages of JSP pages over servlets is that the build process is

performed automatically

Translation and Compilation

During the translation phase, template data is transformed into code that will emit the data into the

stream that returns data to the client.

JSP elements are treated as follows:

Directives are used to control how the Web container translates and executes the JSP page

Scripting elements are inserted into the JSP page's servlet class.

Elements of the form <jsp:XXX ... /> are converted into method calls to JavaBeans

components or invocations of the Java Servlet API

Translation And Compilation Errors

Both the translation and compilation phases can yield errors that are only observed when the page is requested for the first time. However, some ide(s) can compile jsp(s) for you so that you can rectify the errors before you deploy

If an error occurs while the page is being translated (for example, if the translator encounters a

malformed JSP element), the server will return a ParseException, and the servlet class source file will be empty or incomplete

The last incomplete line will give a pointer to the incorrect JSP element.

If an error occurs while the JSP page is being compiled (for example, there is a syntax error in a

scriptlet), the server will return a JasperException and a message that includes the name of the JSP page's servlet and the line where the error occurred

JSP Instance Life - Cycle

Once the page has been translated and compiled, the JSP page's servlet for the most part follows the

servlet life cycle

1. If an instance of the JSP page's servlet does not exist, the container:

a. Loads the JSP page's servlet class

b. Instantiates an instance of the servlet class

c. Initializes the servlet instance by calling the jspInit method 2. Invokes the _jspService method, passing a request and response object.

Scriplets

Adding Scriplets

JSP allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between <% and %> characters (just like expressions, but without the = sign at the start of the sequence.)

This block of code is known as a "scriptlet". By itself, a scriptlet doesn't contribute any HTML

(though it can, as we will see down below.) A scriptlet contains Java code that is executed every time the JSP is invoked.

<HTML>

System.out.println( "Evaluating date now" );

java.util.Date date = new java.util.Date();

%>

Hello! The time is now <%= date %>

</BODY>

</HTML>

By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use a

variable called "out". The following example shows how the scriptlet can generate HTML output.

<HTML>

<BODY>

<%

// This scriptlet declares and initializes "date"

System.out.println( "Evaluating date now" );

java.util.Date date = new java.util.Date();

%>

Hello! The time is now

<%

// This scriptlet generates HTML output out.println( String.valueOf( date ));

</BODY>

</HTML>

Mixing Scriplets & HTML

We have already seen how to use the "out" variable to generate HTML output from within a scriptlet.

For more complicated HTML, using the out variable all the time loses some of the advantages of JSP programming. It is simpler to mix scriptlets and HTML.

Suppose you have to generate a table in HTML. This is a common operation, and you may want to

generate a table from a SQL table, or from the lines of a file. But to keep our example simple, we will generate a table containing the numbers from 1 to N. Not very useful, but it will show you the technique.

The important things to notice are how the %> and <% characters appear in the middle of the "for"

loop, to let you drop back into HTML and then to come back to the scriptlet.

Exercise:

Make the above examples work. Write a JSP to output all the values returned by System.getProperties with "

" embedded after each property name and value. Do not output the "<BR>" using the "out" variable.

JSP Directives Include Directive

There are two mechanisms for including another Web resource in a JSP page: the include directive

and the jsp:include element.

The include directive is processed when the JSP page is translated into a servlet class.

The effect of the directive is to insert the text contained in another file--either static content or

another JSP page--in the including JSP page

You would probably use the include directive to include banner content, copyright information, or

any chunk of content that you might want to reuse in another page.

The syntax for the include directive is as follows:

<%@ include file="filename" %>

Page Directives

The <%@ page %> directive applies to an entire JSP file and any of its static include files, which together are called a translation unit.

You can use the <%@ page %> directive more than once in a translation unit, but you can only use

each attribute, except import, once. Because the import attribute is similar to the import statement in the Java programming language, you can use a <%@ page %> directive with import more than once in a JSP file or translation unit.

No matter where you position the <%@ page %> directive in a JSP file or included files, it applies

to the entire translation unit. However, it is often good programming style to place it at the top of the JSP file.

Import Page Directive

import="{package.class | package.* }, ..."

A comma-separated list of Java packages that the JSP file should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP file. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP file.

The following packages are implicitly imported, so you don't need to specify them with the import attribute:

java.lang.*

javax.servlet.*

javax.servlet.jsp.*

javax.servlet.http.*

You must place the import attribute before the element that calls the imported class.

If you need to include a long list of packages or classes in more than one JSP file, you can create a separate JSP file with a <%@ page %> directive that contains the import list and include that file in the main JSP file.

JSP Declarations Declarations in JSP

The JSP you write turns into a class definition. All the scriptlets you write are placed inside a single

method of this class.

You can also add variable and method declarations to this class. You can then use these variables

and methods from your scriptlets and expressions.

To add a declaration, you must use the <%! and %> sequences to enclose your declarations, as shown

Hello! The time is now <%= getDate() %>

</BODY>

</HTML>

The example has been created a little contrived, to show variable and method declarations.

Please NoteThe date will be the same, no matter how often you reload the page.

Declarations in JSP (Contd.)

You might have noted that the example given on previous page displays the same date each time it is

executed

This is because these are declarations, and will only be evaluated once when the page is loaded! (Just

as if you were creating a class and had variable initialization declared in it.)

Please refer to notes given below

It is in general not a good idea to use variables as shown here. The JSP usually will run as multiple threads of one single instance. Different threads would interfere with variable access, because it will be the same variable for all of them. If you do have to use variables in JSP, you should use synchronized access, but that hurts the performance. In general, any data you need should go either in the session objet or the request objectc (these are introduced a little later) if passing data between different JSP pages

Assignment(s)

JSP Basic Assignments

Create a Banner.jsp which will display today's date. Create an index.jsp and provide anchor on it to

Customer.jsp, Product.jsp, Tax.jsp and Invoice.jsp. On each of these jsp(s) include Banner.jsp on the top. Use both the methods (include directive and jsp:include)

Write a scriplet in Customer.jsp to retrieve (use jdbc) all the data from Customer table (if Customer

table is not created, create one). Use out.println("..."); to display the data retrieved

Modify the above program to give an anchor on Customer.jsp to display index.jsp

Chapter: 2 - Implicit Objects What are Implicit Objects

The JSP-Implicit Objects

Implicit objects are created by the Web container and contain information related to a particular

request, page, or application.

Many of the objects are defined by the Java Servlet technology underlying JSP technology and are

discussed at length later while discussing Servlets

These implicit objects are:

application The context for the JSP page's servlet and any Web components contained in the same application

config Initialization information for the JSP page's servlet.

exception Accessible only from an error page

out The output stream - Type: javax.servlet.jsp.JspWriter

page The instance of the JSP page's servlet processing the current request.

Not typically used by JSP page authors.

pageContect

The context for the JSP page. Provides a single API to manage the various scoped attributes. This API is used extensively when implementing tag handlers

request, response, session Discussed in Detail on next pages

Using Request Object

When the end-user submits a request to the server (usually through a browser), the Servlet Engine at the server side receives it and creates a request object and makes it available to your JSP.

This request object contains data that is submitted by the client. So you see, if you want to catch hold

of data which was sent by the client to the server, it is this request object in which this data is available

You can get this data in your code using request.getParameter(<parameterName>).

Note one very important point: The request object is alive only till the time the response (we will

discuss more on response later) is sent back to the client.

Once the client gets his response, the data that was available in the previous request he had sent is all

gone. Now when he comes back to the server, he will be coming back with a new request. To put it in plain simple language : Each time you hit a link or a submit button on a web page, a new request is created server side for that client

Reading Data from request Object

Lets get to hands-on to get the concepts more clear.

Add a New Customer</h1>

<input type="text" name="id" value=""/>

</td>

<input type="text" name="name" value=""/>

</td>

<input type="text" name="address" value=""/>

</td>

<input type="text" name="cityId" value=""/>

</td>

</tr>

<tr>

<td colspan="2">

<input type="submit" name="submit" value="Add Customer"/>

</td>

</tr>

</table>

</form>

</body>

</html>

Which looks like as follows:

In document CoreJava_JSP_Servlet_Struts_EJB (Page 146-162)

Related documents