Servlets Class Declaration

cabbagewheatInternet και Εφαρμογές Web

13 Νοε 2013 (πριν από 3 χρόνια και 10 μήνες)

78 εμφανίσεις

Designing and Coding Servlets

Page 2/4


This section describes how to write a Servlet, and the decisions you have to make about
your application and the Servlets you place in it.

Servlets Class Declaration


To create a Servlet, write a public Java class
that includes basic I/O support as
well as the package
javax.servlet
. The class must extend either
GenericServlet

or
HttpServlet
. Since Servlets are mostly executed from
Browser which uses HTTP protocol, the latter is recommended


The following example hea
der shows the declaration of an HTTP Servlet called
Bank
Servlet
:


import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;


public class BankServlet extends HttpServlet {


servlet methods...

}


Overriding Methods



Next, you must override
one or more methods to provide instructions for the
servlet to perform its designated task.


All of the processing done by a Servlet on a request
-
by
-
request basis happens in
the service methods, either
service()
for generic Servlets or one of the
doOperati
on()

methods for HTTP Servlets. This method accepts the incoming
request, processes it according to the instructions you provide, and directs the
output appropriately. You can create other methods in a Servlet as well.


Business logic may involve accessing

a database to perform a transaction, or
passing the request to an EJB.

Overriding init



You can override the class initializer
init()
if you need to initialize or allocate
resources for the life of the Servlet instance, such as a counter. The
init()

meth
od runs after the servlet is instantiated but before it accepts any requests.
For more information, see the Servlet API specification.


Note that all
init()

methods must call
super.init(ServletConfig)

in
order to set their scope correctly. This makes the S
ervlets configuration object
available to the other methods in the servlet.


The following example
init()

method initializes a counter by creating a public
integer variable called
accessCount


public class BankServlet extends HttpServlet {


int accessCo
unt;



public void init (ServletConfig config) throws
ServletException {


super.init(config);


accessCount = 0;


}



Now other methods in the Servlet can access this variable.



Overriding destroy


You can override the class destructor
destroy()

to write log messages or to
release resources that would not be released through garbage collection. The
destroy()

method runs just before the servlet itself is deallocated from
memory. For more information, see the servlet API specification.



F
or example, the
destroy()
method could write a log message like this, based
on the example for
Overriding init

above:


out.println("BankServlet was accessed " + accessCount "
times.
\
n");

Overriding service, doGet, and doPost



When a request is made, Servl
et Engine hands the incoming data to the Servlet
engine, which processes the request, including form data, cookies, session
information, and URL name
-
value pairs, into an object of type
HttpServletRequest

called the request object. Client metadata is
encap
sulated as an object of type
HttpServletResponse

and is called the
response object. The Servlet engine passes both objects as parameters to the
Servlets
service()

method.


The default
service()

method in an HTTP servlet routes the request to another
method

based on the HTTP transfer method (POST, GET, etc.) For example,
HTTP POST requests are routed to the
doPost()

method, HTTP
GET
requests
are routed to the
doGet()

method, and so on. This enables the Servlet to
perform different processing on the request d
ata depending on the transfer
method. Since the routing takes place in
service()
, you generally do not
override
service()

in an HTTP Servlet. Instead, override
doGet()

and/or
doPost()
, etc., depending on the type of request you expect.


The automatic routi
ng in an HTTP Servlet is based simply on a call to
request.getMethod()
, which provides the HTTP transfer method. In Servlet
Engine, request data is already preprocessed into a name
-
value list by the time
the Servlet sees the data, so you could simply overr
ide the
service()

method
in an HTTP Servlet without losing any functionality. However, this does make the
Servlet less portable, since it is now dependent on preprocessed request data.


You must override the
service()

method (for generic Servlets) or the
d
oGet()

and/or

doPost()
methods (for HTTP servlets) to perform the tasks needed to
answer the request. Very often, this means accessing EJBs to perform business
transactions, collating the needed information (in the request object or in a JDBC
ResultSet obj
ect), and then passing the newly generated content to a JSP for
formatting and delivery back to the client.


Most operations that involve forms use either a GET or a POST operation, so for
most servlets you override either
doGet()

or
doPost()
. Note that yo
u can
implement both methods to provide for both types of input, or simply pass the
request object to a central processing method, as in the following example:



public void doGet (HttpServletRequest request,


HttpServletResponse response
)


throws ServletException, IOException {


doPost(request, response);

}



All of the actual request
-
by
-
request traffic in an HTTP Servlet is handled in the
appropriate
doOperation()

method, including session management, user
authentication, d
ispatching EJBs and JSPs, and accessing iAS features.


If you have a Servlet that you intend to also call using a
RequestDispatcher

method
include()

or
forward()

, be aware that the request information is no
longer sent as HTTP
POST
,
GET
, etc.
RequestDispa
tcher

methods always
call
service()
. In other words, if a servlet overrides
doPost()
, it may not
process anything if another servlet calls it, if the calling servlet happens to have
received its data via HTTP
GET
. For this reason, be sure to implement rout
ines
for all possible types of input, as explained above.

Note
Arbitrary binary data, like uploaded files or images, can be problematic,
since the web connector translates incoming data into name
-
value pairs by
default. You can program the web connector t
o properly handle this kind of data
and package it correctly in the request object. Accessing Parameters and Storing
Data

Incoming data is encapsulated in a request object. For HTTP servlets, the
request object is of type
HttpServletRequest
. For generic s
ervlets, the
request object is of type
ServletRequest
. The request object contains all the
parameters in a request, and you can also set your own values in the request.
The latter are called
attributes
.

You can access all the parameters in an incoming req
uest by using the
getParameter()

method. For example:

String username = request.getParameter("accountNumber");


You can also set and retrieve values in a request object using
setAttribute()

and
getAttribute()
, respectively. For example:

request.setAttrib
ute("
accountNumber", "3284766");


This reveals one way to transfer data to a JSP, since JSPs have access to the
request object as an implicit bean.


Maintaining Persistent Data using Servlets

Page 3/4


From the perspective of a web server or application
server, a web application is a series
of unrelated server hits. There is no automatic recognition that a user has visited the site
before, even if their last interaction was mere seconds before.

Handling Sessions

A session provides a context between multip
le user interactions by
"remembering" the application state. Clients identify themselves during each
interaction by way of a cookie, or, in the case of a cookie
-
less browser, by
placing the session identifier in the URL.


A session object can store objects
, such as tabular data, information about the
application's current state, and information about the current user. Objects bound
to a session are available to other components that use the same session.


Upon a successful login, you can direct a Servlet to

establish the user's identity in a
standard object called a session object that holds information about the current session,
including the user's login name and whatever other information you want to retain.
Application components can then query the sessi
on object to obtain authentication for the
user.

This example shows a Servlet accessing an EJB called BankingApp by creating
a handle to the account by casting the user's session ID as a account after
importing the accounts remote interface. The account nu
mber is stored in the
user's session.



import bank.BankingApp;




// Get the user's session and user details


HttpSession session = request.getSession(true);


BankingApp account =
(BankingApp)session.getValue(session.getId());



// If the user h
as no account, create a new one


if (account == null) {


account = new BankingApp();


session.putValue(session.getId(), account);


}



You can access EJBs from Servlets by using the Java Naming Directory
Interface (JNDI) to establish a ha
ndle, or proxy, to the EJB. You can then refer to
the EJB as a regular object; any overhead is managed by the bean's container.


This example shows the use of JNDI to look up a proxy for the shopping cart:

String jndiNm = "java:comp/env/ejb/BankingApp";

j
avax.naming.Context initCtx;

Object home;


try


{


initCtx = new javax.naming.InitialContext(env);


}


catch (Exception ex)


{


return null;


}


try


{


java.util.Properties props = null;


home = initCtx.lookup
(jndiNm);


}


catch(javax.naming.NameNotFoundException e)


{


return null;


}


catch(javax.naming.NamingException e)


{


return null;


}


try


{


IBankingApp account = ((IBankingAppHome)
home).create();



}

c
atch (...) {...}

Sending Response To Browser

Page 4/4


Now comes


the main part of sending back Response to the Browser. There are
Two ways you can send response back to Browser. If your Servlet involves very
less output, then you can display it directl
y from Servlet, else send the response
to a JSP page which will show the output.

Sending Response From Servlet

You can generate the output page within a servlet by writing to the output stream.
The recommended way to do this depends on the type of output.



You must always specify the output MIME type using
setContentType()

before any other output commences, as in this example:



response.setContentType("text/html");



For textual output, such as plain HTML, create a
PrintWriter

object and then
write to it
using
println
. For example:



PrintWriter output = response.getWriter();

output.println("Hello, World
\
n");



For binary output, you can write to the output stream directly by creating a
ServletOutputStream

object and then writing to it using
print()
. For
e
xample:



ServletOutputStream output = response.getOutputStream();

output.print(binary_data);



Note that your servlet can not call a JSP if you create a
PrintWriter

or
ServletOutputStream

object.


Sending Response From JSP


Servlets can invoke JSPs in two

ways:



The
include()

method in the
RequestDispatcher

interface calls a
JSP and waits for it to return before continuing to process the interaction.
The
include()

method can be called multiple times within a given
servlet.



This example shows a JSP invoca
tion using
include()
:


RequestDispatcher dispatcher =


getServletContext().getRequestDispatcher("JSP_PAGE_URL");

dispatcher.include(request, response);

... //processing continues





The
forward()

method in the
RequestDispatcher

interface hands
control of t
he interaction to a JSP. The servlet is no longer involved with
output for the current interaction after invoking
forward()
, thus only one
call to the
forward()

method can be made in a particular servlet. Note
that you can not use the
forward()

method if y
ou have already defined
a
PrintWriter

or
ServletOutputStream

object


This example shows a JSP invocation using
forward()
:



RequestDispatcher dispatcher =


getServletContext().getRequestDispatcher("JSP_PAGE_URL");

dispatcher.forward(request, response);



Note
You identify which JSP to call by specifying a URI (Universal Resource
Identifier). The path is a
String
describing a path within the scope of the
ServletContext
and must begin with a backslash ("/"). There is also a
getRequestDispatcher()

method in t
he Request Object that takes a
String

argument indicating a complete path. See the Java Servlet
Specification, v2.2 section 8 for more details about this method

What are JavaBeans ?

by
Faisal Khan
.

Overview

JavaBeans are usual Java classes which adhere to certain coding conventions. Following
are the coding conventions I am talking about :



Implements j
ava.io.Serializable interface



Provides no argument constructor



Provides getter and setter methods for accessing it's properties

Let's now create a simple JavaBean class.

A simple JavaBean class

Create a new SimpleBean.java file and place it in the /WEB
-
INF/classes/com/stardeveloper/bean/test/ folder so that the complete path is :

/WEB
-
INF/classes/com/stardeveloper/bean/test/SimpleBean.java

Now copy the following code and paste it into the SimpleBean.java file we created above
:

package com.stardeveloper.
bean.test;


public class SimpleBean implements java.io.Serializable {



/* Properties */


private String name = null;


private int age = 0;



/* Empty Constructor */


public SimpleBean() {}



/* Getter and Setter Methods */


public String getName() {



ret
urn name;


}



public void setName(String s) {



name = s;


}



public int getAge() {



return age;


}



public void setAge(int i) {



age = i;


}

}

Explanation

First line is the package statement :

package com.stardeveloper.bean.test;

Next we define our c
lass and make it implement java.io.Serializable interface. Notice that
Serializable interface doesn't contain any method. Implementing it just flags to the
compiler that we might be serializing this class's objects.

public class SimpleBean implements java.
io.Serializable {

Then we declare two variables which hold name and age of a person. These variables
inside a JavaBean are called as properties. These properties are private and are thus not
directly accessible by other classes. To make them accessible we
provide getter and setter
methods to get and set their values.

private String name = null;

private int age = 0;

Next we create an empty argument constructor. Keep in mind that the only requirement
to a JavaBean is an empty "argument" constructor, not that
you shouldn't use constructor
at all.

public SimpleBean() {}

Explanation

The convention for writing getter and setter methods for JavaBean's properties is really
simple. All you have to do is to take the property name e.g. name. Make it's first
character u
ppercase e.g. Name. Now append 'get' for getter method and 'set' for setter
method so that it becomes :

public String getName() {


return name;

}


public void setName(String s) {


name = s;

}

See! how easy it is. Since name variable is of type String, we s
et the return type of
getName() to String. Same is the case with setName() method which takes a parameter of
type String because name is of type String.

Next we added four getter and setter methods for private variables ( properties ) name
and age.

public
String getName() {


return name;

}


public void setName(String s) {


name = s;

}


public int getAge() {


return age;

}


public void setAge(int i) {


age = i;

}

Now close the class.

}

Compiling JavaBean

You will compile JavaBean like you will compile any ot
her Java class file. After
compilation, a SimpleBean.class file will be created.

We are now done with SimpleBean

Calling JavaBeans from a JSP Page

by
Faisal Khan
.

Overview

In the earlier article,
What are JavaBeans?
, we learned what are JavaBeans and we even
cr
eated a simple JavaBean class file; SimpleBean.

We will be using this SimpleBean class in this tutorial, so if you haven't read above
article then I suggest you do it now.

Before we continue to describe how to code a JSP page to call that JavaBean, let's f
irst
discuss the three JSP tags provided to us to make use of JavaBeans.

JSP JavaBean Tags

Following are the three tags :



<jsp:useBean>



<jsp:setProperty>



<jsp:getProperty>

Let us now study them one by one.

i. <jsp:useBean>

This tag is used to declare an
d instantiate the JavaBean class. It's syntax is as follows :

<jsp:useBean


id="object
-
name"


scope="page | request | session | application"


type="type
-
of
-
object"



class="fully
-
qualified
-
classname"


beanName="fully
-
qualified
-
beanName"

/>

Let us now see w
hat are the different attributes :



id
-

name of the object e.g.


String name = null;

In the above code, name is the 'id' we are talking about.



scope
-

an optional attribute by which you can control when your
JavaBean object will be destroyed. Default is
page, which means
every page view will create a new JavaBean.



type
-

type of the object which can be the same class, a super
class or an interface which the class implements. This parameter
is optional. e.g.


String name = "Faisal Khan";

In the above cod
e, String is the 'type' we are talking about.



class
-

a fully qualified class name e.g.


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

In the above code, java.util.
Date is the 'class' we are talking
about.



beanName
-

it is also fully qualified class name just like 'class'
attribute above. Only difference is that the class name in the
case of 'beanName' can be provided at request time.

ii. <jsp:setProperty>

This tag

is used to set the value of one or all the properties of given JavaBean. It's syntax
is as follows :

<jsp:setProperty


name="id
-
of
-
the
-
JavaBean"


property="name
-
of
-
property"


param="name
-
of
-
request
-
parameter
-
to
-
use"


value="new
-
value
-
of
-
this
-
property"

/>

Let us now see what the different attributes mean :



name
-

'id' of the <jsp:useBean> tag you set above.



property
-

name of the property whose value you want to set.



param
-

name of the request paramter you want to use to set
the value of this property.



value
-

the new value you want to set for this property.

iii. <jsp:getProperty>

This tag is used to retrieve the value of a given property from the given JavaBean. It's
syntax is as follows :

<jsp:getProperty


name="name
-
of
-
the
-
object"


property="name
-
of
-
property"

/>

Let us see what are the different attributes for this tag :



name
-

'id' of the <jsp:useBean> tag we set above.



property
-

name of the property whose value you want to
retrieve.

We are now finished studying the JSP tags provided to manipulate

JavaBeans. Let's just
spend a few minutes studying what is scope attribute we discussed in <jsp:useBean> tag.

Object Scope

Every JavaBean class object or any other class object we create will have a scope. Scope
means the length of time this object will r
emain in memory. There are four kinds of
scopes :



page
-

it means a new object will be created and destroyed for
every page view. This is the default for <jsp:useBean> tag when
you don't explicitly give it any.



request
-

it means the newly created object
will be created and
bound to the request object. It is used in different JSP
architectures

we will study later when we have covered all the
basic topic
s of JSP pages.



session
-

the newly created object will be bound to the session
object. What this means is that every visitor coming to your site
will have a separate session for it, so you will not have to create
a new object every time for it. You can j
ust retrieve that object
later again from the session object when you want it.



application
-

an object bound to application object means that
your object will stay as long as the application remains loaded.
This can be useful when for instance you want to

count page
views or daily sessions for your site.



To learn more about using sessions in Java Servlets, please read
Managing Sessions with Java Servlets
.

Ok, we have now stu
dies all the three tags for JavaBeans manipulation and also studied
briefly what are the different object scopes and what they mean to us.

Let us now move forward on the next page where we code our SimpleBean.jsp JSP page
which will call this JavaBean, set

new values for it's parameters and then display the
values of these parameters to the user.

SimpleBean.jsp JSP page

Create a new SimpleBean.jsp page and place it in the /WEB
-
APP folder. WEB
-
APP is
the complete path to your
web

application e.g. C:
\
yoursite, then place SimpleBean.jsp
page in C:
\
yoursite
\
SimpleBean.jsp. Remember, never put JSP pages in /WEB
-
INF/
folder.

Now copy the following code and past
e it into the SimpleBean.jsp page above :

<html>

<head>


<title>SimpleBean Test Page</title>

</head>

<body>


<%
--

Creating JavaBeans
--
%>

<jsp:useBean id="simple" class="com.stardeveloper.bean.test.SimpleBean">


<jsp:setProperty name="simple" property="nam
e" value="Faisal Khan" />


<jsp:setProperty name="simple" property="age" value="24" />

</jsp:useBean>


<%
--

Displaying JavaBean property's value
--
%>

<p>Name retrieved from JavaBean has the value of :


<b><jsp:getProperty name="simple" property="name" /><
/b>.<br>

Age retrieved from JavaBean has the value of :


<b><jsp:getProperty name="simple" property="age" /></b> years.<br>

</p>


</body>

</html>

Explanation

Above code is a simple JSP page which makes use of all the three JavaBean tags we
discussed earlie
r. First we create a new JavaBean object for our SimpleBean class by
using <jsp:useBean> tag :

<jsp:useBean id="simple" class="com.stardeveloper.bean.test.SimpleBean">

Then we use <jsp:setProperty> tag to set different values for both the name and age
prop
erties of our SimpleBean class.


<jsp:setProperty name="simple" property="name" value="Faisal Khan" />


<jsp:setProperty name="simple" property="age" value="24" />

We then close the <jsp:useBean> tag.

</jsp:useBean>

Next we display the values of these prop
erties using the <jsp:getProperty> tag twice.

<jsp:getProperty name="simple" property="name" /></b>.<br>

<jsp:getProperty name="simple" property="age" /></b>.<br>