What is Enterprise Computing
Software applications are executed on network environments such as LAN and WANs.
Enterprise Application consists of number of layers such as
Data Layer
Business Layer
Presentation Layer
Data layer consists of data store and it stores on server computer.
Presentation layer consists of user interfaces and it store on client computers.
Business layer consists of business logic and it stores on server.
Multi Tier Architecture
Enterprise Application consists of number of layers or tiers such as (three tier architecture)
Data Layer
Business Layer
Presentation Layer
Data Layer
Data layer consists of data store and it stores on server computer.
This tier related with following
Database
Design the database structure
Normalization
Directory Servers
Database Management System to implement the database
Relational Database Management Systems (RDBMS)
Data Access
Database access drivers
Eg. JDBC
Business Layer
In this business layer, then, data is manipulated, transformed, and converted into content suitable for presentation.
The core of this layer is the code that actually executes business logic. This code maps to a company's business processes; in the best case, a single module of code represents a single business process. These modules can then be called to obtain a client's outstanding balance, for example. This figure is rarely stored in the database, but instead is calculated from the client's purchases subtracted from his or her assets. This allows the raw data to be masked from the presentation layer of an application; instead of asking for data and performing calculations, the application needs to request only the business process that results in a client's account balance, and format the result.
However, this is not entirely for the sake of another book; it is also to show you that the details of the data and business layers are often completely isolated from the presentation layer. This means that two groups could design these at different times, or you could even develop a set of data stores and business rules without worrying about presentation until later (the approach taken by this book). This method forces you to uncouple these layers, which is critical to good application design. It also allows an easy conversion of an application to a set of web services; since your business layer is not specifically aimed at a web application, it is easy to expose beans and other business components as web services down the line. So I'll leave this area intentionally open for interpretation. Of course, this doesn't prevent a basic diagramming of how the presentation layer (be it servlets, web services, Java Swing, or anything else) interacts with the other layers in the application.
The Java 2 Enterprise Edition Specification (J2EE)
In addition to defining the interfaces required for building an enterprise-distributed application, the best feature about the J2EE specification is that it describes what is required from vendor providers, but does not suggest how interfaces should be implemented. Therein lies the formula for success: flexibility, scalability, and making provisions for J2EE and the other specifications’ growth by receiving input from other major third-party vendors and the entire Java community. J2EE is the obvious choice for developing secure distributed applications.
The J2EE’s multi component infrastructure is defined as five functional technologies.
Communications
Presentation
Business applications
Security
Enterprise information system enabling technologies
The Client Tier
A rich client can be both proprietary standalone Java applications and non-Java applications. Rich clients are capable of accessing both RDBMS and ERP services directly via JDBC connectors. They may also access the EJB web container residing within WebSphere or BEA’s WebLogic. The web container contains both servlets and JSP pages that can access the Enterprise JavaBeans.
A thin client residing on a client tier supports the HTML container (browser), HTML, and applets. Thin clients access the web container via HTTP/HTTPS, XML, and HTML. They are also capable of using JDBC connectors to access a relational database and ERP applications.
The Presentation Tier
This tier hosts the web container that supports Java servlets, Java Server Pages, and Java API for XML Parsing, and the XSLT transformation services. These technologies employ both RMI-IIOP and vendor-proprietary protocols for accessing the remote objects.
The Business Tier
This tier hosts the EJB container and provides support for business transactions executed by EJBs. The business beans utilize the JDBC and JTC connectors to interact with an RDBMS and ERP business solution.
The Enterprise Information Services Tier
This tier facilitates cross-platform interaction with enterprise legacy systems. It separates data, including the database, enterprise resource planning, and mainframe transaction processing, from the business and client tiers. J2EE designates two technologies for providing portable access to the EIS tier: JDBC and the Connector technology.
The Communication Technologies
The eight Java technologies that make up the communications component facilitate client-side business component communications. They are described briefly in the following sections.
Java Message Service (JMS) 1.0.2
Business enterprise applications require facilities for exchanging messages. JMS offers a unified-standard messaging API for supporting several different messaging formats, including XML. The JMS API supports two types of messages:
Point-to-point
Publish-subscribe
Java Mail (JavaMail) 1.2
Email pervades our professional and personal lives every day. An email is both platform and protocol agnostic
Java Bean Activation Framework (JAF) 1.0.1
The JAF represents a “smart” application framework. It is capable of analyzing new data, abstracting the data’s operations, and making them available to other application components. This is essential where new data formats are evolving. The JAF is somewhat comparable in functionality to Microsoft .NET’s Framework v.1.1. Frameworks are where all application-centric functionality is defined and managed. As new technologies evolve, and as new data types and development languages emerge, they rely on the framework to support and manage the new technologies.
Java Interface Definition Language (JavaIDL) 1.3
Typically, business applications contain legacy applications that need to be integrated with newly created Java applications. The Java IDL is an Object Request Broker that comes bundled with the Java 2 Standard Edition (J2SE) and allows J2EE components to invoke requests on external CORBA objects using IIOP as the protocol.
Java Naming and Directory Interface (JNDI) 1.2
In a distributed environment, services and objects require a standard, uniform, and transparent method for locating objects residing on different servers on a network. JNDI provides this methodology. It enables applications to access resources distributed throughout the network. J2EE uses JNDI and RMI-IIOP for finding the remote objects.
Java Authentication and Authorization Service (JAAS)
Security-enabling technologies facilitate J2EE application security implementations by providing authentication and authorization services to users before accessing enterprise resources. JAAS is the primary technology for supporting these services. A container such as WebSphere automatically provides them.
Java API for XML Parsing (JAXP) 1.1
JAXP is the technology employed for parsing and transforming XML documents into an appropriate format using the standard Java APIs. JAXP supports the Simple API for XML (SAX 2.0), Document Object Model (DOM), and XSLT, the XML designated transformation language.
Servlets
Unit IT34
Lesson 2
Unit IT34
Lesson 2
• Java introduce applets for client side programming
• Java introduce servlets for server side programming
• Servlets can be loaded dynamically and use to create dynamic web pages
• Web Designing/ Static Web Pages 2 side web browser. client - static web pages.server.web server
• Web Developing/ Dynamic Web Pages diagrame here
• Common Gateway Interface/ CGI programs initially used to generate dynamic web pages
• Drawback
of CGI is it generate separate process for each request and therefore
sever can handle limited number of requests eg. Perl
• Netscape Java Script and Server side API known as NSAPI
• Microsoft ASP and Server side API ISAPI
Java Servlets
• Server side java programs that can be loaded dynamically
• Servlets runs inside a JVM on the server
• Multithreading for handle number of requests
• Portable across the OSs and web servers
• Most of web servers supports servlets
• Add on servlet engine can be used with web server eg. Microsoft’s IIS, IBM’s WebSphere
Java Servlet API
• Servlet API is not a part of JDK, you have to install JSDK (Java Servlets Developer’s Kit)
• Two packages
– javax.servlet
– javax.servlet.http
• javax.servlet package is used to create protocol independent servlets
• The java.servlet.http package used to create HTTP servlets
• All servlets must implement servlet interface
Java Servlet API
• A protocol independent servlet can extend from the class javax.servlet.GenericServlet
• A HTTP servlet can extend from the class javax.servlet.http.HttpServlet
• HttpServlet class is a sub class of GenericServlet class
Creating a Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Welcome extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String host=request.getRemoteHost();
String address=request.getRemoteAddr();
out.println("<HTML>");
out.println("<H EAD><TITLE>Welcome to my page</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Welcom to my page</BIG>");
out.println("Your host name is : "+host+" and address is : "+address);
out.println("</BODY></HTML>");
}
}
Creating a Servlet
• Save the file as Welcome.java
• Compile the file
javac Welcome.java –classpath “c:\jsdk2.0\lib\jsdk.jar”
• To run the servlet you can use servletrunner utility in jSDK
servletrunner –d c:\servlet_home –s c:\jsdk2.0\examples\servlet.properties
• Servlet_home is a directory which kept the Welcome.class file
• Web browser
Calling Servlet from HTML form
<html>
<head>
<title>Let’s introduce ourselves</title>
</head>
<body>
<form method=get action="http://localhost:8080/servlet/Welcome1">
What is your name ?
<input type=text name=“username">
<input type=submit>
</form>
</body>
</html>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Welcome extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String host=request.getRemoteHost();
String address=request.getRemoteAddr();
String name=request.getParameter(“username”);
out.println("<HTML>");
out.println("<H EAD><TITLE>Welcome to my page</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>”+name+” Welcom to my page</BIG>");
out.println("Your host name is : "+host+" and address is : "+address);
out.println("</BODY></HTML>");
}
}
Servlets
Unit IT34
Lesson 3
Unit IT34
Lesson 3
Login Servlet
• The following Servlet program illustrates HTML form which used to Login to a intranet.
• import java.io.*;
• import javax.servlet.*;
• import javax.servlet.http.*;
• public class LoginServlet extends HttpServlet
• {
• public void doGet(HttpServletRequest req, HttpServletResponse res)
• throws ServletException,IOException
• {
• res.setContentType("text/html");
• PrintWriter out = res.getWriter();
• String user=req.getParameter("user");
• String password=req.getParameter("pwd");
• out.println("<HTML>");
• out.println("<HEAD><TITLE>Login Servlet</TITLE></HEAD>");
• out.println("<BODY>");
• if("student".equalsIgnoreCase(user)&&"hardy123".equalsIgnoreCase(password))
• out.println("Welcome to Hardy Advanced Technological Institute");
• else
• out.println("User Name and/or Password combination is invalid");
• out.println("</BODY></HTML>");
• }
• }
• The getParameter() method accept parameter from web page to servlet.
• Servlet checks user name and password and returns the response as a dynamic web page.
HTML Page>
<html>
<head>
<title>Student Login</title>
</head>
<body>
<p>
<form method=get
action="http://localhost:8080/servlet/LoginServlet">
Enter User Name <input type=text name="user">
<p>
Enter Password <input type=password name="pwd">
<p>
<input type="Submit" value="Login">
<input type="reset">
</form>
</body>
</html>
Servlet Design
• A
servlet represents a Java class running within a Java Virtual Machine
(JVM) related to a web server. Servlets interact with a collection of
JavaBeans or Enterprise JavaBeans (EJBs) to execute any described
business logic. As previously stated, servlets add functionality by
providing session management and other related functions such as user
authentication and authorization. The following topics provide a
framework for understanding a servlet’s responsibilities:
• HTTP essentials
• Servlet life cycle
• Servlet primary classes
• Advantages of Servlets over the Traditional CGI
• Efficient.
With traditional CGI, a new process is started for each HTTP request.
If the CGI program does a relatively fast operation, the overhead of
starting the process can dominate the execution time. With servlets, the
Java Virtual Machine stays up, and each request is handled by a
lightweight Java thread, not a heavyweight operating system process.
Similarly, in traditional CGI, if there are N simultaneous
request to the same CGI program, then the code for the CGI program is
loaded into memory N times. With servlets, however, there are N
threads but only a single copy of the servlet class. Servlets also have
more alternatives than do regular CGI programs for optimizations such as
caching previous computations, keeping database connections open, and
the like.
Advantages of Servlets over the Traditional CGI
• Convenient.
Hey, you already know Java. Why learn Perl too? Besides the convenience
of being able to use a familiar language, servlets have an extensive
infrastructure for automatically parsing and decoding HTML form data,
reading and setting HTTP headers, handling cookies, tracking sessions,
and many other such utilities.
• Powerful.
Java servlets let you easily do several things that are difficult or
impossible with regular CGI. For one thing, servlets can talk directly
to the Web server (regular CGI programs can't). This simplifies
operations that need to look up images and other data stored in standard
places. Servlets can also share data among each other, making useful
things like database connection pools easy to implement. They can also
maintain information from request to request, simplifying things like
session tracking and caching of previous computations.
• Portable.
Servlets are written in Java and follow a well-standardized API.
Consequently, servlets written for, say I-Planet Enterprise Server can
run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets
are supported directly or via a plugin on almost every major Web server.
• Inexpensive.
There are a number of free or very inexpensive Web servers available
that are good for "personal" use or low-volume Web sites. However, with
the major exception of Apache, which is free, most commercial-quality
Web servers are relatively expensive. Nevertheless, once you have a Web
server, no matter the cost of that server, adding servlet support to it
(if it doesn't come preconfigured to support servlets) is generally free
or cheap.
HTTP and Servlets
• HTTP,
which provides the basic services for the Web, is built on the TCIP/IP
protocol and is employed for application-level data transmission. One of
the primary beneficial characteristics of HTTP is its request-response protocol.
It is the transmission protocol of choice because it facilitates
transmission of data through corporate firewalls. It also allows
requests and responses to exist as MIME-like messages.
• From
an application-level perspective, HTTP has its drawbacks. It is both
stateless and connectionless. It is based on a web server and has the
following format: it receives client requests and sends a response back
to the client. It is important to understand that neither the client nor
server retains any state information whatsoever. Incidentally, servlets
take over where HTTP is unable to preserve state. Servlets support
session state. A client can be one of the following:
A web-enabled browser A Java applet
Another web server Another web-enabled application
The Servlet Life Cycle
• The
process of loading a servlet into memory, executing the servlet, and
then unloading the servlet from memory is the servlet life cycle. For
example, a servlet is accessed by typing the following URL: http://localhost/servlet/GreetingsServlet. Typing the keyword servlet in the URL path informs the web server that the client request is designated for a particular servlet and not an HTML page.
• Creating a servlet requires the following steps:
• Create a GenericServlet subclass, essentially the class javax.servlet.http.HttpServlet, meaning you invoke the servlet via HTTP.
• Supply
the minimum doGet() or a doPost() method to make the servlet workable.
When the servlet is requested for the first time, the web server asks
the servlet engine to load the designated server class and all of its
methods into memory on the servlet engine node.
The Servlet Life Cycle
• Pass
control to the init() method. Note that GenericServlet provides a
default empty init() method. Here is where you perform any
initialization tasks, such as connecting to a database. The init()
method receives only one initial call, which occurs immediately after
the servlet is loaded into memory. The following code demonstrates how
to write the init() method:
• public void init(javax.servlet.ServletConfig config) throws ServletException
{super.init (config);
// place your code here to perform any initialization tasks
}
{super.init (config);
// place your code here to perform any initialization tasks
}
• Each time a servlet is called, a new thread is created, and that thread executes over the service() method.
• Override
the service() method in order to perform any work. This method is where
a servlet performs its multifarious tasks. Because the service() method
is always executed within a new thread, make sure that everything
executed within this method is reentrant (thread safe).
• Finally,
call the destroy() method when the web server senses that the servlet’s
tasks are complete. The destroy() method unloads the servlet from
memory. Typically, tasks such as closing database connections,
closing files, and other administrative tasks are performed in this
context.
Servlet Interfaces and Classes
• The
Java Servlet API 2.1 offers developers an extensive set of classes and
interfaces with which to develop web applications. APIs are contained
within three distinct packages. The developer is required to supply
implementations for these interfaces:
• javax.servlet
• javax.servlet.http
• javax.servlet.jsp
The javax.servlet Package
• The
javax.servlet package represents a collection of basic APIs for
servlets. However, they are not bound to any particular schema or
protocol that defines how they should be implemented. Table 2-2 lists
the classes and interfaces in the javax.servlet package.
Table 2-2: Classes and Interfaces in the javax.servlet Package
Servlet Interface
• The Servlet interface defines the essential APIs for servlets that include the init(), service(), and destroy() methods.
• Note All servlets implement this interface by subclassing the GenericServlet class or, alternatively, the HttpServlet class.
ServletContext Interface
• For each servlet, a context is required because communication must be established with a servlet in a nonrequest-specific
manner. Requirements for this include locating path information,
accessing different servlets running on a web server, and writing to the
server log file.
• Note If
a server supports multiple virtual hosts, the ServletContext object
must be unique. The ServletContext object resides within the
ServletConfig object. You can access this object by employing the
Servlet.getServletConfig() method.
GenericServlet Class
• This
class is abstract and provides the primary behavior for the Servlet
interface. This class also implements the ServletConfig interface,
thereby offering a convenient way to access the ServletContext and
initialization parameters. It also implements the init() and destroy()
methods. All subclasses should override both the init() method and
destroy() method and call the super-class implementation for the
GenericServlet class.
ServletRequest Interface
• The
ServletRequest interface prescribes an object as the first parameter
passed in a call to the service() method for a GenericServlet. This
provides the servlet with metadata about the request originating from a
client call. It includes data, parameter name, values, attributes, and
an input stream. For example, the HttpServletRequest provides HTTP data.
Furthermore, a servlet request represents a MIME body request.
Conversely, the response provides a MIME body response. It is always
wise to use the getReader() method when the body contains text. If the body contains binary data, use the getInputStream() method.
ServletResponse Interface
• This
interface defines an object used in transmitting MIME-encoded data from
the servlet to a client. The servlet engine creates a ServletResponse
object and transmits it as an argument in the servlet’s service method.
Always call the SetContentType() method before calling either the
getWriter() or the getOutputStream() method.
RequestDispatcher Interface
• This
interface defines an object that receives requests from a client and
forwards them to a resource, such as a servlet, an HTML file, or a JSP
file on the server. The servlet engine creates a RequestDispatcher
object, which wraps a server resource residing on a specified path. The
intent is wrapping servlets. However, a servlet engine can create
RequestDispatcher objects to wrap any type of repository resource.
• A
RequestDispatcher is obtained from the ServletContext by utilizing the
ServletContext.getRequestDispatcher(“resource-name”). Once the
dispatcher is obtained, a servlet can forward the request to the named
resource in getRequestDispatcher(). An alternative is to use
RequestDispatcher() for sending a request to a Java Server Page for
display.
HttpServlet Class
• The
GenericServlet provides the basic behavior for a servlet. However, a
separate mechanism for processing HTTP requests is essential. The
HttpServlet, a subclass of GenericServlet, provides the additional
behavior for HTTP requests. The GET and POST methods are most commonly
used. HttpServlet includes the doGet() and doPost() methods for handling
both HTTP GET and HTTP POST.
• When
an HttpServlet is requested via a URL, the service() method examines
the HTTP header and determines which HTTP method to invoke. The
programmer must provide overrides for doGet() and doPost() in order to
achieve the servlet’s requested tasks. Both the service() and do()
methods require two parameters, which represent instances of the
HttpServletRequest and HttpServletResponse interfaces.
• These versions of the request and response objects contain HTTP-specific items such as cookies, headers, and sessions.
HttpServletRequest Interface
• This
interface extends the ServletRequest interface by defining a request
object associated with the HTTP request. Special items included in this
category are authentication through the getAuth() method, the list of
cookies through the getCookies() method, and the query string through the getQueryString() method. The servlet engine implements this interface.
HttpServletResponse Interface
• This
interface extends the ServletResponse interface and defines a response
object corresponding with an HTTP response. This interface permits the
servlet’s service() method both to access and set HTTP headers and to
return data (HTML) to a client.
HttpSession Interface
• This
interface establishes an application-level connection between the web
browser and the web server. Utilizing sessions enables the developer to
store session-specific data in the servlet engine. The session persists
for a specific time period spanning more than one connection or page
request from the user. Typically, a session corresponds to a single user
who may visit the same site repeatedly. The server can maintain a
session by leveraging the services of a cookie or by rewriting URLs.
HttpUtils Class
• This
interface represents a concrete class providing a collection of methods
that a developer can use when creating HttpServlet subclasses. The
getRequestURI() method, a static method, facilitates the ability to
reconstruct the request URI for use by the server.
• Nonstatic
methods include parsePostData(), for parsing the parameters of a POST,
and parseQueryString(), for parsing a GET request’s query string.
Accept Data from Form by using Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/** Shows all the parameters sent to the servlet via either
* GET or POST. Specially marks parameters that have no values or
* multiple values.
*/
public class ShowParameters extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println("Form Details" +"<BODY BGCOLOR=\"#FDF5E6\">\n"+"<H1 ALIGN=CENTER>"+title+"</H1>\n"+
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements())
{
String paramName = (String)paramNames.nextElement();
out.println("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1)
{
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.print("<I>No Value</I>");
else
out.print(paramValue);
}
else
{
out.println("<UL>");
for(int i=0; i<paramValues.length; i++)
{
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
Accept Data from Form by using Servlet
<HTML>
<HEAD>
<TITLE>A Sample FORM using POST</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">A Sample FORM using POST</H1>
<FORM ACTION="http://localhost:8080/servlet/ShowParameters"
METHOD="POST">
Item Number:
<INPUT TYPE="TEXT" NAME="itemNum"><BR>
Quantity:
<INPUT TYPE="TEXT" NAME="quantity"><BR>
Price Each:
<INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR>
<HR>
First Name:
<INPUT TYPE="TEXT" NAME="firstName"><BR>
Last Name:
<INPUT TYPE="TEXT" NAME="lastName"><BR>
Middle Initial:
<INPUT TYPE="TEXT" NAME="initial"><BR>
Shipping Address:
---Accept Data from Form by using Servlet—
<TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
Credit Card:<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Visa">Visa<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Master Card">Master Card<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Amex">American Express<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Discover">Discover<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Java SmartCard">Java SmartCard<BR>
Credit Card Number:
<INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
Repeat Credit Card Number:
<INPUT TYPE="PASSWORD" NAME="cardNum"><BR><BR>
<CENTER>
<INPUT TYPE="SUBMIT" VALUE="Submit Order">
</CENTER>
</FORM>
</BODY>
</HTML>
Servlets
Unit IT34
Lesson 4
Unit IT34
Lesson 4
Managing Session State with Servlets
• As
a developer, one of the biggest challenges is maintaining an identity
with users as they revisit your site multiple times. The information
collected during these visits is called session data. Making the distinction between session data and transaction data
is easy. Session data is temporary, whereas transaction data is
persisted in a repository such as DB2 or Oracle. You can easily convert
session data to transaction data by using an interface provided by the
Java Servlet API. As each session is created, it is assigned a unique
identifier. The ID is subsequently associated with the user and becomes
the key ultimately used for locating the proper session for subsequent
visits.
• The
HttpSession interface facilitates both storing and retrieving
application state information. To begin, an instance of the HttpSession
is procured through the HttpServletRequest interface. The required
interface method is the HttpSession getSession(boolean). The
Boolean argument, if determined to be true, creates a new session. Many
times, it is desirable to ascertain whether the HttpSession returned was
in fact a newly created session or one previously created. Accomplish
this by using the HttpSession interface method boolean isNew(). It
returns a Boolean to indicate whether the sessionID was returned in the
current HttpServletRequest object. It is also possible to discard a
session by using the void invalidate() method.
• public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
• {
String id=request.getPararameter("id");
Employee emp = Employee.getEmployeeFor(id);
HttpSession session = request.getSession(true);
String id=request.getPararameter("id");
Employee emp = Employee.getEmployeeFor(id);
HttpSession session = request.getSession(true);
• /*check to see if the session is new.
If not true, invalidate the current session and create a new session */
If not true, invalidate the current session and create a new session */
• if(session.isNew()==false)
• {
session.invalidate();
session=request.getSession(true);
}
session.putValue("employee",emp);
}
session.invalidate();
session=request.getSession(true);
}
session.putValue("employee",emp);
}
• Assume
the user has decided to submit the changes. Clicking the Submit button
invokes another servlet to process the modifications and persist any
data modifications.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
HttpSession session =request.getSession(false);
HttpSession session =request.getSession(false);
if(session== null)
handleError();
else
handleError();
else
{
Employee emp =(Employee)session.getValue("employee");
if(emp != null)
{
session.invalidate();
}
//send a response
}
Employee emp =(Employee)session.getValue("employee");
if(emp != null)
{
session.invalidate();
}
//send a response
}
• The preceding example demonstrates how to procure an existing session from the request object. The false parameter in the getSession() method specifies not
to create a new session if one is not located in the request object. If
so, a null is returned. The getValue() method return type is Object, so
the value must be cast to the appropriate type before the value is
usable.