0% found this document useful (0 votes)
8 views21 pages

Java m4

This document provides an overview of Servlets and Java Server Pages (JSP), detailing their life cycles, advantages, and the use of Tomcat for development. It explains key components such as the Servlet API, handling HTTP requests and responses, session tracking, and cookies. Additionally, it covers JSP tags, variables, and methods, highlighting the differences between JSP and servlets in terms of simplicity and structure.

Uploaded by

astitvarajfbg
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views21 pages

Java m4

This document provides an overview of Servlets and Java Server Pages (JSP), detailing their life cycles, advantages, and the use of Tomcat for development. It explains key components such as the Servlet API, handling HTTP requests and responses, session tracking, and cookies. Additionally, it covers JSP tags, variables, and methods, highlighting the differences between JSP and servlets in terms of simplicity and structure.

Uploaded by

astitvarajfbg
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ADVANCED JAVA BIS402

Module 4
Introducing Servlets & Java Server Pages
Introducing servlets: Background; The Life Cycle of a Servlet; Using
Tomcat for Servlet Development; A simple Servlet; The Servlet API; The
Jakarta. Servlet Package; Reading Servlet Parameter; The
[Link] package; Handling HTTP Requests and Responses;
Using Cookies; Session Tracking.
Java Server Pages (JSP); JSP tags, Variables and Objects, Methods, Control
statements, Loops, Request String, Parsing other information, User
sessions, Cookies, Session Objects.

➢ Servlets are small programs that execute on the server side of a web
connection.
Background
➢ Consider a request for a static web page.
➢ A user enters a Uniform Resource Locator (URL) into a browser.
➢ The browser generates an HTTP request to the appropriate web server.
➢ The web server maps this request to a specific file.
➢ That file is returned in an HTTP response to the browser.
➢ The HTTP header in the response indicates the type of the content.

Advantages of Servlets

1) Performance is better as they execute within web server.


2) Servlets are platform-independent because they are
written in Java.
3) Java security manager on the server enforces a set of
restrictions to protect the resources on a server machine.
4) Full functionality of the Java class libraries is available to a servlet.

5
ADVANCED JAVA BIS402

The Life Cycle of a Servlet *

1) User enters URL to browser and an HTTP request for this URL is
generated. This request is then sent to the appropriate server.
2) This HTTP request is received by the web server and particular servlet
is dynamically retrieved and loaded into the address space of the server.
3) The server invokes the init( ) method of the servlet. This method is
invoked only when the servlet is first loaded into memory. Here
initialization parameters to the servlet can be passed for configuration.
4) The server then invokes the service( ) method of the [Link] method
is called to process the HTTP requests.
Servlet reads data that has been provided in the HTTP request and
formulates an HTTP response.
5) The server may decide to unload the servlet from its memory in the end.
The server calls the destroy() method to relinquish any resources such
as file handles.

6
ADVANCED JAVA BIS402

Using Tomcat
Tomcat contains the class libraries, documentation, and run-time support
that is required to create and test servlets.

A Simple Servlet**
The basic steps in building and testing a simple servlet:
1. Create and compile the servlet source code. Then, copy the servlet’s class
file to the proper directory, and add the servlet’s name and mappings to the
proper [Link] file.
2. Start Tomcat.
3. Start a web browser and request the servlet.

Eg: A simple servlet code

➢ [Link] package - This package contains the classes and


interfaces required to build servlets.
➢ The program defines HelloServlet as a subclass of GenericServlet. The
GenericServlet class provides functionality that simplifies the creation
of a servlet.
For example, it provides versions of init( ) and destroy( ), which may
be used as is. Only the service( ) method needs to be coded.
➢ The first argument is a ServletRequest object. This enables the servlet
to read data that is provided via the client request.
➢ The second argument is a ServletResponse object. This enables the
servlet to formulate a response for the client.

7
ADVANCED JAVA BIS402

➢ The call to setContentType( ) establishes the MIME(Multipurpose


Internet Mail Extension) type of the HTTP response. In this program,
the MIME type is text/html. This indicates that the browser should
interpret the content as HTML source code.
➢ The getWriter( ) method obtains a PrintWriter. Anything written to this
stream is sent to the client as part of the HTTP response.
➢ println( ) is used to write some simple HTML source code as the HTTP
response

The Servlet API*


Consists of [Link] and [Link]
[Link]

- contains a number of interfaces and classes

The Servlet Interface


- All servlets must implement the Servlet interface.

8
ADVANCED JAVA BIS402

The ServletConfig Interface


The ServletConfig interface allows a servlet to obtain configuration data
when
it is loaded.

The ServletContext Interface


The ServletContext interface enables servlets to obtain information about
their
environment.

The ServletRequest Interface


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

9
ADVANCED JAVA BIS402

The ServletResponse Interface


The ServletResponse interface enables a servlet to formulate a response for
a
client.

The GenericServlet Class


- The GenericServlet class provides implementations of the basic life cycle
methods for a servlet. GenericServlet implements the Servlet and
ServletConfig interfaces.

10
ADVANCED JAVA BIS402

- A method to append a string to the server log file is available.


void log(String s)
void log(String s, Throwable e)

‘s’ is the string to be appended to the log, and ‘e’ is an exception that
Occurred

The ServletInputStream Class


- This class extends InputStream.
- Provides an input stream that a servlet developer can use to read the
data from a client request.
- A method is provided to read bytes from the stream
int readLine(byte[ ] buffer, int offset, int size) throws IOException

The ServletOutputStream Class


- The ServletOutputStream class extends OutputStream.
- It also defines the print( ) and println( ) methods, which output data to
the stream.

The Servlet Exception Classes


[Link] defines two exceptions.
- The first is ServletException, which indicates that a servlet problem
has occurred.
- The second is UnavailableException, which extends ServletException
indicating that a servlet is unavailable.

Reading Servlet Parameters***

The below example contains two files. A web page is defined in


[Link], and a servlet is defined in
[Link].

➢ The ServletRequest interface includes methods that allow you to read


the names and values of parameters that are included in a client
request.

11
ADVANCED JAVA BIS402

12
ADVANCED JAVA BIS402

Steps
➢ Compile the Servlet.
➢ Update the [Link] file with appropriate server name.
➢ Start Tomcat (if it is not already running).
➢ Display the web page in a browser.
➢ Enter an employee name and phone number in the text fields.
➢ Submit the web page.

The [Link] Package

The HttpServletRequest Interface


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

13
ADVANCED JAVA BIS402

The ServletResponse Interface


The ServletResponse interface enables a servlet to formulate a response for
a client.

14
ADVANCED JAVA BIS402

The HttpSession Interface


The HttpSession interface enables a servlet to read and write the state
information that is associated with an HTTP session.

15
ADVANCED JAVA BIS402

The Cookie Class*


- The Cookie class encapsulates a cookie.
- A cookie is stored on a client and contains state information. Cookies are
valuable for tracking user activities.
- For example, assume that a user visits an online store. A cookie can save
the user’s name, address, and other information. The user does not need to
enter this data each time he or she visits the store.
- A servlet can write a cookie to a user’s machine via the addCookie( ) method
of the HttpServletResponse interface.
- The data for that cookie is then included in the header of the HTTP response
that is sent to the browser.
- Information stored in browser
- The domain and path of the cookie determine when it is included in the
header of an HTTP request.
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie

Cookie Constructor
Cookie(String name, String value)

16
ADVANCED JAVA BIS402

The HttpServlet Class


The HttpServlet class extends GenericServlet. It is commonly used when
developing servlets that receive and process HTTP requests.

Handling HTTP Requests and Responses

- The HttpServlet class provides specialized methods that handle the


various types of HTTP requests.
- A servlet developer overrides one of these methods. These methods are
doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and
doTrace( ).
Handling HTTP GET Requests
The example contains two files. A web page is defined in
[Link], and a servlet is defined in [Link].

17
ADVANCED JAVA BIS402

[Link]

[Link]

Compile the servlet. Next, copy it to the appropriate directory, and update
the [Link] file, as previously described. Then, perform these steps to test
this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit the web page.

18
ADVANCED JAVA BIS402

Handling HTTP POST Requests


The HTML source code for [Link] is same as [Link]
except that the method parameter for the form tag explicitly specifies POST
method instead of GET method.

The source code for [Link] is shown in the following


listing. The doPost( ) method is overridden to process any HTTP POST
requests that are sent to this servlet.

19
ADVANCED JAVA BIS402

Using Cookies

Servlet which uses Cookies to be developed. The servlet is invoked when a


form on a web page is submitted.

[Link]

- When button is pressed, text field value is passed to the


AddCookieServlet.
- This java file gets the parameter value passed from user and passes it
to a Cookie object created. This cookie is then added to the header of
the HTTP response using addCookie() method.

Session Tracking*

- HTTP is a stateless protocol


- Each request is independent of the previous one
- A session is used to collect state information.

Program to collect session of the browsing

20
ADVANCED JAVA BIS402

Java Server Pages


- Java Server Pages (JSP) is a server-side program that is similar in
design and functionality to a Java servlet.

- A JSP is called by a client to provide a web service.

- A JSP differs from a Java servlet in the way in which the JSP is
written

- A JSP is simpler to create than a Java servlet because a JSP is written


in HTML rather than Java programming Language.

- There are three methods that are automatically called when a JSP is
requested and when the JSP terminates.

- jsplnt() method : called first when the JSP is requested and is used to
initialize objects and variables that are used throughout the life of the
JSP.

21
ADVANCED JAVA BIS402

- jspDestroy() method: is automatically called when the JSP


terminates normally

- service() method: is automatically called and retrieves a connection


to HTTP.

JSP Tags***
- A JSP program consists of a combination of HTML tags and JSP tags.

- A JSP tag begins with a <%, which is followed by Java code, and ends
with %>.

- JSP tags are embedded into the HTML component of a JSP program
and are
processed by a JSP virtual engine such as Tomcat

- There are 5 types of JSP tags that you'll use in a JSP program
➢ Comment tag A comment tag opens with <%-- and closes with --%>,
and is
followed by a comment that usually describes the functionality of
statements
that follow the comment tag.

➢ Declaration statement tags: A declaration statement tag opens with


<%! and is followed by a Java declaration statement(s) that define
variables, objects, and methods that are available to other components
of the JSP program .

➢ Directive tags: A directive tag opens with <%@ and commands the JSP
virtual engine to perform a specific task, such as importing a Java
package required by objects and methods used in a declaration
statement. The directive tag close with %>. There are three commonly
used directives. These are import, include, and taglib.

- The import tag is used to import Java packages into the JSP program.
Eg: <%@ page import=" import java . sql.* "; %>

The first tag imports the [Link] package.

- The include tag inserts a specified file into the JSP program replacing
the include tag.

22
ADVANCED JAVA BIS402

Eg: <%@ include ftle="keogh\[Link]" %>

This tag includes the [Link] file located in the keogh directory

- The taglib tag specifies a file that contains a tag library.


Eg: <%@ taglib uri= "rnyTags. tld" %>

And the last tag loads the Tags. tld library.

➢ Expression tags An expression tag opens with <%= and is used for an
expression statement whose result replaces the expression tag when
the JSP virtual engine resolves JSP tags. An expression tags closes
with %> .

➢ Scriptlet tags A scriptlet tag opens with <% and contains commonly
used Java control statements and loops. A scriptlet tag closes with
%>.

Variables and Objects


Declaring a variable

<HTML>
<HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD>
<BODY>
<%! int age=29; %>
<P> Your age is: <%=age%> </P>
</BODY>
< /HTML>

Declaring multiple variables

<HTML>
<HEAD>
<TI'I'LE> JSP Programming < / TI'rLE>
</HEAD>
<BODY>
<% ! int age=29;
float salary;
int empnurnber ;
%>
</ BODY>
</ HTML>

23
ADVANCED JAVA BIS402

Declaring Objects and arrays within a single tag

<HTML>
<HEAD>
<TITLE> JSP Programming </ TITLE>
</ HEAD>
<BODY>
<%! String Name;
String[ ] Telephone= { "2 01 -555-1212 ", "201-555 - 44 33 " } ;
String Company = new String () ;
Vector Assignments= new Vector() ;
int[ ] Grade= {100, 82 ,93};
%>
</ BODY>
</ HTML>

Calling Methods*

<HTML>
<HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD>
<BODY>
<%!
int curve (int grade)
{ return 10 + grade; }
%>
<P> Your curved grade is : <%= curve(80) %> </P>
</BODY>
< / HTML>

Using Control statements*

<HTML>
<HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD>
<BODY>
<% ! int grade=70;%>

<% if (grade > 69) { %>


<P> You passed! </ P>
<%} else { %>
<P> Better luck next time. </P>
<%} %>
<% switch (grade) {

24
ADVANCED JAVA BIS402

case 90 : %>
<P> Your final grade is a A </P>
<% break;
case 80 : %>
<P> Your final grade is a B </P>
<% break;
case 70 : %>
<P> Your final grade is a C </P>
<% break;
case 60 : %>
<P> Your final grade is an F </P>
<% break ;
}
%>
</ BODY> </HTML>
Request String

- The browser generates a user request string whenever the Submit


button is selected.

- The user request string consists of the URL and the query string.

- The getParameter() method requires an argument, which is the name


of the field whose value you want.

-
- 4 predefined objects in JSP program

* request: Instance of HttpServletRequest


* response: Instance of HttpServletResponse
* session: Instance of HttpSession
* out: Instance of JspWriter

- Request string consists of 2 parts separated by question mark.

25

You might also like