chapter 3 servlet & jsp

54
Servlets

Upload: jafar-nesargi

Post on 13-May-2015

397 views

Category:

Technology


7 download

TRANSCRIPT

Page 1: Chapter 3 servlet & jsp

Servlets

Page 2: Chapter 3 servlet & jsp

Servlets

Java Servlet is a java object file developed as a component and runs on the server.

Servlets are programs that run on a Web or application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server

Servlets is a component can be invoked from HTML.

Note: Servlets cannot run independently as a main application

like the java applet, the servlet does not have main method.

Page 3: Chapter 3 servlet & jsp

Servlets

Servlet do not display a graphical interface to the user.

A servlet’s work is done at the server and only the results of the servlet’s processing are returned to the client in the form of HTML.

A Servlet is a Java technology-based Web component, managed by a container that generates dynamic content.

Like other Java technology-based components, Servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.

Page 4: Chapter 3 servlet & jsp

Predessor of servlet In the early days of the web u have

to use the Common Gateway interface(CGI) to perform server side processing of forms and interaction with the datadase.

Later microsoft ASP technology enable server side processing using Vbscript, Javascript.

Page 5: Chapter 3 servlet & jsp

Difference Between Servlet & CGI

The advantages of using servlets are their fast performance and ease of use combined with more power over traditional CGI (Common Gateway Interface).

Traditional CGI scripts written in Java have a number of disadvantages when it comes to performance

When an HTTP request is made, a new process is created for each call of the CGI script. This overhead of process creation can be very system-intensive, especially when the script does relatively fast operations. Thus, process creation will take more time than CGI script execution.

Java servlets solve this, as a servlet is not a separate process. Each request to be handled by a servlet is handled by a separate Java thread within the Web server process, omitting separate process forking (split) by the HTTP domain.

Page 6: Chapter 3 servlet & jsp

Difference Between Servlet & CGI

Simultaneous CGI request causes the CGI script to be copied and loaded into memory as many times as there are requests.

However, with servlets, there are the same amount of threads as requests, but there will only be one copy of the servlet class created in memory that stays there also between requests.

A servlet can be run by a servlet engine in a restrictive environment, called a sandbox. This is similar to an applet that runs in the sandbox of the Web browser. This makes a restrictive use of potentially harmful servlets possible.

Page 7: Chapter 3 servlet & jsp

Advantages of Servlets

Platform Independence: Servlets are written entirely in java so these are

platform independent. Servlets can run on any Servlet enabled web server.

Performance Due to interpreted nature of java, programs written

in java are slow. But the java Servlets runs very fast. These are due

to the way Servlets run on web server. For any program initialization takes significant

amount of time. But in case of Servlets initialization takes place first time it receives a request and remains in memory till times out or server shut downs.

Page 8: Chapter 3 servlet & jsp

Extensibility Java Servlets are developed in java which is robust, well-

designed and object oriented language which can be extended or polymorphed into new objects.

So the java Servlets take all these advantages and can be extended from existing class to provide the ideal solutions.

4. Safety Java provides very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.

5. Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.

Page 9: Chapter 3 servlet & jsp

Life cycle of a servlet

• Init () Method• Service () Method• Destroy() method

Init () Method:-

During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method.

The container passes an object implementing the ServletConfig interface via the init() method.

This configuration object allows the servlet to access name-value initialization parameters from the web application.

Page 10: Chapter 3 servlet & jsp

• Service () Method:-

◦ After initialization, the servlet can service client requests. each request is serviced in its own separate thread.

◦ The Web container calls the service() method of the servlet for every request.

◦ The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request.

◦ The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester.

• Destroy() method:-

◦ Finally, the Web container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet.

Page 11: Chapter 3 servlet & jsp
Page 12: Chapter 3 servlet & jsp

Types of servlets

• Generic Servlets: Generic Servlets are protocal independent

that is they do not contain any inherent support for any protocal.

Generic Servlets handle request by overriding the services() method.

• HTTP Servlets: HTTP Servlets are HTTP protocal specific. This

makes it very useful in a browser environment. In case of HTTP Servlets, service() method

route the request to another method based on which HTTP transfer method is used.

Page 13: Chapter 3 servlet & jsp

Using Tomcat for Servlet Development

To create servlets, you will need access to a servlet development environment.

Tomcat is an open-source product maintained by the Jakarta Project of the Apache Software Foundation.

It contains the class libraries, documentation, and runtime support that you will need to create and test servlets.

Page 14: Chapter 3 servlet & jsp

Servlet API Two packages contain the classes and interfaces that

are required to build servlets.

javax.servlet javax.servlet.http.

They constitute the Servlet API.

These packages are not part of the Java core packages. Instead, they are standard extensions provided by Tomcat.

The Servlet API has been in a process of ongoing development and enhancement. The current servlet specification is version 2.4,

Page 15: Chapter 3 servlet & jsp

Simple Servlet programimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); }}

Page 16: Chapter 3 servlet & jsp

public class ServletTemplate extends HttpServlet {

Declaring a class Name of the class

Subclass the httpservlet class to create a servlet

Page 17: Chapter 3 servlet & jsp

public void doGet(HttpServletRequest request,

HttpServletResponse response)

You are overriding the doget method that comes from the httpservlet class

The parameter is a httpsevletrequest object

that you are naming request

The parameter is a httpsevletresponse object

that you are naming response

Page 18: Chapter 3 servlet & jsp

throws ServletException, IOException

You are declaring that the doget method can throw two

exceptions ServletException, IOException

Page 19: Chapter 3 servlet & jsp

Executing Servlet ProgramSetting Class path

1. My computer->Properties->Advance->Environment Variables->

Edit User VariableVariable name: pathVariable Value: C:\Program Files\Java\jdk1.5.0_03\bin;C:\Program Files\servlet.jar;

Edit System VariableVariable name: CLASSPATHVariable Value: C:\Program Files\Java\jdk1.5.0_03\bin;C:\Program Files\servlet.jar;%.%;

Page 20: Chapter 3 servlet & jsp

2. Running the servlet in cmd prompt C:\Documents and Settings\eec-cs>cd\ C:\>cd C:\Program Files\Apache Tomcat 4.0\webapps\examples\WEB-INF\classes C:\Program Files\Apache Tomcat 4.0\webapps\examples\WEB-INF\classes>javac HelloWorld.java C:\Program Files\Apache Tomcat 4.0\webapps\examples\WEB-INF\classes>

Page 21: Chapter 3 servlet & jsp

3. Start Tomcat

4. Open IE and type below link http://localhost:8080/examples/

servlet/HelloWorld

Page 22: Chapter 3 servlet & jsp

javax.servlet Package

The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.

The following table summarizes the core interfaces that are provided in this package.

All servlets must implement this interface or extend a class that implements the interface.

Page 23: Chapter 3 servlet & jsp

Reading Servlet Parameters

The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a client request

Page 24: Chapter 3 servlet & jsp

javax.servlet.http package

Classes

Page 25: Chapter 3 servlet & jsp

HttpServletRequest Interface

The HttpServletRequest interface enables a servlet to obtain information about a client request.

Page 26: Chapter 3 servlet & jsp

HttpServletResponse InterfaceThe HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.

Page 27: Chapter 3 servlet & jsp

HttpSession InterfaceThe HttpSession interface enables a servlet to

read and write the state information that is associated with an HTTP session.

Page 28: Chapter 3 servlet & jsp

HttpSessionBindingListener Interface

The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session.

Page 29: Chapter 3 servlet & jsp

Handling HTTP Requests and Responses

Servlets can be used for handling both the GET Requests and the POST Requests.

The HttpServlet class is used for handling HTTP GET / POST Requests as it has some specialized methods that can efficiently handle the HTTP requests.

These methods are: ◦ doGet( ) ◦ doPost( ) ◦ doPut( ) ◦ doDelete( ) ◦ doOptions( ) ◦ doTrace( ) ◦ doHead( )

Page 30: Chapter 3 servlet & jsp

An individual developing Servlets for handling HTTP Requests needs to override one of these methods in order to process the request and generate a response. The servlet is invoked dynamically when an end-user submits a form.

If Form method attribute value is GET, then doGet( ) method of servlet will be called, if method=”POST” doPost( ) method of servlet which is mentioned as action will be called.

Ex: <form action=”sampleServlet” method=”GET”>

In above example since method is GET, sampleServlet’s doGet( ) will be called.

Page 31: Chapter 3 servlet & jsp

Both doGet( ) and doPost( ) takes two arguments objects of HttpServletRequest and HttpServletResponse classes.

Ex: public void doGet(HttpServletRequest req,

HttpServletResponse res) throws ServletException, IOException

public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException

In above example req is an object of HttpServletRequest class which contains the incoming information (information passed by client program).

The res is an object of HttpServletResponse class which

contains the outgoing information (response back to client).

Page 32: Chapter 3 servlet & jsp

Getting request data

The request object of HttpServletRequest class contains the incoming request data sent by client program.

By using the following methods we can get the request parameter values.

Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request.

The parameters are stored as a set of name-value pairs. Multiple parameter values can exist for any given parameter name. The following methods of the ServletRequest interface are available to access parameters:

◦ getParameter ( ) ◦ getParameterNames ( ) ◦ getParameterValues ( )

Page 33: Chapter 3 servlet & jsp

getParameter ( ) method is used to access single value, takes name of input parameter as an argument and returns a string object.

Ex: String s=req.getParameter(“user”);

getParameterValues ( ) method is used to access multiple value entered by user in a client program, it takes name of input parameter as an argument and returns a array of string object.

Ex: String [ ] lang=req.getParameterValues (“language”);

Page 34: Chapter 3 servlet & jsp

When we want to access all the parameters of a form, we make use of Enumeration object and its methods as shown below.

Ex: Enumeration en; String pname; String pvalue; en = request.getParameterNames(); while (en.hasMoreElements()) { pname = (String) en.nextElement(); pvalue= request.getParameterValues(pname); for(int i=0;i<pvalue.length;i++) { out.println(pvalue[i]); } }

Page 35: Chapter 3 servlet & jsp

Cookies

Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting the same Web site or domain later.

To send cookies to the client, a servlet would create one or more cookies with the appropriate names and values via new Cookie(name, value).

A Cookie is created by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain whitespace or any of: [ ] ( ) = , " / ? @ : ;

Ex: Cookie userCookie = new Cookie("user", "uid1234");

Page 36: Chapter 3 servlet & jsp

The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse.

Cookie userCookie = new Cookie("user", "uid1234");

response.addCookie(userCookie);

Page 37: Chapter 3 servlet & jsp

The getXXX( ) method can be used to retrieve the attribute XXX of a cookie object, which returns the string value. For example getName( ) used to retrieve the name of a cookie.

The setXXX( ) method is used to set the value of XXX attribute of a cookie, which accepts the value as argument which need to be set.

Ex: c.setValue(“123”); It sets Value attribute of cookie c as 123.

Page 38: Chapter 3 servlet & jsp

Servlet-Sessions There are a number of problems that arise from the fact that HTTP

is a "stateless" protocol.

In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions.

This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce.

When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?

Page 39: Chapter 3 servlet & jsp

Servlets provide an outstanding technical solution: the HttpSession API.

“A session is created each time a

client requests service from a Java servlet. The servlet processes the request and responds accordingly, after which the session is terminated.”

Page 40: Chapter 3 servlet & jsp

JSP - Java Server Pages

Introduction

JSP is one of the most powerful, easy-to-use, and fundamental tools in a Web-site developer's toolbox.

JSP combines HTML and XML with Java servlet (server application extension) and JavaBeans technologies to create a highly productive environment for developing and deploying reliable, interactive, high-performance platform-independent Web sites.

JSP facilitates the creation of dynamic content on the server.

Page 41: Chapter 3 servlet & jsp

It is part of the Java platform's integrated solution for server-side programming, which provides a portable alternative to other server-side technologies, such as CGI.

JSP integrates numerous Java application technologies, such as Java servlet, JavaBeans, JDBC, and Enterprise JavaBeans.

It also separates information presentation from application logic and fosters a reusable component model of programming.

Page 42: Chapter 3 servlet & jsp

Advantages of JSP over Servlets

Servlet use println statements for printing an HTML document which is usually very difficult to use. JSP has no such tedious task to maintain.

JSP needs no compilation, CLASSPATH setting and packaging.

In a JSP page visual content and logic are seperated, which is not possible in a servlet.

There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages.

Usually with JSP, Java Beans and custom tags web application is simplified.

Page 43: Chapter 3 servlet & jsp

Fundamental JSP Tags JSP tags are an important syntax element of Java Server

Pages which start with "<%" and end with "%>" just like HTML tags. JSP tags normally have a "start tag", a "tag body" and an "end tag". JSP tags can either be predefined tags or loaded from an external tag library.

Fundamental tags used in Java Server Pages are classified into the following categories:-

Declaration tag Expression tag Directive tag Scriptlet tag Comments

Page 44: Chapter 3 servlet & jsp

Declaration tag

The declaration tag is used within a Java Server page to declare a variable or method that can be referenced by other declarations, scriptlets, or expressions in a java server page.

A declaration tag does not generate any output on its own and is usually used in association with Expression or Scriplet Tags.

Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration.

Syntax :- <%! Declaration %>Example: <%! int var = 1; %>

<%! int x, y ; %>

Page 45: Chapter 3 servlet & jsp

Expression tag

An expression tag is used within a Java Server page to evaluate a java expression at request time.

The expression enclosed between "<%=" and "%>" tag elements is first converted into a string and sent inline to the output stream of the response.

Syntax :- <%= expression %>Example: <%= new java.util.Date() %>

Page 46: Chapter 3 servlet & jsp

Directive tag

Directive tag is used within a Java Server page to specify directives to the application server .

The directives are special messages which may use name-value pair attributes in the form attr="value".

Syntax :- <%@directive attribute="value" %>

Page 47: Chapter 3 servlet & jsp

Where directive may be:

1. page: page is used to provide the information about it.

Example: <%@page language="java" %>

2. include: include is used to include a file in the JSP page.

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

3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags).

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

Page 48: Chapter 3 servlet & jsp

Scriptlet tag

A Scriptlet tag is used within a Java Server page to execute a java source code scriplet which is enclosed between "<%" and "%>" tag elements.

The output of the java source code scriplet specified within the Scriptlet tag is executed at the server end and is inserted in sequence with rest of the web document for the client to access through web browser.

Syntax :- <% java code %>

Page 49: Chapter 3 servlet & jsp

Comments Comments tag is used within a Java Server

page for documentation of Java server page code.

Comments surrounded with "<%/*" and "*/%" tag elements are not processed by JSP engine and therefore do not appear on the client side web document but can be viewed through the web browser’s "view source" option.

Syntax :- <%-- comment -- %>

Page 50: Chapter 3 servlet & jsp

Request String The browser generates a user request string whenever

the submit is selected. The User request string consists of the URL and the

query string.

http://localhost:8080/examples/test/reg.jsp?fname=“bob”&

lname=“smith”

The getParameter(name) is the method used to parse a value of a specified field.

<% string firstname = request.getParameter(fname) string lastname = request.getParameter(lname)

%>

Page 51: Chapter 3 servlet & jsp

User Sessions A JSP program must be able to track a

session as a client moves between HTML pages and JSP programs.

There are three commonly used methods to track a session.

1. Using Hidden Field2. Using Cookies3. Using JavaBean

Page 52: Chapter 3 servlet & jsp

Cookies Cookies is a small piece of information created by a JSP program that

is stored on the Client’s hard disk by the browser.

You can create and read a cookie by using methods of the cookie class and the response object.

Example: how to create a cookie

<HTML><HEAD><TITLE>JSP PROGRAMMING </TITLE></HEAD><BODY><%! String MyCookieName = “userId”; String MyCookieValue = “Jk12345”; Response.addCookie(new Cookie(MyCookieName, MyCookieValue));%></BODY></HTML>

Page 53: Chapter 3 servlet & jsp

HOW TO READ A COOKIE

<HTML> <HEAD> <TITLE> JSP Programming</TITLE></HEAD><BODY><%! String MyCookieName=“userID”; String MyCookieValue; String Cname,Cvalue; int found=0; Cookie[] cookies=request.getCookies(); for(int i=0;i<cookies.length;i++){ CName=cookies[i].getName(); CValue= cookie[i].getValue(); if(MyCookieName.equals(cookieNames[i])){ found=1; MyCookieValue=CookieValue; }} if(found==1){ %> <p> Cookie name =<% MYCookieName%></p> <p> Cookie Value=<% MyCookieValue %></p> <&}></BODY></HTML>

Page 54: Chapter 3 servlet & jsp

Session Objects

A JSP database system is able to share information among JSP programs within a session by using a session object.

Each time a session is created, a unique ID is assigned to the session and stored as a cookie