Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
62 views44 pages

Servelets JSPs

Servlets are Java programs that run on web servers and act as a middle layer between client requests and backend applications or databases. They read request data from clients, generate responses by accessing databases or making backend calls, and send responses back to clients. JSPs are similar to servlets but use HTML tags with embedded Java code to generate dynamic web page content on the server side. Both servlets and JSPs allow for dynamic request processing and content generation on the web.

Uploaded by

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

Servelets JSPs

Servlets are Java programs that run on web servers and act as a middle layer between client requests and backend applications or databases. They read request data from clients, generate responses by accessing databases or making backend calls, and send responses back to clients. JSPs are similar to servlets but use HTML tags with embedded Java code to generate dynamic web page content on the server side. Both servlets and JSPs allow for dynamic request processing and content generation on the web.

Uploaded by

Chayma Charrada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Servelets & JSPs

Introduction
• Servlets are Java programs
• Run on
• Web servers
• Application servers
• Act as a middle layer between requests coming from clients and
databases or applications on the HTTP server.
• A client could be :
• A Web browser
• Other HTTP client
• Their job is to perform the following tasks, as illustrated in Figure
1
Steps description
1. Read the explicit data sent by the client.
• From an HTML form on a Web page.
• From an applet
• From a custom HTTP client program.
2. Read the implicit HTTP request data sent by the
browser.
HTTP information includes :
• cookies,
• information about media types and compression schemes the
browser understands, etc
5. Send the implicit HTTP response data.
There are really two varieties of data sent:
• The document itself
• HTTP information (Cookies, Caching parameters, etc)
3. Generate the results.
• By talking to a database (browser can’t talk directly to the database or for security reasons)
• Executing an RMI or EJB call,
• Invoking a Web service,
• Computing the response directly.

So the Web middle layer extracts the incoming data from the HTTP stream, talk to the
application and embed the results inside a document.

4. Send the explicit data (i.e., the document) to the


client.
This document can be sent in a variety of formats :
• Text (HTML (is by far the most common format)
• Text (XML),
• Binary (GIF images),
• A compressed format like gzip that is layered on top of some other
underlying format.
An important servlet/JSP task is to wrap the results inside of HTML.
Four Points for Servlets

It is regular Java code. There are new APIs, but no new syntax.

It has unfamiliar import statements. The servlet and JSP APIs are
not part of J2SE; they are a separate specification (and are also part
of the J2EE).

It overrides the doGet method. Servlets have different


methods to respond to different types of HTTP
commands.

It extends a standard class (HttpServlet). Servlets provide a rich


infrastructure for dealing with HTTP.
Sample servlet code
Main methods
• doDelete(HttpServletRequest req, HttpServletResponse resp),
• doGet(HttpServletRequest req, HttpServletResponse resp), qui traite les requêtes HTTP GET. Cette
méthode traite également les requêtes de type HEAD, qui renvoient uniquement l'en-tête de la réponse.
Les requêtes de type HEAD peuvent être utilisées par les navigateurs pour déterminer si les données
qu'ils détiennent sont à jour ou non.
• doOptions(HttpServletRequest req, HttpServletResponse resp), qui traite les requêtes HTTP OPTIONS.
• doPost(HttpServletRequest req, HttpServletResponse resp), qui traite les requêtes HTTP POST.
• doPut(HttpServletRequest req, HttpServletResponse resp), qui traite les requêtes HTTP PUT.
• doTrace(HttpServletRequest req, HttpServletResponse resp), qui traite les requêtes HTTP TRACE.
• getLastModified(HttpServletRequest req), qui renvoie la date et l'heure de la dernière modification de
l'objet req, permettant ainsi à un navigateur de savoir si l'objet qu'il possède en cache est à jour ou non.
• service(HttpServletRequest req, HttpServletResponse resp), qui reçoit les requêtes HTTP et les
distribue aux méthodes intéressées, en fonction de leur type.
JSPs
JSP Servlet
HTML pages with Java code Java programs with HTML
embedded inside of them. embedded inside of them.
A normal HTML page A regular Java class

A JSP document is just another way of


writing a servlet

JSP pages get translated into servlets, the servlets get compiled, and it is the
servlets that run at request time.
A JSP page
User Inputs and Form Data
• URLs like http://host/path?user=Marty+Hall&origin=bwi&dest=sfo.
• The part after the question mark is known as form data (or query data) and is the most common way to get
information from a Web page to a server-side program.
• Form data can be attached to the end of the URL after a question mark (as above) for GET requests; form data can
also be sent to the server on a separate line for POST requests.
Example:
<FORM ACTION="...">...</FORM>
If ACTION is omitted, the data is submitted to the URL of the current page.
Input elements to collect user data :
<INPUT TYPE="TEXT" NAME="...">
A submit button
<INPUT TYPE="SUBMIT">
• When the button is pressed, the URL designated by the form’s ACTION is invoked.
• With GET requests, a question mark and name/value pairs are attached to the end of the URL, where the names come from the NAME
attributes in the HTML input elements and the values come from the end user.
• With POST requests, the same data is sent, but on a separate request line instead of attached to the URL.
Reading Form Data from Servlets
• request.getParameter to get the value of a form parameter
• request.getParameterValues if the parameter appears more than once,
• request.getParameterNames if you want a complete list of all parameters in the current request.

• Reading Single Values: getParameter


• To read a request (form) parameter, you simply call the getParameter method of HttpServletRequest,
supplying the case-sensitive parameter name as an argument.
• You supply the parameter name exactly as it appeared in the HTML source code, and you get the result
exactly as the end user entered it; any necessary URL-decoding is done automatically.
• Unlike the case with many alternatives to servlet technology, you use getParameter exactly the same way
when the data is sent by GET (i.e., from within the doGet method) as you do when it is sent by POST (i.e.,
from within doPost); the servlet knows which request method the client used and automatically uses the
appropriate method to read the data.
• An empty String is returned if the parameter exists but has no value, and null is returned if there was
no such parameter.
• Parameter names are case sensitive so, for example, request.getParameter("Param1") and
request.getParameter("param1") are not interchangeable.
• Looking Up Parameter Names: getParameterNames and getParameterMap
Note that Enumeration is an interface that merely guarantees that the actual class will have
hasMoreElements and nextElement methods: there is no guarantee that any particular underlying data
structure will be used. And, since some common data structures (hash tables, in particular) scramble the
order of the elements, you should not count on getParameterNames returning the parameters in the
order in which they appeared in the HTML form.
Automatically Populating Java Objects from RequestParameters: FormBeans

It is possible, in JSP, to use the JavaBeans component architecture to greatly simplify


the process of reading request parameters, parsing the values, and storing the results
in Java objects.
An ordinary Java object is considered to be a bean if the class uses private fields and has
methods that follow the get/set naming convention.
The names of the methods (minus the word “get” or “set” and with the first character in
lower case) are called properties. For example, an arbitrary Java class with a getName
and setName method is said to define a bean that has a property called name.
JSP
• JavaServer Pages (JSP) technology enables you to mix regular, static HTML with
dynamically generated content. You simply write the regular HTML in the normal
manner, using familiar Web-page-building tools.
• You then enclose the code for the dynamic parts in special tags, most of which start
with <% and end with %>.
JSP syntax
Types of JSP Scripting Elements
JSP scripting elements let you insert Java code into the servlet that
will be generated from the JSP page.
There are three forms:
1. Expressions of the form <%= Java Expression %>, which are
evaluated and inserted into the servlet’s output.
2. Scriptlets of the form <% Java Code %>, which are inserted
into the servlet’s _jspService method (called by service).
3. Declarations of the form <%! Field/Method Declaration %>, which
are inserted into the body of the servlet class, outside any existing
methods.
JSPJSPsyntax
Expression
Example:
<%= Java Value %> Current time: <%= new java.util.Date() %>

JSP Scriptlet
Example:
<% Java Statement %>

JSP Declaration
Examples:
• <%! Field Definition %>
• <%! Method Definition %>

JSP Directive
Description:
High-level information about the structure of the servlet code (page), code that is included at page-
translation time (include), or custom tag libraries used (taglib)
JSP Directives
A JSP directive affects the overall structure of the servlet that results from the JSP
page.
The following templates show the two possible forms for directives :
<%@ directive attribute="value" %>
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>

In JSP, there are three main types of directives:


• Page : controls the structure of the servlet by importing classes, customizing the servlet superclass, setting
the content type, and the like
• Include : inserts a file into the JSP page at thetime the JSP file is translated into a servlet
• Taglib : defines custom markup tags
The page directive

To define one or more of the following case-sensitive attributes :


• import,
• contentType,
• pageEncoding,
• session,
• isELIgnored (JSP 2.0 only),
• buffer,
• autoFlush,
• info,
• errorPage,
• isErrorPage,
• isThreadSafe,
• language,
• extends
The import attribute of the page directive allows specifying the packages that should be
imported by the servlet into which the JSP page gets translated.
Using utility classes  they should always be in packages.
By default, the servlet imports java.lang.*, javax.servlet.*, javax.servlet.jsp.*,
javax.servlet.http.*, and possibly some number of server-specific entries.

Never write JSP code that relies on any server-specific classes being imported
automatically; doing so makes your code nonportable.

• Use of the import attribute takes one of the following two forms:
• <%@ page import="package.class" %>
• <%@ page import="package.class1,...,package.classN" %>

Example :
<%@ page import="java.util.*" %>
The import attribute is the only page attribute that is allowed to appear multiple times within
the same document.
The page uses three classes:
• <%@ page import="java.util.*,coreservlets.*" %>
The contentType attribute sets the Content-Type response header, indicating the MIME
type of the document being sent to the client.
Use of the contentType attribute takes one of the following two forms:
• <%@ page contentType="MIME-Type" %>
• <%@ page contentType="MIME-Type; charset=Character-Set" %>
For example, the directive
<%@ page contentType="application/vnd.ms-excel" %> has the same basic effect as the scriptlet
<% response.setContentType("application/vnd.ms-excel"); %>

Unlike regular servlets, for which the default MIME type is text/plain, the default for JSP
pages is text/html (with a default character set of ISO-8859-1).

• <%@ page contentType="someMimeType; charset=someCharacterSet" %>


only want to change the character set
For example, Japanese JSP pages might use the following
• <%@ page pageEncoding="Shift_JIS" %>
• Generating Excel:
Example:
• <%@ directive att="val" %>

JSP Action
Description:
• Action that takes place when the page is requested
Example:
• jsp:include
• jsp:useBean
• jsp:invoke
JSP Expression Language Element
Description:
Shorthand JSP expression
Example:
• ${ EL Expression }
Custom Tag (Custom Action)
Description:
Invocation of custom tag
Example:
<prefix:name>
Body
</prefix:name>

Escaped Template Text


Description:
Text that would otherwise be interpreted specially. Slash is removed and remaining text is sent to the client
Examples:
<\%
%\>
The extends attribute designates the superclass of the servlet that will be generated for the JSP page. It
takes the following form.
<%@ page extends="package.class" %>

XML Syntax for Directives


If you are writing XML-compatible JSP pages, you can use an alternative XML-compatible syntax for
directives as long as you don’t mix the XML syntax and the classic syntax in the same page.
These constructs take the following form:
• <jsp:directive.directiveType attribute="value" />
• For example, the XML equivalent of
• <%@ page import="java.util.*" %>
• is
• <jsp:directive.page import="java.util.*" />
Including external pieces into a JSP document

Three main capabilities :


• The jsp:include action:
• Includes the output of a page at request time.
• The include directive:
• Inserts JSP code into the main page before that main page is translated into a servlet. Its main
advantage is that it is powerful: the included code can contain JSP constructs such as field definitions
and content-type settings that affect the main page as a whole

• The jsp:plugin action:


• The jsp:plugin element is used to insert applets that use the Java Plug-in into JSP pages.
Forwarding Requests with jsp:forward

jsp:include is used to combine output from the main page and the auxiliary page.
Instead, jsp:forward is used to obtain the complete output from the auxiliary page.

Example:
<% String destination;
if (Math.random() > 0.5) {
destination = "/examples/page1.jsp";
} else {
destination = "/examples/page2.jsp";
}
%>
<jsp:forward page="<%= destination %>" />
USING JAVABEANS COMPONENTS IN JSP DOCUMENTS

Beans are merely regular Java classes that follow some simple conventions defined by the JavaBeans
specification (a standard format); beans extend no particular class, are in no particular package, and use
no particular interface.
Advantages :
1. No Java syntax: By using beans, page authors can manipulate Java objects using only XML-compatible
syntax: no parentheses, semicolons, or curly braces. This promotes a stronger separation between the
content and the presentation and is especially useful in large development teams that have separate Web
and Java developers.
2. Simpler object sharing : When you use the JSP bean constructs, you can much more easily share objects
among multiple pages or between requests than if you use the equivalent explicit Java code.
3. Convenient correspondence between request parameters and object properties. The JSP bean
constructs greatly simplify the process of reading request parameters, converting from strings, and
putting the results inside objects.
Rules for developping beans
• A bean class must have a zero-argument (default) constructor
• A bean class should have no public instance variables (fields) (use of accessor Methods)
• Persistent values should be accessed through methods called get Xxx and setXxx:
Standard JSP actions for accessing beans can only make use of methods that use the get Xxx/setXxx or
isXxx/ setXxx naming convention.
Using Beans: Basic Tasks
Three main constructs to build and manipulate JavaBeans components in JSP pages:
• jsp:useBean. In the simplest case, this element builds a new bean.
It is normally used as follows:
<jsp:useBean id="beanName“ class="package.Class" />

This statement usually means “instantiate an object of the class specified by


Class, and bind it to a variable in _jspService with the name specified by id.”
Note, however, that you use the fully qualified class name—the class name with packages included.
This requirement holds true regardless of whether you use <%@ page import... %> to import
packages.
• jsp:getProperty. This element reads and outputs the value of a bean property. Reading a property
is a shorthand notation for calling a method of the form getXxx.
This element is used as follows:
<jsp:getProperty name="beanName“ property="propertyName" />
• jsp:setProperty. This element modifies a bean property (i.e., calls a method of the form setXxx).
It is normally used as follows:
<jsp:setProperty name="beanName“ property="propertyName“ value="propertyValue" />
The following subsections give details on these elements.
• jsp:useBean Options:
• scope: associates the bean with more than just the current page
• beanName: attribute passed to instantiate method of java.beans.Bean instead of class attribute
• Type : to precise the super class of the object

Accessing Bean Properties:


jsp:getProperty
Once you have a bean, you can output its properties with jsp:getProperty, which takes a
name attribute that should match the id given in jsp:useBean and a property attribute that
names the property of interest.
Setting Simple Bean Properties: jsp:setProperty

To modify bean properties, you normally use jsp:setProperty.


This action has several different forms, but with the simplest form you supply three
attributes: name (which should match the id given by jsp:useBean), property (the name
of the property to change), and value (the new value).
JavaBeans vs.
• JavaBeans has been Enterprise JavaBeans
at the center of many new paradigms and
technologies that have emerged since its inception.
• Among emerging technologies, Enterprise JavaBeans has generated
tremendous interest in the business computing community.
• However, a common misconception is that an Enterprise JavaBean is
an extension of a "plain vanilla" JavaBean with enterprise functionality.
While both JavaBeans and Enterprise JavaBeans are software
component models, their purpose is different:
• A JavaBean is a general-purpose component model,
• whereas EJB, as the name suggests, is a component model that is enterprise
specific.
• Even though these models have entirely different architectures, they adhere
to certain underlying principles that generally govern a software component
model.

• We'll use these principles and the basic


characteristics of software components to
compare JavaBeans and Enterprise JavaBeans.
Basic characteristics of software components

• Goals
The underlying theme of both JavaBeans and Enterprise JavaBeans is, as Sun puts it,
"Write once, run anywhere" (WORA).
Accordingly, the primary objective of both models is to ensure :
• portability,
• reusability of Java software components.
• Interoperability

You might also like