Copyrights © 2012 Jatin Kotadiya. All Rights Reserved . Powered by Blogger.

Tuesday, October 23, 2012

Java JSP & Servlet


Servlet & JSP
1.      History of web application
2.      Web Server Introduction
3.      Servlet Container
4.      What is Java Servlet?

––––––––––––––––––––––––––

History of web application
Earlier in client- server computing, each application had its own client program and it worked as a user interface and need to be installed on each user's personal computer.
Most web applications use HTML/XHTML that is mostly supported by all the browsers and web pages are displayed to the client as static documents.  A web page can merely displays static content and it also lets the user navigate through the content, but a web applicationprovides a more interactive experience.
Any computer running Servlets or JSP needs to have a container. A container is nothing but a piece of software
Responsible for loading, executing and unloading the Servlets and JSP
.While servlets can be used to extend the functionality of any Java- enabled server. They are mostly used to extend web servers, and are efficient replacement for CGI scripts. CGI was one of the earliest and most prominent server side dynamic content solutions, so before going forward it is very important to know the difference between CGI and the Servlets.
Common Gateway Interface (CGI)
The Common Gateway Interface, which is normally referred as CGI, was one of the practical techniques developed for creating dynamic content. By using the CGI, a web server passes requests to an external program and after executing the program the content is sent to the client as the output. In CGI when a server receives a request it creates a new process to run the CGI program, so creating a process for each request requires significant server resources and time, which limits the number of requests that can be processed concurrently. CGI applications are platform dependent. There is no doubt that CGI played a major role in the explosion of the Internet but its performance, scalability issues make it less than optimal solutions.
Java Servlets
Java Servlet is a generic server extension that means a java class can be loaded dynamically to expand the functionality of a server. Servlets are used with web servers and run inside a Java Virtual Machine (JVM) on the server so these are safe and portable. Unlike applets they do not require support for java in the web browser. Unlike CGI, servlets don't use multiple processes to handle separate request. Servets can be handled by separate threads within the same process. Servlets are also portable and platform independent.


Web Server Introduction
A web server is the combination of computer and the program installed on it. Web server interacts with the client through a web browser. It delivers the web pages to the client and to an application by using the web browser and he HTTP protocols respectively. We can also define the web server as the package of large number of programs installed on a computer connected to Internet or intranet for downloading the requested files using File Transfer Protocol, serving e-mail and building and publishing web pages. A web server works on a client server model. A computer connected to the Internet or intranet must have a server program. While talking about Java language then a web server is a server that is used to support the web component like the Servlet and JSP. Note that the web server does not support to EJB (business logic component) component.
A computer connected to the Internet for providing the services to a small company or a departmental store may contain the HTTP server (to access and store the web pages and files), SMTP server (to support mail services), FTP server (for files downloading) and NNTP server (for newsgroup). The computer containing all the above servers is called the web server. Internet service providers and large companies may have all the servers like HTTP server, SMTP server, FTP server and many more on separate machines. In case of Java, a web server can be defined as the server that only supports to the web component like servlet and jsp. Notice that it does not support to the business component like EJB.
Servlet Container
A servlet container is nothing but a compiled, executable program. The main function of the container is to load, initialize and execute servlets. The servlet container is the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages
Specifications are developed by Sun under the Java Community Process (JCP) [jcp.aip.org]
A container handles large number of requests as it can hold many active servlets, listeners etc. It is interesting to note here that the container and the objects in a container are multithreaded. So each object must be thread safe in a container as the multiple requests are being handled by the container due to the entrance of more than one thread to an object at a time.
Note: A Servlet container may run stand alone i.e. without a web server or even on another host.


List of Servlet Container

Non-commercial Web containers

  • Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under the Apache Software License.
  • Apache Geronimo is a full Java EE implementation by Apache.
  • GlassFish (open source), from Sun Microsystems
  • Jetty
  • Jaminid contains a higher abstraction than servlets.
  • Enhydra
  • Winstone supports specification v2.4, has a focus on minimal configuration and the ability to strip the container down to only what you need.
  • Tiny Java Web Server (TJWS) 2.5, small footprint, modular design

Commercial Web containers

  • BEA WebLogic Server or Weblogic Express, from BEA Systems
  • Borland Enterprise Server
  • Sun GlassFish Enterprise Server, from Sun Microsystems
  • Sun Java System Web Server, from Sun Microsystems
  • JBoss (open source)
  • JRun, from Adobe Systems (formerly developed by Allaire Corporation)
  • LiteWebServer (open source)
  • Oracle Application Server, from Oracle Corporation
  • Orion Application Server, from IronFlare
  • Caucho's Resin Server (open source)
  • ServletExec, from New Atlanta Communications
  • WebObjects, from Apple Inc.
  • WebSphere, from IBM
  • Netweaver, from SAP
  • tc Server (SpringSource)

Everybody wants a web site


What does your web server do?


What does client do?

HTML
When server answers a request, the server usually send some type of content to the browse so that browse can display it. Server often send some type of instructions written in HTML, a HyperText Markup Language. The HTML tells browser how to present the content to the user.
All web browsers know what to do with HTML. Some time old browser might not understand parts of page that was written using newer HTML version
HTTP
Most of the conversations held on the web browser client and server are held using HTTP protocol, which allow simple request and response conversation. The client send HTTP request and server answers HTTP response
HTTP GET Request



HTTP Post Request


HTTP Response









First Servlet
1.      Build Source directory tree
2.      Write helloservlet.java
3.      Create deployment descriptor(DD) named web.xml
4.      Build  Deployment Directory Tree in Tomcat
5.      Copy files in Tomcat Directory
6.      Start tomcat from tomcat/bin/startup.bat
7.      Start browser open urlhttp://localhost:8080/first/HelloServlet
8.      Shutdown tomcat from tomcat/bin/shutdown.bat

1.      Build Source directory
2.      Write helloservlet.java

import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;

public class HelloServlet extends HttpServlet
{
public void service(HttpServletRequest request,
HttpServletResponse response)
throwsServletException,IOException
{
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head>");
pw.println("</head>");
pw.println("<body>");
pw.println("<h3>Hello Servlet!</h3>");
pw.println("</body>");
pw.println("</html>");
}
}


Compile Java File

Compile Again with Servlet-Api.jar

Javac –cp f:\su\tomcat\lib\servlet-api.jar HelloServlet.java

3.      Create deployment descriptor(DD) named web.xml
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>

</web-app>

4.      Build  Deployment Directory Tree in Tomcat
5.      Copy files in Tomcat Directory
Web.xml in WEB-INF folder
HelloWorld.class in WEB-INF\classes

6.      Start tomcat from tomcat/bin/startup.bat
7.      Start browser open urlhttp://localhost:8080/FirstServlet/HelloServlet
http://localhost:8080/FirstServlet/HelloServlet





<servlet>
<servlet-name><INTERNAL NAME></servlet-name>
<servlet-class><CLASS NAME></servlet-class>
</servlet>
<servlet-mapping>
<servlet-name><INTERNAL NAME></servlet-name>
<url-pattern>/<URL NAME></url-pattern>
</servlet-mapping>


Understanding Deployment Descriptor


Servlet Life Cycle
Servlets run on the web server platform as part of the same process as the web server itself. The web server is responsible for initializing, invoking, and destroying each servlet instance.
A web server communicates with a servlet through a simple interface, javax.servlet.Servlet. This interface consists of three main methods:
  • init()
  • service()
  • destroy()
and two ancillary methods:
  • getServletConfig()
  • getServletInfo()
You may notice a similarity between this interface and that of Java applets. This is by design! Servlets are to web servers what applets are to web browsers.An applet runs in a web browser, performing actions it requests through a specific interface. A servlet does the same, running in the web server.
When a servlet is first loaded, its init() method is invoked. This allows the servlet to perform any setup processing such as opening files or establishing connections to their servers. If a servlet has been permanently installed in a server, it loads when the server starts to run. Otherwise, the server activates a servlet when it receives the first client request for the services provided by the servlet.
The init () method is guaranteed to finish before any other calls are made to the servlet--such as a call to the service() method. Note that init() will only be called once; it will not be called again unless the servlet has been unloaded and then reloaded by the server.
The init() method takes one argument, a reference to a ServletConfig object which provides initialization arguments for the servlet. This object has a method getServletContext() that returns a ServletContext object containing information about the servlet's environment (see the discussion on Servlet Initialization Context below).
The service() method is the heart of the servlet. Each request message from a client results in a single call to the servlet's service() method. The service() method reads the request and produces the response message from its two parameters:
  • A ServletRequest object with data from the client. The data consists of name/value pairs of parameters and an InputStream. Several methods are provided that return the client's parameter information. The InputStream from the client can be obtained via the getInputStream() method. This method returns a ServletInputStream, which can be used to get additional data from the client. If you are interested in processing character-level data instead of byte-level data, you can get a BufferedReader instead with getReader().
  • A ServletResponse represents the servlet's reply back to the client. When preparing a response, the method setContentType () is called first to set the MIME type of the reply. Next, the method getOutputStream() or getWriter() can be used to obtain a ServletOutputStream or PrintWriter, respectively, to send data back to the client.
As you can see, there are two ways for a client to send information to a servlet. The first is to send parameter values and the second is to send information via the InputStream (or Reader). Parameter values can be embedded into a URL. How this is done is discussed below. How the parameter values are read by the servlet is discussed later.
The service() method's job is conceptually simple--it creates a response for each client request sent to it from the host server. However, it is important to realize that there can be multiple service requests being processed at once. If your service method requires any outside resources, such as files, databases, or some external data, you must ensure that resource access is thread-safe. Making your servlets thread-safe is discussed in a later section of this course.
The destroy() method is called to allow your servlet to clean up any resources (such as open files or database connections) before the servlet is unloaded. If you do not require any clean-up operations, this can be an empty method.
The server waits to call the destroy() method until either all service calls are complete, or a certain amount of time has passed. This means that the destroy() method can be called while some longer-running service() methods are still running. It is important that you write your destroy() method to avoid closing any necessary resources until all service() calls have completed.


Inheritance of Servlet Classes


Servlet Context Listener






Cookies
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
public void service(HttpServletRequest request,
HttpServletResponse response)
throwsServletException,
IOException
{
            PrintWriter pw = response.getWriter();
              Cookie c1 = new Cookie("Name1","Cookie Name 1");
              Cookie c2 = new Cookie("Name2","Cookie Name 2");
            response.addCookie(c1);
            response.addCookie(c2);

            pw.println("<html>");
            pw.println("<head>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<h3>Hello Cookie!</h3>");
            Cookie[] c = request.getCookies() ;
            if( c != null){
            for(int i=0;i<c.length;i++){
                        try{
            pw.println("<br>" + c[i].getName() + "=" + c[i].getValue() );
                        }
                        catch(Exception e){
                                    pw.println(e.getMessage());
                        }
        }
            }

            pw.println("</body>");
            pw.println("</html>");
}
}
Session
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
import java.net.*;
importjava.util.*;
public class HelloServlet extends HttpServlet
{
            public void doGet(HttpServletRequestrequest,HttpServletResponse response) throws ServletException,IOException
            {
           
response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession(true);
        Date date = new Date(session.getCreationTime());
        Date accessed = new Date(session.getLastAccessedTime());
out.println("<br>ID " + session.getId());
out.println("<br>Created: " + date);
out.println("<br>Last Accessed: " + accessed);
        String data = request.getParameter("data");
if (data != null &&data.length() > 0) {
            String dataValue = request.getParameter("dataValue");
session.setAttribute(data, dataValue);
        }

        Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
            String name = (String)e.nextElement();
            String value = session.getAttribute(name).toString();
out.println("<br>" + name + " = " + value);
                    }  
            }
}


Request  Dispatcher
FirstServlet.java
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
            public void service(HttpServletRequestrequest,HttpServletResponse response)
            throwsServletException,IOException
            {
                        request.setAttribute("hello", "I am Request Attribute comes from First Servlet");
            getServletContext().getRequestDispatcher("/SecondServlet").forward(request, response);
                       
            }
}

SecondServlet.java
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void service(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException,IOException
{
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head>");
pw.println("</head>");
pw.println("<body>");
pw.println("<h3>Hello Second Servlet!</h3>");
pw.println("<h3>" + request.getAttribute("hello") + "</h3>");
pw.println("</body>");
pw.println("</html>");
}
}

Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>


<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/SecondServlet</url-pattern>
</servlet-mapping>

</web-app>


JSP
Introduction to JSP
JSP stands for JavaServer Pages. JSP is one of the most powerful, easy-to-use and fundamental technology for web developers. JSP combines HTML, XML, Java Servlet and JavaBeans technologies into one highly productive technology to allow web developers to develop reliable, high performance and platform independent web applications and websites.
JSP Advantages
Separate the business logic and presentation:  The logic to generate dynamic elements or content is implemented and encapsulated by using JavaBeans components. The user interface (UI) is created by using special JSP tags. This allows developers and web designers maintain the JSP page easier.
Write Once, Run Anywhere:  as a part of Java technology, JPS allows  developers to developer JSP pages and deploy them in a variety of platforms, across the web servers without rewriting or changes.
Dynamic elements or content produced in JSP can be served in a different formats:  With JSP you can write web application for web browser serving HTML format. You can even produce WML format to serve hand-held device browsers. There is no limitation of content format which JSP provides.
Take advantages of Servlet API: JSP technically is a high-level abstraction of Java Servlets. It is now easier to get anything you've done with Servlet by using JSP. Beside that  you can also reuse all of your Servlets you've developed so far in the new JSP.
Writing the first JSP page
A JavaServer Page, technically speaking, is a web page which is embedded Java code. Java code is executed in the server side and merge with the static elements of the web page such as HTML tags... then returns the result which is plain old HTML code, JavaScript and CSS to the web browser.
This is the source code of your first JSP page which prints the simple famous greeting in programming world "Hello World" on the web browser.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<h1>
<%
out.println("Hello World");
            %>
</h1>
</body>
</html>

JSP Page is composed of HTML and Java code. The Java code is embedded between the notations <% and %> and  it is called Scriptlet.  Inside the scriptlet block, we call the method println of the out object to print the text "Hello World".

JSP Scripting Elements

JSP Scripting allows you to insert Java code into the servlet which is generated from JSP page. These are the forms of scripting elements such as: comment, expression, scriptlet, declaration and expression language.

JSP Comment

JSP comments are used to explain the complicated logic code or to mark some region inside a JSP page for later changes. Comments in JSP is declared inside a JSP page as follows



<%-- This is a JSP comment --%>

<%--

   This is a JSP comment can span

in multiple lines

--%>

Expression

The most simple and basic of JSP scripting is expression. Expression is used to insert values directly to the output. The syntax of the expression is as follows. ( Be noted that there is no space between <% and =

<%= expression %>

For example, if you want to print out the current date and time you can use the expression as follows:

<%= new java.util.Date()%>

Scriptlet

Scriptlet is similar to the Expression without the equal sign "=". You can insert any plain Java code inside the scriptlet. Because of mixing between Java code and HTML is difficult to maintain so scriptlet is not recommended to use anymore. Here is the syntax of the scriptlet:

<%// any java source code here %>
 

In this example, we print the greeting based on the current time of the day using scriptlet.

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>

<head>

<title>JSP syntax</title>

</head>

<body>

<%

                // using scriptlet

java.util.Calendar now = new java.util.GregorianCalendar();

                String tod = "";

 

if (now.get(now.HOUR_OF_DAY) < 12) {

tod = "Morning!";

                } else if (now.get(now.HOUR_OF_DAY) < 18) {

tod = "Afternoon!";

                } else {

tod = "Evening!";

                }

%>

 

        Good <%=tod%>

 

</body>

</html>

Declaration

If you want to define methods or fields you can use JSP declaration. The JSP declaration is surrounded by the sign <%! and %>. For example, if you want to declare a variable x, you can use JSP declaration as follows:

<%!int x =10;%>
 
The final semicolon is very important.
 
The difference between a variable using declaration and a variable is declared using Scriptlet is that a variable declare using declaration tag is accessible by all the methods while a variable declared using Scriptlet is only accessible to the method _jspservice of the generated servlet from JSP page.
 
We can also declare a method using declaration tag, such as:

 

<%!
publicbooleanisInRange(intx,intmin,int max){
return x >= min && x <= max;
}
%>

 




Understanding JSP Life Cycle

JSP never outputs the content directly to the browser. Instead, JSP replies on initial server-side processing process which translates JSP page into the JSP Page class. The page class then will handle all the requests made of JSP. The JSP life cycle is described as the picture below:

JSP life cycle can be divided into four phases: Translation, Initialization, execution and finalization.

Translation

In the translation phase, JSP engine checks for the JSP syntax and translate JSP page into its page implementation class if the syntax is correct. This class is actually a standard Java servlet. After that, JSP engine compiles the source file into class file and ready for use.

If the container receives the request, it checks for the changes of the JSP page since it was last translated. If no changes was made, It just loads the servlet otherwise the process of check, translate and compile occurs again. Because the compilation process takes time so JSP engine wants to minimize it to increase the performance of the page processing.

Initialization

After the translation phase, JSP engine loads the class file and create an instance of of the servlet to handle processing of the initial request. JSP engines will call a method jspInit() to initialize the a servlet. jspInit method is generated during the translation phase which is normally used for initializing application-level parameters and resources. You can also overide this method by using declaration.

<%!
public void jspInit(){
      // put your custom code here  
   }
%>

Execution

After the initialization phase, the web container calls the method _jspService() to handle the request and returning a response to the client. Each request is handled is a separated thread. Be noted that all the scriptlets and expressions end up inside this method. The JSP directives and declaration are applied to the entire page so the are outside of this method.

Finalization

In the finalization phase, the web container calls the method jspDestroy(). This method is used to clean up memory and resources. Like jspInit() method, you can override the jspDestroy() method also to do your all clean up such as release the resources you loaded in the initialization phase....

<%!

public void jspDestroy(){

      // put your custom code here

      // to clean up resources

   }

%>

JSP Implicit Objects

JSP container provides a list of instantiated objects for you to access different kind of data in a web application. Those objects are called implicit object because it is automatically available to access.  These are some main implicit objects in JSP which you use most:

·         request object

·         response object

·         session object

·         out object

·         pageContext object

·         application object

·         config object

·         page object

·         excpetion object

The request object

Each time a client requests a JSP page, the JSP engine creates a new object to represents that request called request object.  The request object is an instance of class javax.servlet.http.HttpServletRequest. The request object contains all information about the current HTTP request and the clients.  Be noted that request object only available in a scope of the current request. It is re-created each time new request is made.

By using methods of the request object you can access almost information such as HTTP header, query string, cookies...

The response object

JSP also creates the response object which is an instance of classjavax.servlet.http.HttpServletResponse.  The response object represents the response to the client. By using this object you can add new cookies, change MIME content type of the page. In addition, the response object also contains sufficient information on the HTTP to be able to return HTTP status codes or make the page redirect to the other page.

The session object

The session object is used to track information of a particular client between multiple requests. the session object is avaible in the server so it can helps you to overcome the stateless of HTTP protocol. You can use session object to store a arbitrary information between client requests. The session object is an instance of class javax.servlet.http.HttpSession.

The out object

The output stream is exposed to the JSP through the out object. the out object is an instance of class javax.servlet.jsp.JspWriter. The out object may refer to an output stream or a filtered stream... You can use the out object methods to send the data into the output stream such as println method. Then JSP take care the rest.

The pageContext object

The pageContextobject represent the entire JSP page. You can use the pageContext object to get page attributes of a page. thepageContext object is an instance of class javax.servlet.jsp.pagecontext.

The application object

The application object is a representation of JSP page through its life cycle. The application object is created when a JSP page is initialized and removed when the JSP page is removed by jspDestroy() method or JSP page is recompiled. As its name imply, the information of the application object is accessible to any object used within the JSP page.

The config object

The config object allows you to access the initialization parameters for the Servlet and JSP engine. The config object is an instance of the class javax.servlet.ServletConfig.

The page object

The page object is an instance of a JSP page. By using the page object, you can call any method of the page's servlet.

The exception object

The exception object contains the exception which is thrown from the previous JSP page. You can use the exception object to generate friendly error message based on erorr condition to the end-user.

·         Request                       Javax.servlet.http.httpservletrequest

·         Response                     Javax.servlet.http.httpservletresponse

·         Session                        Javax.servlet.http.httpsession

·         Out                              Javax.servlet.jsp.JspWriter

·         PageContext                Javax.servlet.jsp.pagecontext

·         Application                  Javax.servlet.http.ServletContext

·         Config                          Javax.servlet.http.ServletConfig

·         Page                            jsp.HttpJspPage

 

Working with HTML Form - part I

HTML form basically is a graphic user interface (GUI) which you present to get the input data from the users. Once user submits the form from the client side; from the server side, you need to capture those data for further processing such as business logic validation, saving the data into the database and so on. Let start with a simple HTML form which getting user information.

<html>

<head>

<title>JSP Form Demo</title>

<style type="text/css">

label{ margin-right:20px;}

input{ margin-top:5px;}

</style>

</head>

<body>

<form action="handleUserInfo.jsp" method="post">

<fieldset>

<legend>User Information</legend>

<label for="fistName">First Name</label>

<input type="text" name="firstName" /><br/>

<label for="lastName">Last Name</label>

<input type="text" name="lastName" /><br/>

<label for="email">Email</label>

<input type="text" name="email" /><br/>

<input type="submit" value="submit">

</fieldset>

</form>

</body>

</html>

 

The form is very simple which contains three fields: first name, last name and email. In addition, It contains the submit button which users can submit when he/she finish entering the data.

In the form tag, you can see it uses the post method to post the data to the server. In the server a JSP file will responsible for getting and processing the data. Here is the handleUserInfo.jsp code.

<html>

<head>

<title>JSP Form Demo</title>

</head>

<body>

<%

            String firstName = request.getParameter("firstName");

            String lastName = request.getParameter("lastName");

            String email = request.getParameter("email");

        %>

<p>Hi <%=firstName%><%=lastName%>!,

your submitted email is <%=email%>.</p>

</body>

</html>

The request object is used to get the data from the submitted form. The getParametermethod of request object accepts the name of the form field and return the value. The return value of the getParameter method is always String type so if you have form field which accepts numerical value, you have to convert it. If no form field found, the getParameter method will return null.  After getting the values from the form, handleUserInfo.jsp uses those values to print out a message.

 

In this tutorial, you've use the request object to get the data from a HTML form. The form and the JSP is seperated. In the next tutorial, you will learn how to handle HTML form inside a single JSP page.

Working with HTML Form - part II

When dealing with HTML, you have multiple ways to separate the code to handle the form data and HTML form itself. These are the most two common ways to do so:

  1. Page which contains HTML Form and JSP page which handles HTML Form are separated. (as you see in the previous tutorial)

   2. Single JSP page to display form and  handle form.

In order to achieve the second way, we need to add an additional hidden field in the HTML form. When user submits the form data, we check the value of this hidden  field to see whether the form is submitted or not. Let's take a look at thecode below.

<html>
<head>
<title>JSP Form Demo</title>
<styletype="text/css">
label{ margin-right:20px;}
input{ margin-top:5px;}
</style>
</head>
<body>
<%
String val = request.getParameter("isSubmitted");
intisSubmitted = 0;
if (val != null) {
isSubmitted = Integer.parseInt(val);
if (isSubmitted == 1) {
                    String firstName = request.getParameter("firstName");
                    String lastName = request.getParameter("lastName");
                    String email = request.getParameter("email");
out.println("<p>Hi " + 
firstName + " " + 
lastName + "!, 
your submitted email is " + email +"</p>");
                }
            }
        %>
<% if (isSubmitted == 0) {%>
<formaction="index.jsp"method="post">
<fieldset>
<legend>User Information</legend>
<labelfor="fistName">First Name</label>
<inputtype="text"name="firstName"/><br/>
<labelfor="lastName">Last Name</label>
<inputtype="text"name="lastName"/><br/>
<labelfor="email">Email</label>
<inputtype="text"name="email"/><br/>
<inputtype="hidden"name="isSubmitted"value="1"/>
<inputtype="submit"value="submit">
</fieldset>
</form>
<%}%>
</body>
</html>

The first thing you can realize that the action of the Form now is pointed to the  page which form is embedded or index.jsp page. Second the logic of processing form data and displaying form are in a single JSP page.  The sequence of events occurs as follows.

·         At the first time when the page is loaded, the code checks for the form field name isSubmitted. Because getParameter will return null so the isSubmitted variable is set to 0 and the code displays the Form.

·         When user submits the form, there is a hidden field called isSubmitted with the value 1 available ion the form. Therefore at this time the parameter  isSubmitted is available. The code still checks for the parameter isSubmitted and find it. Then the process of collecting data and printing them out occurs as normal but no Form is output after the post back.

One of the most important thing to keep in mind when you deal with form is that: Never trust data which is submitted from client side. You can do client validation for simple validation such as required field, email is in the correct format in by using JavaScript. In the server side, you can do simple validation also after collecting the data, plus business validation to validate the constraints among data you collected.

JSP Directives

JSP directives instruct the JSP container on how to work with JSPs. There are three directives in the JSP specification: page, include and taglib. The directive form usualy follows the following form:

<%@ directiveattribute1 ="value 1"
              attribute2 ="value 2"
...
%>

page Directive

The page directive allows you to define one or more following attributes:

import Option

import="package.class"

import="package.class1,...,package.classN"

Import option allows you to specify which classes or packages are used in the page. for example, you can import all the classes in the package java.util as follows:

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

You can use  import option multiple times in the page directive.

contentType Option

contentType="MIME-Type"

contentType="MIME-Type; charset=Character-Set".

The contentType option allows you specify the MIME type of the output page. The default is text/html you can also use other values such as text/plain for outputing text format  such as

<%@ page contentType="text/plain" %>

isThreadSafe Option

isThreadSafe="true|false".

isThreadSafe option allows you to indicate the page is being processed as thread-safe. The default value of the isThreadSafe is true therefore all JSPs are considered thread-safe. If isThreadSafe is set to false, JSP engine ensures that only one thread at a time is executing the current JSP page.

session Option

session="true|false".

By using session option, you are telling JSP compiler that you want to use session or not. The default value of the session attribute is true, indicating that there is an implicit variable called session is available for your use.

buffer and autoFlush Options

buffer and autoFlush options let you control the JSP buffering.

You can turn buffer on or off or even specify the buffer size by using buffer option such as:

 

<%@ page buffer="none" %>

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

autoFlush option controls whether the buffer is flushed automatically when it is full.  The default value of autoFlush is true means JSP automatically flush the buffer when it is full.

Info Option

Info option allows you to define the description of the servlet. Later on you can access this value by calling the method:

Servlet.getServletInfo().

extends Option

In some cases, you need to create your own super class of JSP pages and using this supper class in different JSPs. In order to do so, first you need to create a super class first. This supper class normally inherits from the HttpServlet class. And in the JSPs you use the extends option to use that supper class in you JSP page.

isELIgnored Option

isELIgnored option provide the ability for you to disable the evaluation of the expression language (EL). You will learn more about expression language in the later tutorial.

errorPage Option

errorPage option allows you to indicate the error page to be displayed when the error occurs in the current executing page. For example:

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

isErrorPage Option

isErrorPage option indicates that the current JSP page can be used as an error page for other JSP page. When you set isErrorPage equal true, JSP engine creates an implicit exception object which contains the Throwable object that caused the error page to be called. By using this excpetion object, you can print out the error message to the user, for example:

<%@ page isErrorPage="true" %>

<html>

<head>

<title>Error Occurred</title>

</head>

<body>

<h1>Error</h1>

        An error occurred while processing your request.

<p>

            The error message is: <%= exception.getMessage()%>.</p>

        Please contact the System Administrator for advices.

</body>

</html>

Include Directive

Include directive lets you to include a file (JSP or HTML) at the time JSP engine translate the JSP page into a servlet.  The syntax of include directive is as follows:

<%@ include file="relative url" %>

The filename you specify in the include directive is a relative URL. If you provide a file name without associated path, the JSP compiler always assumes that the file is in the same directory as the JSP page.

Normally the include directive is used to include common sections of  a JSP page in a web application or website such as header, navigation bar, footer... to make those section reusable in every JSP page.

taglib Directive

JSP has a set of standard tags for you to use. JSP also provide a possibility to allow you to create new custom tags look like HTML and XML tag. In this case, you can use taglib directive to use your custom tag in your JSP page. For using custom tag, you can refer to the custom tag tutorial. The syntax of using taglib directive is as follows:

<%@ tagliburi=http://localhost/jsptutorial/taglib/mytaglib   prefix="jsptutorial" %>

JSP Standard Actions

JSP actions are special XML tags which control the behavior of servlet engine. JSP actions allow you to insert a file dynamically, reuse external JavaBean components, forward the request to the other page and generate HTML for Java Applet plugin.

jsp:include action

JSP include action allows you to include a file at runtime. The syntax of jspinclude action is as follows:

<jsp:include page="Relative URL" flush="true" />

In the page attribute you insert a relative URL of a file which could be an HTML file or another JSP page. Unlike the include directive, the jsp include action insert a file at the time page is being requested.

jsp:useBean action

jspuseBean action lets you load a JavaBean component into the page and use it later. jspuseBean action allows you to reuse other Java classes. The syntax of jspuseBean action is as follows:

<jsp:useBean id="objectName" class="package.class" />

By using the jsp:useBean action, you create an new object with the object name objectName of the class package.class. Later on you can access the properties of this object by using either jsp:setProperty or jsp:getProperty. Let's take a look at an example. First we have a JavaBeans call Message:

public class Message {

 

private String text;

public String getText() {

return text;

    }

public void setText(String text) {

this.text = text;

    }

}

Then we create a JSP page which uses the jsp:useBean action to access JavaBean Message inside that page.

<html>

<head>

<title>jsp:useBean Demo</title>

</head>

<body>

<jsp:useBean id="msg"class="com.jsptutorial.Message" />

 

<jsp:setProperty name="msg" property="text"value="JSP useBean Demo" />

<h1>

<jsp:getProperty name="msg"property="text" />

</h1>

 

</body>

</html>

We use jsp:setProperty to set the text property of the JavaBean Message and then we call jsp:getProperty to get that message and print it out. Here is the output screenshot:

jsp:forward Action

jsp:forward action allows you to forward a request to the other page. The syntax of the jsp:forward action is listed as below. There is one attribute called page which value is a page you want to forward the request to. You can specify the page statically or dynamically by using expression.

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

<jsp:forward page="<%= java-expression %>" />

jsp:plugin Action

jsp:plugin action allows you to embeded Java Applet into a page. Suppose you have an applet which demonstrates the JSP page lifecycle called com.jsp.jspapplet. Here is the way we use jsp:plugin action to embeded that applet into a page:

<html>

<head>

<title>jsp:plugin Demo</title>

</head>

<body>

<jsp:plugin type="applet"

code="com.jsp.jspapplet"

codebase="."   

width="500"

height="400">

<jsp:fallback>

<p>Unable to use Java Plugin</p>

</jsp:fallback>

</jsp:plugin>

 

</body>

</html>



 

JSP - Working with session

HTTP protocol is stateless. It means that there is no permanent connection between client (web browser) and Web Server. When client request a page from a web server, it opens a connection, retrieve the page and close connection. Web servers doesn't know what happen then in the client side. In addition, If another request from client is made, web server doesn't associate the new connection with the connection has been made.

In order to overcome the stateless of HTTP protocol, JSP provides you the implicit session object which is aHttpSession object. The session object resides in the server side so you can keep arbitrary data about the client and other data as well in session and later on in different requests you can retrieve the saved data for processing. JSP stores data in the server side in the session object by using a single key that client remembers.

The session object has the three most important methods which you use most as bellows:

publicvoidsetAttribute(Stringname,Objectvalue)
throwsIllegalStateException
 
publicObjectgetAttribute(Stringname)
throwsIllegalStateException
 
publicvoidremoveAttribute(Stringname)
throwsIllegalStateException

Let's take a look at an example how to use session object. In this example, we have three pages: In the first page we collection data from user, after that user submits the form to a second page which is used to store data in session. In the last page, we get data back from the session and display it.

<html>
<head>
<title>JSP Form</title>
</head>
<body>
<formmethod="post"action="savetosession.jsp">
<table>
<tr>
<td>First Name</td>
<td><inputtype="text"name="firstname"/></td>
</tr>
<tr>
<td>Last Name</td>
<td><inputtype="text"name="lastName"/></td>
</tr>
<tr>
<td>Comments</td>
<td><textareaname="comments"cols="30"rows="5"></textarea></td>
</tr>
<tr>
<tdcolspan="2"><inputtype="submit"value="submit"/></td>
</tr>
 
</table>
 
</form>
</body>
</html>

In the form above, when user enters information, clicks submit button, the data goes through the page savetosession.jsp. In the savetosession.jsp page we save all the submitted data into the session object and forward the request to another page called display.jsp page

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
          String firstName = request.getParameter("firstName");
          String lastName = request.getParameter("lastName");
          String comments = request.getParameter("comments");
          // save data into the session
session.setAttribute("firstName", firstName);
session.setAttribute("lastName", lastName);
session.setAttribute("comments", comments);
 
%>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%-- forward to the display.jsp page--%>
<jsp:forwardpage="display.jsp"/>
</body>
</html>

As you see the code above, we use the setAttribute() method to save data into the session object. Here is the page for displaying data in the session object: display.jsp

<%@pagecontentType="text/html"pageEncoding="UTF-8"%>
<html>
<head>
<title>Displaying data inSession</title>
</head>
<body>
<h1>Displaying data in sessionobject</h1>
<table>
<tr>
<td>FirstName</td>
<td><%=session.getAttribute("firstName")%></td>
</tr>
<tr>
<td>LastName</td>
<td><%=session.getAttribute("lastName")%></td>
</tr>
<tr>
<td>Comments</td>
<td><td><%=session.getAttribute("comments")%></td>
</tr>
</table>
</body>
</html>

The code is obvious, we used the getAttribute() method of the session object to retrieve data which was entered in the form and displayed it on the page by using expression.

How session works

When server creates a new session, it always adds a session identifier in the form of cookie. When web browser asks for a page or makes a request, the web browser always sends cookie which are created by the web server in the request. Therefore in the server side, web server checks for that cookie and find the corresponding session that is matched to the received cookie.

The session normally short-lived so the session cookie is not saved into disk. Session also has time out. When the time is out, the session is no longer exist in the server side. You can set time out of session in configuration file in the server.

Working with cookie in JSP

Cookie is a small piece of information which is stored in user's computer. Web server uses cookie to identify the user in the next time visit.

Each time user visits a website which cookie is enable, the web server adds extra data into the HTTP header and responds to the web browser. in the next time when user visits the same site again, the web browser also sends cookie in the HTTP request header to the web server.

User can also disables cookie in the web browser which supports disable cookie function such as Mozilla Firefox, IE...

Cookie is stored in the user's computer as a string of name/value. In addition, cookie has attributes such as domain, path, timeout...

JSP provides API to allows you to work with cookie effectively through object of the class javax.servlet.http.Cookie. Let's take a look at an example how to set cookie in JSP and respond it back to the client.

<%@pageimport="javax.servlet.http.Cookie"%>
<html>
<head>
<title>JSP SetCookie</title>
</head>
<body>
<%
Cookiecookie=newCookie("ClientID","JSP Guru");
cookie.setMaxAge(3600);
response.addCookie(cookie);
%>
</body>
</html>

In the code, first you create a new cookie with the name and value. If you se the methods such as setDomain()  and setPath() to restrict the cookie to the current URL you have to read the cookie exactly from that URL. Cookie has its own lifetime called expiration time. If you don't set the timeout for the cookie, it will be removed when user closes the web browser. The method setMaxage() is used to set the expiration time for the cookie. Finally you add cookie to the response header and store it in the user's computer by using method addCookie() of response object.

Reading cookie
To read cookie from a HTTP request, you first call the method getCookies() of the request object. This method returns you a list of available cookies in the request header, then you can walk through all of them. Here is the code to read cookie information:
<%@page import="javax.servlet.http.Cookie"%>
<html>
<head>
<title>JSP Read Cookie</title>
</head>
<body>
<%
Cookie[] list = request.getCookies();
if(list != null){
for(int i = 0; i <list.length;i++){
out.println(list[i].getName() + ":" + list[i].getPath());
                }
            }
        %>
</body>
</html>

Removing existing cookie
If you want to remove an existing cookie you've sent to the web browser, you can use the method setMaxAge() of that cookie object to set its timeout to zero. This is the sample code to remove all the cookies.
<%@page import="javax.servlet.http.Cookie"%>
<html>
<head>
<title>Removing existing cookie</title>
</head>
<body>
<%
Cookie[] list = request.getCookies();
if (list != null) {
for (int i = 0; i <list.length; i++) {
list[i].setMaxAge(0);
out.println(list[i].getName() + " cookie is removed");
                }
            }
        %>
</body>
</html>




0 comments:

Post a Comment