Enterprise Solutions
Unit IT34
Lesson 1
Unit IT34
Lesson 1
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.
Presentation Layer
• Last, but not least, is the presentation layer. As with the data layer, creating the presentation layer is another difficult task, as there are many decisions to be made. Additionally, this layer often has the most constraints upon it: clients have a variety of browsers and versions of browsers, as well as other Internet-capable devices; output may need to be in a specific format; speed of display may be a factor; and so on. In the Forethought application, the presentation layer must be able to serve multiple types of clients, and do it in a way that doesn't force a lot of duplication of content. JSP, XML, and XSL are all part of the solutions that will be examined for solving this problem. As I'll be spending Volume II on the subject of presentation, I'll leave these details for a later is cussion.
Presentation Layer
• 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
Figure 2-1: A J2EE web container

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.
• Remote Method Invocation and Internet Inter-ORB Protocol (RMI-IIOP) 1.0
All interaction between components in a distributed environment consists of client calls to remote objects residing on different machines. RMI uses the Java Remote Method Protocol (JRMP) for communications with remote objects. RMI works only in a Java environment, whereas the Internet Inter-ORB protocol (IIOP) represents a CORBA- based standard, which is independent of the underlying protocol. CORBA is the glue that facilitates interoperability with non-Java and CORBA clients. Subsequently, RMI and IIOP were merged to provide cross-platform communications, a real win-win for developers.
• Extensible Markup Language (XML)
XML is the markup language of choice for enabling businesses to define object behavior and provide data-format-independent representations in an extensible manner. XML facilitates transmission of data over the wire and penetrates corporate firewalls seamlessly.
This explains why XML is a core component of every enterprise application in both Java and .NET-oriented web services. For example, all distributed applications employ XML for creating web-config files, for creating deployment descriptors, and for providing metadata to applications via a methodology called reflection.
• 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
esources. JAAS is the primary technology for supporting these services. A container such as WebSphere automatically provides them.
The Presentation Technologies
• The three presentation-oriented technologies include Java servlets, Java Server Pages (JSPs), and Java API for XML Parsing (JAXP).
• Java Servlets 2.3
Servlets represent server-side Java objects that function as an intermediary between web clients and other business objects (JavaBeans or Enterprise JavaBeans). The beans support the execution of business logic and interact with database objects. In essence, servlets implement the presentation logic and manage requests from web browsers to business components.
• Java Server Pages (JSPs) 1.2
Java Server Pages are a servlet extension designed to construct dynamic presentation- oriented applications. A JSP page consists of directives and code fragments that provide functionality similar to ASP.NET pages. Once the servlet accepts a client request and delegates the requested task to a business logic–oriented JavaBean or EJB, it designates a Java Server Page for returning any requested business result to the client via HTTP and HTML. JSPs can interact with business components.
• 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.
Java Database Connectivity
JDBC ODBC Bridge
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
class JDBC
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
Statement stmt=con.createStatement();
String query="SELECT * FROM STUDENTTABLE";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
System.out.print(rs.getInt("SID")+" ");
System.out.print(rs.getString("Name")+" ");
System.out.println(rs.getInt("Marks"));
}
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}}
Step 1:
Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Step 2:
Create a connection
Connection con = DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
Step 3:
Create SQL statement
Statement stmt=con.createStatement();
Step 4:
Returns the result set
String query="SELECT * FROM STUDENTTABLE";
ResultSet rs=stmt.executeQuery(query);
Step 5:
Close the connection
con.close();
Configure the ODBC Data Source & System
DSN
Control Panel
Administrative Tools
Data Sources (ODBC)
System DSN Tab Sheet, Add Button
Microsoft Access Driver (*.mdb), Finish Button
Data Source Name (Similar to Coding)
Select Database, OK Button
Advanced Button, User Name & Password (Similar to Coding), OK Button
OK Button, OK Button
import java.sql.*;
class JDBC
{
public static void main(String[] args)
{
int sId=6;
String name="Charindra Silva";
int marks=90;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
Statement stmt=con.createStatement();
String query="INSERT INTO STUDENTTABLE VALUES(?,?,?)";
PreparedStatement insert=con.prepareStatement(query);
insert.setInt(1,sId);
insert.setString(2,name);
insert.setInt(3,marks);
insert.executeUpdate();
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
import java.sql.*;
class JDBC
{
public static void main(String[] args)
{
int sId=1;
String name="Nelani Fonseka";
int marks=60;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
Statement stmt=con.createStatement();
String query="UPDATE STUDENTTABLE SET Name='"+name+"',"+"Marks="+marks+" WHERE SID="+sId;
stmt.executeUpdate(query);
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
import java.sql.*;
class JDBC
{
public static void main(String[] args)
{
int sId=5;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
Statement stmt=con.createStatement();
String query="DELETE * FROM STUDENTTABLE WHERE SID="+sId;
stmt.executeUpdate(query);
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Java Database Connectivity
Enterprise Solutions
Unit IT34
Lesson 4
Enterprise Solutions
Unit IT34
Lesson 4
What is JDBC?
• JDBC stands for Java Database Connectivity. It describes a list of methods a Java programmer can use to access a relational database.
• JDBC can used to access a database on the same machine, or a server on a LAN or on a server across the internet.
• JDBC provides a common database programming API for Java programmers. However, JDBC drivers do not directly communicate with as many database products as ODBC drivers. Instead, many JDBC drivers communicate with database using ODBC. In-fact one of the first JDBC drivers was the JDBC-ODBC bridge driver developed by JavaSoft.
• JDBC was simply a better solution for Java applications and applets. The problem with ODBC is that it is a C language API, not a Java API. Java is object-oriented and C is not. C uses pointers and other programming constructs that Java does not support. A Java version of ODBC would require a significant rewrite of the ODBC API. ODBC drivers must be installed on client machines. This means that applet access to databases would be constrained by the requirement to download and install a JDBC driver. A pure Java solution allows JDBC drivers to be automatically downloaded and installed along with the applet. This greatly simplifies database access for applet users.
JDBC Driver Types
1. JDBC-ODBC Bridge
2. Native API
3. Native Protocol Pure Java Driver
4. JDBC-Net Pure Java Driver
5. JDBC-ODBC Bridge
– The JDBC-ODBC bridge provides JDBC access via most ODBC drivers.
– Some ODBC binary code and in many cases database client code must be loaded on each client machine that uses this driver.
– Overhead involved.
– Most appropriate where client installation are not a major problem.
6. Native API Partly Java Driver
– Converts JDBC calls into calls on the client API for oracle or other DBMSs’.
– The Java driver requires some operating system specific binary code loaded on each client machine.
7. Native Protocol Pure Java Driver
– Converts JDBC calls directly to the network protocol used by DBMSs’.
– Therefore a direct call is allowed from client to server.
– Machine independent.
- JDBC-Net Pure Java Driver
– Translates JDBC calls into a DBMS independent net protocol, which is then translated, to a particular vendor specific database protocol by a server.
– Allows Java client to connect to many different databases.
– Standard JDBC driver
– Eg. Oracle Thin Driver, OCI Driver
– import java.sql.DriverManager;
– import java.sql.Connection;
– import java.sql.Statement;
– import java.sql.ResultSet;
– class JDBC
– {
– public static void main(String[] args)
– {
– try
– {
– Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
– Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
– Statement stmt=con.createStatement();
– String query="SELECT * FROM STUDENTTABLE";
– ResultSet rs=stmt.executeQuery(query);
– while(rs.next())
– {
– System.out.print(rs.getInt("SID")+" ");
– System.out.print(rs.getString("Name")+" ");
– System.out.println(rs.getInt("Marks"));
– }
– con.close();
– }
– catch(Exception e)
– {
– System.out.println(e.getMessage());
– }
– }}
Fsdf
Dsds
Step 1:
Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Step 2:
Create a connection
Connection con = DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
Step 3:
Create SQL statement
Statement stmt=con.createStatement();
Step 4:
Returns the result set
String query="SELECT * FROM STUDENTTABLE";
ResultSet rs=stmt.executeQuery(query);
Step 5:
Close the connection
con.close();
Configure the ODBC Data Source & System
DSN
Control Panel
Administrative Tools
Data Sources (ODBC)
System DSN Tab Sheet, Add Button
Microsoft Access Driver (*.mdb), Finish Button
Data Source Name (Similar to Coding)
Select Database, OK Button
Advanced Button, User Name & Password (Similar to Coding), OK Button
OK Button, OK Button
import java.sql.*;
class JDBC
{
public static void main(String[] args)
{
int sId=6;
String name="Charindra Silva";
int marks=90;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
Statement stmt=con.createStatement();
String query="INSERT INTO STUDENTTABLE VALUES(?,?,?)";
PreparedStatement insert=con.prepareStatement(query);
insert.setInt(1,sId);
insert.setString(2,name);
insert.setInt(3,marks);
insert.executeUpdate();
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
-----------------------------------
Java Database Connectivity
Enterprise Solutions
Unit IT34
Lesson 5
Enterprise Solutions
Unit IT34
Lesson 5
PreparedStatement Class
• Invoking statement
import java.sql.PreparedStatement;
• PreparedStatement object allows you to execute parameterized queries.
Eg. String query="INSERT INTO STUDENTTABLE VALUES(?,?,?)";
PreparedStatement insert=con.prepareStatement(query);
insert.setInt(1,sId);
insert.setString(2,name);
insert.setInt(3,marks);
insert.executeUpdate();
Eg. String query=“SELECT * FROM STUDENTTABLE
WHERE SID=?";
PreparedStatement insert=con.prepareStatement(query);
insert.setInt(1,sId);
ResultSet rs=insert.executeQuery();
• executeQuery() method used to execute queries such as SELCT and DELETE.
• executeUpdat() method used to execute queries such as INSERT and UPDATE.
• import java.sql.*;
• class JDBC
• {
• public static void main(String[] args)
• {
• int sId=6;
• String name="Charindra Silva";
• int marks=90;
• try
• {
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
• Statement stmt=con.createStatement();
• String query="INSERT INTO STUDENTTABLE VALUES(?,?,?)";
• PreparedStatement insert=con.prepareStatement(query);
• insert.setInt(1,sId);
• insert.setString(2,name);
• insert.setInt(3,marks);
• insert.executeUpdate();
• con.close();
• }
• catch(Exception e)
• {
• System.out.println(e.getMessage());
• }
• }
• }
• import java.sql.*;
• class JDBC
• {
• public static void main(String[] args)
• {
• int sId=1;
• String name="Nelani Fonseka";
• int marks=60;
• try
• {
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
• Statement stmt=con.createStatement();
• String query="UPDATE STUDENTTABLE SET Name='"+name+"',"+"Marks="+marks+" WHERE SID="+sId;
• stmt.executeUpdate(query);
• con.close();
• }
• catch(Exception e)
• {
• System.out.println(e.getMessage());
• }
• }
• }
• --------------------------------------------
• import java.sql.*;
• class JDBC
• {
• public static void main(String[] args)
• {
• int sId=1;
• String name="Nelani Fonseka";
• int marks=60;
• try
• {
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
• Statement stmt=con.createStatement();
• String query="UPDATE STUDENTTABLE SET Name='"+name+"',"+"Marks="+marks+" WHERE SID="+sId;
• stmt.executeUpdate(query);
• con.close();
• }
• catch(Exception e)
• {
• System.out.println(e.getMessage());
• }
• }
• }
• import java.sql.*;
• class JDBC
• {
• public static void main(String[] args)
• {
• int sId=5;
• try
• {
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Connection con=DriverManager.getConnection("jdbc:odbc:HardyDb","scott","tiger");
• Statement stmt=con.createStatement();
• String query="DELETE * FROM STUDENTTABLE WHERE SID="+sId;
• stmt.executeUpdate(query);
• con.close();
• }
• catch(Exception e)
• {
• System.out.println(e.getMessage());
• }
• }
• }
• Using a Servlet to access a Database
• import java.io.*;
• import javax.servlet.*;
• import javax.servlet.http.*;
• import java.sql.*;
• public class ExamServlet extends HttpServlet
• {
• public void doPost(HttpServletRequest req, HttpServletResponse res)
• throws ServletException,IOException
• {
• res.setContentType("text/html");
• PrintWriter out = res.getWriter();
• String index=req.getParameter("index");
• out.println("<HTML>");
• out.println("<HEAD><TITLE>Login Servlet</TITLE></HEAD>");
• out.println("<BODY>");
• try
• {
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Connection con=DriverManager.getConnection("jdbc:odbc:exam","scott","tiger");
• Statement stmt=con.createStatement();
• String query="SELECT * FROM RESULT WHERE index='"+index+"'";
• ResultSet rs=stmt.executeQuery(query);
• while(rs.next())
• {
• out.println("Index Number : "+rs.getString("index"));
• out.println("Exam Result : "+rs.getString("marks"));
• }
• }
• catch(Exception e)
• {
• out.println("Error : "+e);
• }
• out.println("</BODY></HTML>");
• }
• }
• <html>
• <head>
• <title>Exam Result</title>
• </head>
• <body>
• <p>
• <form method=post action="http://localhost:8080/servlet/ExamServlet">
• Enter Index Number:<input type=text name="index">
• <p>
• <input type="Submit" value="Login">
• <input type="reset">
• </form>
• </body>
• </html>
Java Server Pages (JSP)
What is Java Server Pages
• JSPs represent a Java-based technology that allows the development of dynamic web sites.
• Think of JSP as a type of server-side scripting language.
• Java Server Pages are text files, usually with the extension .jsp, that take the place of traditional HTML pages.
• JSP files contain traditional HTML along with embedded code that allows the page designer to access data from Java code running on the server.
Advantages of JSP
• JSP use an HTML-like syntax in coding and it is easy to use.
• JSP automatically generate servlet and eliminate the need for manually writing doGet() and doPost() methods.
• JSP model separates presentation tasks from implementation tasks.
• More powerful and easier to use than Microsoft ASP or other MS script language.
• High Performance.
• JSP is portable and it can run on other operating systems and non-Microsoft web servers.
• JSP consists of reusable components.
The JSP Life Cycle
• JSPs begin life as a text file and are translated to servlets. The translation involves conversion of JSP source code into servlet source code by the JSP container. This process is commonly referred to as compilation of a JSP page into a servlet.
• Note Don’t confuse the process of converting JSP source code to servlet source code with compilation of Java code into bytecode.
• After the conversion process is complete, the servlet is subsequently compiled.
• JSPs are converted to servlets, they inherit a servlet’s dependence on the request-response model.
The JSP Life Cycle
• When the JSP container translates the body of a JSP page into a servlet, it creates a new class that implements the javax.servlet.Servlet interface.
• This new class contains a method called _jspService() and is constructed from the body of a JSP page. In addition, the container bases the newly generated class on a class whose service() method calls _jspService().
• A JSP page is translated to a method that maps requests to responses based on the JSP’s page contents.
First JSP Program
• The JSP code as follows.
<html>
<head>
<title>My First JSP</title>
</head>
<body bgcolor="#ffffff">
<h1>
<%= “Hello World from JSP” %>
</h1>
</body>
</html>
<head>
<title>My First JSP</title>
</head>
<body bgcolor="#ffffff">
<h1>
<%= “Hello World from JSP” %>
</h1>
</body>
</html>
• Save the file into HelloWorld folder as HelloWorld.jsp
Running the JSP using Jakarta Tomcat JSP Container
• Install the Jakarta Tomcat as a JSP container.
• Copy the HelloWorld folder in to
C:\Program Files\Apache Tomcat 4.0\webapps\examples\jsp
• Start the Tomcat
• Run Internet Explorer and type
http://localhost:8080/examples/jsp/HelloWorld/HelloWorld.jsp
Example JSP Program for Declaration
• The JSP code as follows.
<html>
<head>
<title>Declaration</title>
</head>
<%! int i=10; %>
<%=i%>
</body>
</html>
JSP Tags
• JSP provides four major categories of markup tags.
- Directives
– is a set of tags for providing the JSP container with page-specific instructions for how the document containing the directives is to be processed.
– Directives do not affect the handling of individual requests, but instead affect global properties of the JSP page that influence its translation into a servlet.
- Scripting Elements
– are used to embed programming instructions, written in the designated scripting language for the page, which are to be executed each time the page is processed for a request.
– Some scripting elements are evaluated purely for their side effects, but they may also be used to generate dynamic content that appears in the output of the page.
- Comments
– are used for adding documentation strings to a JSP page.
– JSP supports multiple comment styles, including one which enables documentation to appear in the output from the page.
– Other JSP comments can only be viewed in the original JSP file, or in the source code for the servlet into which the page is translated.
- Actions
– support several different behaviors. Like scripting elements, actions are processed for each request received by a page.
– Actions can transfer control between pages, specify applets, and interact with server-side JavaBeans components.
– Like scripting elements, actions may or may not generate dynamic content. All custom tags incorporated via extended tag libraries take the form of actions.
JSP Directives Tags
• Directives are used to convey special processing information about the page to the JSP container.
• For example, directives may be used to specify the scripting language for the page, to include the contents of another page, or to indicate that the page uses a custom tag library.
• Directives do not directly produce any output that is visible to end users when the page is requested; instead, they generate side effects that change the way the JSP container processes the page.
Page directive
• The page directive is the most complicated JSP directive, primarily because it supports such a wide range of attributes and associated functionality. The basic syntax of the page directive is as follows:
<%@ page attribute1="value1" attribute2="value2" attribute3=… %>
• White space after the opening <%@ and before the closing %> is optional, but recommended to improve readability. Like all JSP tag elements, the page directive supports an XML-based syntax, as follows:
<jsp:directive.page attribute1="value1"
attribute2="value2" attribute3=… />
Attribute specifications are identical for the two tag styles, and there are eleven different attributes recognized for the page directive. In the examples to follow, we will use the first style, only because it is slightly less verbose and therefore appears more frequently in JSP pages that are created manually. Keep in mind that these two tag styles are interchangeable.
Info attribute
• The info attribute allows the page author to add a documentation string to the page that summarizes its functionality. This string will then be available for use by the JSP container or other tools in a programmatic manner for displaying the summary information. There are no restrictions on the length or contents of the documentation string, but author, version, and copyright information are commonly included, as in the following example:
<%@ page info="The CLU homepage, Copyright 1982 by Kevin Flynn." %>
• The default value for the info attribute is the empty string.
Language attribute
• The language attribute specifies the scripting language to be used in all scripting elements on the page. All JSP containers are required to support Java as a scripting language, and this is the default if the language attribute is not explicitly specified. As indicated earlier in the chapter, support for other scripting languages is optional, and varies among JSP implementations. Here is how the language attribute is used to specify Java as the scripting language:
<%@ page language="java" %>
Note that if the include directive is employed, scripting elements in the included page must use the same scripting language as the current page.
Java Server Pages (JSP)
JSP Elements
• JSP elements are
– Directives
– Scripting Elements
– Actions
• Scripting elements let you specify Java code that will become part of the resultant servlet.
• directives let you control the overall structure of the servlet
actions let you specify existing components that should be used, and otherwise control the behavior of the JSP engine.
JSP Scripting Elements
• JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:
- Expressions of the form <%= expression %> that are evaluated and inserted into the output,
- Scriptlets of the form <% code %> that are inserted into the servlet's service method, and
- Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.
JSP Expressions
• A JSP expression is used to insert Java values directly into the output. It has the following form: <%= Java Expression %>
• The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at run-time (when the page is requested), and thus has full access to information about the request.
• For example, the following shows the date/time that the page was requested:
• Current time: <%= new java.util.Date() %>
• To simplify these expressions, there are a number of predefined variables that you can use. These implicit objects are discussed in more detail later, but for the purpose of expressions, the most important ones are:
• request, the HttpServletRequest;
• response, the HttpServletResponse;
• session, the HttpSession associated with the request (if any); and
• out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client.
• Here's an example:
• Your hostname: <%= request.getRemoteHost() %>
• Finally, note that XML authors can use an alternative syntax for JSP expressions: <jsp:expression> Java Expression </jsp:expression>
• Remember that XML elements, unlike HTML ones, are case sensitive. So be sure to use lowercase.
• If you want to do something more complex than insert a simple expression, JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets have the following form:
<% Java Code %>
• Scriptlets have access to the same automatically defined variables as expressions. So, for example, if you want output to appear in the resultant page, you would use the out variable.
<% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %>
• Note that code inside a scriptlet gets inserted exactly as written, and any static HTML (template text) before or after a scriptlet gets converted to print statements. This means that scriptlets need not contain complete Java statements, and blocks left open can affect the static HTML outside of the scriptlets.
• For example, the following JSP fragment, containing mixed template text and scriptlets
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>
• will get converted to something like:
if (Math.random() < 0.5) {
out.println("Have a <B>nice</B> day!");
} else {
out.println("Have a <B>lousy</B> day!");
}
• If you want to use the characters "%>" inside a scriptlet, enter "%\>" instead. Finally, note that the XML equivalent of <% Code %> is <jsp:scriptlet> Code </jsp:scriptlet>
JSP Declaration
• A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside of the service method processing the request). It has the following form:
<%! Java Code %>
• Since declarations do not generate any output, they are normally used in conjunction with JSP expressions or scriptlets.
JSP Declaration
• For example, here is a JSP fragment that prints out the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded):
<%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %>
As with scriptlets, if you want to use the characters "%>", enter "%\>" instead. Finally, note that the XML equivalent of <%! Code %> is <jsp:declaration> Code </jsp:declaration>
JSP Directives
• A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
However, you can also combine multiple attribute settings for a single directive, as follows:
<%@ directive attribute1="value1" attribute2="value2"
...
attributeN="valueN" %>
JSP Directives
• There are two main types of directive:
• page, which lets you do things like import classes, customize the servlet superclass, and the like;
• and include, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet.
• The specification also mentions the taglib directive, which is not supported in JSP version 1.0, but is intended to let JSP authors define their own tags. It is expected that this will be the main new contribution of JSP 1.1.
JSP page Directive
• The page directive lets you define one or more of the following case-sensitive attributes:
• import="package.class" or import="package.class1,...,package.classN". This lets you specify what packages should be imported.
• For example:
<%@ page import="java.util.*" %>
The import attribute is the only one that is allowed to appear multiple times.
<%@ page import="java.util.*" %>
The import attribute is the only one that is allowed to appear multiple times.
JSP include Directive
• This directive lets you include files at the time the JSP page is translated into a servlet. The directive looks like this:
<%@ include file="relative url" %>
• The URL specified is normally interpreted relative to the JSP page that refers to it, but, as with relative URLs in general, you can tell the system to interpret the URL relative to the home directory of the Web server by starting the URL with a forward slash. The contents of the included file are parsed as regular JSP text, and thus can include static HTML, scripting elements, directives, and actions.
• Example Using Scripting Elements and
• Directives
• <HTML>
• <HEAD>
• <TITLE>Using JavaServer Pages</TITLE>
• <META NAME="author" CONTENT="Marty Hall -- hall@apl.jhu.edu">
• <META NAME="keywords"
• CONTENT="JSP,JavaServer Pages,servlets">
• <META NAME="description"
• CONTENT="A quick example of the four main JSP tags.">
• <LINK REL=STYLESHEET
• HREF="My-Style-Sheet.css"
• TYPE="text/css">
• </HEAD>
• Example Using Scripting Elements and
• Directives
• <BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
• VLINK="#551A8B" ALINK="#FF0000">
• <CENTER>
• <TABLE BORDER=5 BGCOLOR="#EF8429">
• <TR><TH CLASS="TITLE">
• Using JavaServer Pages</TABLE>
• </CENTER>
• <P>
• <UL>
• <LI><B>Expression.</B><BR>
• Your hostname: <%= request.getRemoteHost() %>.
• <LI><B>Scriptlet.</B><BR>
• <% out.println("Attached GET data: " +
• request.getQueryString()); %>
• <LI><B>Declaration (plus expression).</B><BR>
• <%! private int accessCount = 0; %>
• Accesses to page since server reboot: <%= ++accessCount %>
• <LI><B>Directive (plus expression).</B><BR>
• <%@ page import = "java.util.*" %>
• Current date: <%= new Date() %>
• </UL>
• </BODY>
• </HTML>
Predefined Variables/ Implicit Objects
• To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined variables, sometimes called implicit objects. The available variables are request, response, out, session, application, config, pageContext, and page. Details for each are given below.
request
• This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in practice
response
• This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client.
out
• This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive.
JSP Actions
• JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include:
• jsp:include - Include a file at the time the page is requested.
• jsp:useBean - Find or instantiate a JavaBean.
• jsp:setProperty - Set the property of a JavaBean.
• jsp:getProperty - Insert the property of a JavaBean into the output.
• jsp:forward - Forward the requester to a new page.
• jsp:plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.
JSP with Java Beans
• jsp:useBean action lets you load in a JavaBean to be used in the JSP page. This is a a very useful capability because it lets you exploit the reusability of Java classes without sacrificing the convenience that JSP adds over servlets alone.
• The simplest syntax for specifying that a bean should be used is:
<jsp:useBean id="name" class="package.class" />
• This usually means "instantiate an object of the class specified by class, and bind it to a variable with the name specified by id.
JSP with Java Beans
• Now, once you have a bean, you can modify its properties via jsp:setProperty action
• Recall that with beans, when you say "this bean has a property of typeX called foo", you really mean "this class has a method called getFoo that returns something of type X, and another method called setFoo that takes an X as an argument."
JSP with Java Beans
• The jsp:setProperty action is discussed in more detail in the next section, but for now note that you can either supply an explicit value, give a param attribute to say that the value is derived from the named request parameter, or just list the property to indicate that the value should be derived from the request parameter with the same name as the property. You read existing properties in a JSP expression or scriptlet by calling the appropriate getXxx method, or more commonly, by using the jsp:getProperty action.
• Example JSP Program which use a Bean
• <HTML>
• <HEAD>
• <TITLE>Reusing JavaBeans in JSP</TITLE>
• <LINK REL=STYLESHEET
• HREF="My-Style-Sheet.css"
• TYPE="text/css">
• </HEAD>
• <BODY>
• <CENTER>
• <TABLE BORDER=5>
• <TR><TH CLASS="TITLE">
• Reusing JavaBeans in JSP</TABLE>
• </CENTER>
• Example JSP Program which use a Bean
• <P>
• <jsp:useBean id="test" class=“hall.SimpleBean" />
• <jsp:setProperty name="test"
• property="message"
• value="Hello WWW" />
• <H1>Message: <I>
• <jsp:getProperty name="test" property="message" />
• </I></H1>
• </BODY>
• </HTML>
• SimpleBean.java
• package hall;
• public class SimpleBean {
• private String message = "No message specified";
• public String getMessage()
• {
• return(message);
• }
• public void setMessage(String message)
• {
• this.message = message;
• }
• }
• HTML File (Hello.html)
• <html>
• <head>
• <title>Magazine Publisher Login</title>
• </head>
• <body>
• <p>
• <form method=get action="http://localhost:8080/examples/jsp/HelloName/HelloName.jsp">
• Enter Visitor's Name :<input type=text name="name">
• <p>
• <input type="Submit" value="Login">
• <input type="reset">
• </form>
• </body>
• </html>
• JSP File (HelloName.jsp)
• <HTML>
• <BODY>
• <% String visitor = request.getParameter("name");
• if (visitor == null) visitor = "World"; %>
• Hello, <%= visitor %>!
• </BODY>
• </HTML>
-------------------------------------------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.