SlideShare a Scribd company logo
JSP and Servlets
JavaServer pages are actually, text files that combine standard HTML and new scripting tags. JSPs
look like HTML, but they get compiled into Java Servlets the first time they are invoked. Java
servlets are a key component of server-side Java development.
A servlet is a small pluggable extension to a server that enhances the server’s functionality.
Servlets allow developers to extend and customize any Java-enabled Server- a web server, a
mail server, an application server or any custom server.
JSP
JavaServer pages are on the whole, text files that combine standard HTML and new scripting
tags. JSPs look like HTML, but they get compiled into Java Servlets the first time they are
invoked.
The resulting servlet is a combination of the HTML from the JSP file and embedded dynamic
content specified by the new tags
That is not to say that JSPs must contain HTML. Some of them will contain only Java code; this is
particularly useful when the JSP is responsible for a particular task like maintaining application
flow.
What is needed to write JSP based web application?
As you will come to know in a short time, programming with JSP will need a thorough knowledge
of how servlets are written and executed as the code segments inserted in a JSP are mostly
Servlet code.
If you have already written some ASP programs you may find it easy to work with JSP as there
are so many similarities although they are 2 different technologies.
How does JSP look?
Before considering more technical details regarding JSP, let us see how a JSP file looks and what its static parts are and what its dynamics parts are:
Consider the HelloWorld.jsp below
1. <HTML>
2. <HEAD>
3. <META NAME=”GENERATOR “ Content = “Microsoft Visual Studio 6.0”>
4. <TITLE></TITLE>
5. </HEAD>
6. <BODY>
7. <center><h1>
8. <% out.println(“Hello World!”); %>
9. </h1><center>
10. </BODY>
11. </HTML>
How to test a JSP?
Once a JSP is written next question is how do you test it? To test JSP we are going to use Java
Web Server. The steps are as following:
Copy the HelloWorld.jsp to c:JavaWebServer2.0public_html directory as it is the document
root of the Java Web Server . (Assuming that the Java Web Server is installed in c:)
Now start the Java Web Server.s web service.
Open your browser window.
Now in the address bar type in an address ashttp://IPAddress:: 8080/HelloWorld.jsp, where IP
address of your machine.
Jsp and Servlets
Servlets
The rise of server-side Java applications is one of the latest and most exciting trends in Java
programming. The Java language was originally intended for use in small, embedded devices.
Java’s potentially as a server-side development platform had been sadly overlooked until
recently.
Businesses in particular have been quick to recognize Java’s potential on the server-side. Java is
inherently suited for large client/server applications. The cross platform nature of Java is
extremely useful for organizations that have a heterogeneous collection of servers running
various flavors of the UNIX and Windows operating systems.
Java’s modern, object-oriented memory-protected design allows developers to cut development
cycles and increase reliability. In addition, Java’s built-in support for networking and enterprise
APIs provides access to legacy data, easing the transition from older client/server system.
Java servlets are a key component of server-side Java development.
A servlet is a small pluggable extension to a server that enhances the server’s functionality.
Servlets allow developers to extend and customize any Java-enabled Server- a web server, a
mail server, an application server or any custom server.
History of Web Application
While servlets can be used to extend the functionality of any Java-enabled server, today they are
most often used to extend web servers, providing a powerful, efficient replacement for CGI
scripts. When you use servlet to create dynamic content for a web page or otherwise extend the
functionality of a web server, you are in effect creating a Web application.
While a web page merely displays static content and lets the user navigate through that content,
a web application provides a more interactive experience. A web application may be as simple
as a key word search on a document archive or as complex as an electronic storefront.
Web applications are being deployed on the internet and on corporate intranets and extranets,
where they have the potential to increase productivity and change role of servlets in any web
application it is necessary to understand the architecture of any current web application.
Web Architecture
2-tier Architecture
Typical client/server systems are all 2-tiered in nature where the application resides entirely on
the client PC and database resides on a remote server. But 2-tier systems have some
disadvantages such as:
◦ The processing load is given to the PC while more powerful server acts as a traffic controller between
the application and the database.
◦ Maintenance is the greatest problem. Imagine a situation where there is a small modification to be
done in the application program. Then in case of a 2-tier architecture system, it is necessary to go to each
client machine and make the necessary modifications to the programs loaded on them.
◦ That is the reason why the modern web applications are all developed based on 3-tier architecture.
N-tier Architecture
Although the title of this section is given as N-Tier architecture, here the concentration is on the
3-tier architecture. Basic reason for this is that any web application developed based on N-tier
architecture functions just similar to typical 3-tier architecture.
1. First-Tier:
1. Basically the presentation Layer.
2. Represented by the GUI kind of thing.
1. Middle-Tier :
1. Application Logic
2. Third-Tier :
1. Data that is needed for the application.
The basic idea behind 3-tier architecture is that to separate application logic from the user
interface. This gives the flexibility to the design of the application as well as ease of
maintenance. If you compare this with 2-tier architecture, it is very clear that in 3-tier
architecture the application logic can be modified without affecting the user interface and the
database.
Typical Web Application
A typical web application consists of following steps to complete a request and response.
1. Web application will collect data from the user. (First tier)
2. Send a request to the web server.
3. Run the requested server program. (Second and third tier)
4. Package up the data to be presented in the web browser.
5. Send it back to the browser for display. (First tier)
Servlet Life Cycle
This process can be broken down into the nine steps as follows:
The server loads the servlet when it is first requested by the client or if configured to do so, at
server start-up. The servlet may be loaded from either a local or a remote location using the
standard Java class loading facility.
This step is equivalent to the following code:
Class c=Class.forName(“com.sourcestream.MyServlet”);
It should be noted that when referring to servlets, the term load often refers to the process of
both loading and instantiating the servlet.
2. The server creates one or more instances of the servlet class. Depending on implementation.
The server may create a single instance that services all requests through multiple threads or
create a pool of instances from which one chosen to service each new request. This step is
equivalent to the following Java code:
Servlet s=(Servlet) c.newInstance (); where ,c is the same Class object created in previous step.
The server constructs a ServerConfig object that provides initialization information to the servlet.
The server calls the servlet’s init () method, passing the object constructed in step 3 as a parameter.
The init () method is guaranteed to finish execution prior to the servlet processing the first request. If
the server has created multiple servlet instances (step 2), the init () method is called one time for
each instance.
The server constructs a ServletRequest or HttpServletRequest object from the data included in
the client’s request. It also constructs a ServletResponse or HttpServletResponse object that
provides methods for customizing the server’s response. The type of object passed in these two
parameters depends on whether the servlet extends the GenericServlet class or the HttpServlet
class, respectively.
The server calls the servlet’s service() method passing the objects constructed in step 5 as
parameters. When concurrent requests arrive, multiple service() methods can run in separate
threads.
The service () method processes the client request by evaluating the ServletRequest or
HttpServletRequest object and responds using ServletResponse or HttpServletResponse object.
If the server receives another request for this servlet, the process begins again at step 5.
When instructed to unload the servlet, perhaps by the server administrator or programmatically
by the servlet itself, the server calls the servlet‟s destroy() method. The servlet is then eligible
for garbage collection.
Jsp and Servlets
The Java Servlet Development Kit
The Java Servlet Development Kit (JSDK) contains the class libraries that you will need to create
servlets. A utility known as the servletrunner is also included, which enables you to test some of
the servlets that you create
You can download the JSDK without charge from the Sun Microsystems Web site at
java.sun.com. Follow the instructions to install this toolkit on your machine. For a Windows
machine, the default location of Version 2 of the JSDK is c:Jsdk2.0. The directory
c:Jsdk2.0bin contains
servletrunner.exe. Update your Path environment variable so that it includes this directory. The
directory c:Jsdk2.0lib contains jsdk.jar.
This JAR file contains the classes and interfaces that are needed to build servlets. Update your
Classpath environment variable so that it includes c:Jsdk2.0libjsdk.jar.
A Simple Servlet
To become familiar with the key servlet concepts, we will begin by building and testing a simple
servlet. The basic steps are the following:
1. Create and compile the servlet source code.
2. Start the servletrunner utility.
3. Start a Web browser and request the servlet.
Create and Compile the Servlet Source
Code
To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
First, note that this program imports the javax.servlet package, which contains the classes and
interfaces required to build servlets. You will learn more about these classes and interfaces later
in this chapter. Next, the program defines HelloServlet as a subclass of GenericServlet. The
GenericServlet class provides functionality that makes it easy to handle requests and responses.
Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden.
This method handles requests from a client. Notice that the first argument is a ServletRequest
object. This enables a servlet to read data that is provided via the client request. The second
argument is an ServletResponse object. This enables a servlet to formulate a response for the
client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In this program,
the MIME type is text/html, which indicates that the browser should interpret the content as
HTML source code.
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to
the client as part of the HTTP response. Then, println( ) is used to write some simple HTML
source code as the HTTP response.
Compile this source code and place the HelloServlet.class file in the directory named
c:Jsdk2.0examples. This ensures that it can be located by the servletrunner utility.
Start the servletrunner Utility
Open a command prompt window and type servletrunner to start that utility. This tool listens on
port 8080 for incoming client requests.
Start a Web Browser and Request the Servlet
Start a Web browser and enter the URL shown here:
http://localhost:8080/servlet/HelloServlet
The appletviewer Tool
Applets, as you have already learned in the earlier section, are programs written in Java that are
designed to run embedded in Web pages. You can run these applets using Web browser. The
appletviewer tool is a program that lets you run applets without the overhead of running a Web
browser. It provides an easy way to test applets written in the Java language.
java, The Java Interpreter
java is the interpreter that is used to execute compiled .java applications. The bytecode (.class)
that is the result of compiling a Java program is interpreted and executed.
Syntax
java [option] <classname>
where <classname> only includes the name of the class and not the extension (.class)
javap, The Java Disassembler
The Java disassembler is used to disassembler the Java bytecode to display the member
variables and the methods.
javah, The C-Header File Creation
The javah tool creates the C-header file necessary to extend you java code with the C language.
Syntax
javah [option] <classname>
The javadoc Tool (Documentation Generator)
The javadoc tool is used when you want to document the Java source file with proper comment
entries. Javadoc creates HTML documents, which can be viewed using any Web browser
Tiips and Triicks
Java is an interpreted language, which means that the Java code needs to be read and
interpreted during execution. This makes Java a platform-independent language but leaves the
Java program slower than the programs developed in compiled language like „C‟ and „C++‟.
Tip 1: General Rules
Check the algorithm first. The highest improvements are in most cases derived from changing the
algorithm. So check this first before you start “low-level” java code optimization.
Use the profiler. Use a profiler to find out what code takes the most time. Normally less than 10 %
of the code takes more than 90 % of the execution time.
Check the results. Check the improvement after each change by using a profiler.
Tips 2: Compiler Option
First of all use the optimizing options of the compilers. Sun‟s Java Compiler has the
–O option:
javac –o Yourclass.java
Tips 3: Profiling
To find out where to start with optimization and get the best improvements, use a profiling tool.
Use it also to check the result of each change in code.
Sun‟s JDK has a profiling options built in the Java interpreter.
java –prof Yourclass (for application)
java –prof sun.applet.AppletViewer yourPage.html (for applets)
The output is written to the file java.prof.
Tips 4: Integer Arithmetic
Whenever possible, use integer arithmetic instead of floating-point arithmetic. The data type
you should use is init. Avoid using double or float, because integer operations are much faster
than floating-point operations. Do not use short, because it often needs to be cast to init, since
most methods returns int values.
Try to convert floating-point calculations to integer calculations, e.g. Slow Fast
double r = Math.random ();
double x = Math.random () * r;
double y = Math.random () * r;
int r = Math.random () *100;
int x = Math.random () * r /100;
int y = Math.random () * r / 100;
The double returned by Math.random () is immediately converted to int.
Tips 5: Instantiation
Creating new objects is time-consuming. Try to avoid new operators. Reuse the existing objects.
This has advantages, because less memory and less collection are needed, both of which
reduces the execution time.
Tips 6: Pre-Calculation
Move loop-invariant code outside the loop and method-invariant calculations into the constructor or
the init () method, for example, Slow Fast
for ( int i = 0 ; i < 360 ; i ++ )
{
x = i* ( a / ( 180.0 / 3.14 ) );
} aRad = a / ( 180.0 / 3.14 );
for ( int i= 0 ; i < 360 ; i + + )
{
x = i * aRad;
}
Tips 7: Loops
First of all, make sure that the variable for the loop counter is a local integer variable and not an
instance or class variable.
Restructuring the loops may also improve the performance, because you can optimize the
compare operation, for example, Slow Fast
for ( int i = 0 ; i < max ; i+ +)
for ( int i = max ; - - i > = 0 ; )
The second loop has two advantages: The comparison is with a constant, which is faster than
comparison with another variable. Using the decrement operator directly in the comparison
expression is faster than a special increment operation.
Often , loops are used to move array elements to another array. In this case, the arraycopy ()
method is much faster.
Tips 8: Methods/Classes
Wherever possible declare your classes final. This increases the overall efficiency of a program, since
the Java interpreter does not need to look for the overridden methods in the derived classes.
Methods should be declared private, final or static, if possible. Public methods are only applicable if
they need to be called from other classes. Private methods can only be called from the same class,
final methods cannot be inherited, and static methods cannot be inherited, and static methods
cannot access instance variables.
Declare methods as synchronized only when necessary.
Sometimes, it is better write inline code instead of calling the method, if the called method is small,
for example, Math.max (). Slow Fast
mVar = Math.max ( avar , bvar );
mVar = aVar > bVar ? aVar : bVar ;
Tips 9: The. Operator
Using the ‟.‟ operator to access objects and instance variables also takes time. Avoid using
complex hierarchies.
For example, Slow Fast
a.b.c.d = 0;
a.b.c.e = null ;
a.b.c.f = “string”; o = a.b.c;
o.d = 0;
o.e = null ;
o.f = “string”;

More Related Content

PPT
1 java servlets and jsp
PPTX
java Servlet technology
PPTX
Javax.servlet,http packages
PDF
Java servlets
PPTX
Servlet.ppt
PPT
Java Servlets
DOC
Java Servlets & JSP
1 java servlets and jsp
java Servlet technology
Javax.servlet,http packages
Java servlets
Servlet.ppt
Java Servlets
Java Servlets & JSP

What's hot (20)

PPTX
PPT
Java servlets
PPT
Java Servlets
DOC
PDF
JEE Programming - 04 Java Servlets
PPT
Servlet ppt by vikas jagtap
PPT
J2EE - JSP-Servlet- Container - Components
PDF
Servlets lecture1
PPTX
Servlets
PPT
Java servlet life cycle - methods ppt
PPT
An Introduction To Java Web Technology
PPTX
Core web application development
PPT
Knowledge Sharing : Java Servlet
PPT
Jsp sasidhar
PPTX
Chapter 3 servlet & jsp
PDF
Weblogic
PDF
JAVA EE DEVELOPMENT (JSP and Servlets)
PPTX
Servletarchitecture,lifecycle,get,post
PPT
Java Server Faces (JSF) - Basics
PPTX
Java Server Pages
Java servlets
Java Servlets
JEE Programming - 04 Java Servlets
Servlet ppt by vikas jagtap
J2EE - JSP-Servlet- Container - Components
Servlets lecture1
Servlets
Java servlet life cycle - methods ppt
An Introduction To Java Web Technology
Core web application development
Knowledge Sharing : Java Servlet
Jsp sasidhar
Chapter 3 servlet & jsp
Weblogic
JAVA EE DEVELOPMENT (JSP and Servlets)
Servletarchitecture,lifecycle,get,post
Java Server Faces (JSF) - Basics
Java Server Pages
Ad

Similar to Jsp and Servlets (20)

DOCX
Online grocery store
PPTX
Java Servlet
PPTX
Web container and Apache Tomcat
PDF
Java servlet technology
DOC
Unit5 servlets
PPT
Ppt for Online music store
PPT
Introduction to the Servlet / JSP course
PPT
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
PPTX
UNIT-3 Servlet
DOCX
Server side programming bt0083
PPTX
AJppt.pptx
PPT
JEE Course - The Web Tier
PPTX
PDF
Liit tyit sem 5 enterprise java unit 1 notes 2018
ODP
servlet 2.5 & JSP 2.0
PPTX
JSP overview
PPTX
Java Server Pages(jsp)
DOC
Servlets and jsp pages best practices
PPT
Web Application Deployment
PDF
SERVER SIDE PROGRAMMING
Online grocery store
Java Servlet
Web container and Apache Tomcat
Java servlet technology
Unit5 servlets
Ppt for Online music store
Introduction to the Servlet / JSP course
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
UNIT-3 Servlet
Server side programming bt0083
AJppt.pptx
JEE Course - The Web Tier
Liit tyit sem 5 enterprise java unit 1 notes 2018
servlet 2.5 & JSP 2.0
JSP overview
Java Server Pages(jsp)
Servlets and jsp pages best practices
Web Application Deployment
SERVER SIDE PROGRAMMING
Ad

More from Raghu nath (20)

PPTX
Mongo db
PDF
Ftp (file transfer protocol)
PDF
MS WORD 2013
PDF
Msword
PDF
Ms word
PDF
Javascript part1
PDF
Regular expressions
PDF
Selection sort
PPTX
Binary search
PPTX
JSON(JavaScript Object Notation)
PDF
Stemming algorithms
PPTX
Step by step guide to install dhcp role
PPTX
Network essentials chapter 4
PPTX
Network essentials chapter 3
PPTX
Network essentials chapter 2
PPTX
Network essentials - chapter 1
PPTX
Python chapter 2
PPTX
python chapter 1
PPTX
Linux Shell Scripting
PPTX
Mongo db
Ftp (file transfer protocol)
MS WORD 2013
Msword
Ms word
Javascript part1
Regular expressions
Selection sort
Binary search
JSON(JavaScript Object Notation)
Stemming algorithms
Step by step guide to install dhcp role
Network essentials chapter 4
Network essentials chapter 3
Network essentials chapter 2
Network essentials - chapter 1
Python chapter 2
python chapter 1
Linux Shell Scripting

Recently uploaded (20)

PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Business Ethics Teaching Materials for college
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Pre independence Education in Inndia.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
RMMM.pdf make it easy to upload and study
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
2.FourierTransform-ShortQuestionswithAnswers.pdf
O7-L3 Supply Chain Operations - ICLT Program
Anesthesia in Laparoscopic Surgery in India
Renaissance Architecture: A Journey from Faith to Humanism
Business Ethics Teaching Materials for college
O5-L3 Freight Transport Ops (International) V1.pdf
Institutional Correction lecture only . . .
PPH.pptx obstetrics and gynecology in nursing
Week 4 Term 3 Study Techniques revisited.pptx
Microbial diseases, their pathogenesis and prophylaxis
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
VCE English Exam - Section C Student Revision Booklet
TR - Agricultural Crops Production NC III.pdf
Basic Mud Logging Guide for educational purpose
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Pre independence Education in Inndia.pdf
Insiders guide to clinical Medicine.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
RMMM.pdf make it easy to upload and study
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx

Jsp and Servlets

  • 2. JavaServer pages are actually, text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java Servlets the first time they are invoked. Java servlets are a key component of server-side Java development. A servlet is a small pluggable extension to a server that enhances the server’s functionality. Servlets allow developers to extend and customize any Java-enabled Server- a web server, a mail server, an application server or any custom server.
  • 3. JSP JavaServer pages are on the whole, text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java Servlets the first time they are invoked. The resulting servlet is a combination of the HTML from the JSP file and embedded dynamic content specified by the new tags That is not to say that JSPs must contain HTML. Some of them will contain only Java code; this is particularly useful when the JSP is responsible for a particular task like maintaining application flow.
  • 4. What is needed to write JSP based web application? As you will come to know in a short time, programming with JSP will need a thorough knowledge of how servlets are written and executed as the code segments inserted in a JSP are mostly Servlet code. If you have already written some ASP programs you may find it easy to work with JSP as there are so many similarities although they are 2 different technologies.
  • 5. How does JSP look? Before considering more technical details regarding JSP, let us see how a JSP file looks and what its static parts are and what its dynamics parts are: Consider the HelloWorld.jsp below 1. <HTML> 2. <HEAD> 3. <META NAME=”GENERATOR “ Content = “Microsoft Visual Studio 6.0”> 4. <TITLE></TITLE> 5. </HEAD> 6. <BODY> 7. <center><h1> 8. <% out.println(“Hello World!”); %> 9. </h1><center> 10. </BODY> 11. </HTML>
  • 6. How to test a JSP? Once a JSP is written next question is how do you test it? To test JSP we are going to use Java Web Server. The steps are as following: Copy the HelloWorld.jsp to c:JavaWebServer2.0public_html directory as it is the document root of the Java Web Server . (Assuming that the Java Web Server is installed in c:) Now start the Java Web Server.s web service. Open your browser window. Now in the address bar type in an address ashttp://IPAddress:: 8080/HelloWorld.jsp, where IP address of your machine.
  • 8. Servlets The rise of server-side Java applications is one of the latest and most exciting trends in Java programming. The Java language was originally intended for use in small, embedded devices. Java’s potentially as a server-side development platform had been sadly overlooked until recently. Businesses in particular have been quick to recognize Java’s potential on the server-side. Java is inherently suited for large client/server applications. The cross platform nature of Java is extremely useful for organizations that have a heterogeneous collection of servers running various flavors of the UNIX and Windows operating systems.
  • 9. Java’s modern, object-oriented memory-protected design allows developers to cut development cycles and increase reliability. In addition, Java’s built-in support for networking and enterprise APIs provides access to legacy data, easing the transition from older client/server system. Java servlets are a key component of server-side Java development. A servlet is a small pluggable extension to a server that enhances the server’s functionality. Servlets allow developers to extend and customize any Java-enabled Server- a web server, a mail server, an application server or any custom server.
  • 10. History of Web Application While servlets can be used to extend the functionality of any Java-enabled server, today they are most often used to extend web servers, providing a powerful, efficient replacement for CGI scripts. When you use servlet to create dynamic content for a web page or otherwise extend the functionality of a web server, you are in effect creating a Web application. While a web page merely displays static content and lets the user navigate through that content, a web application provides a more interactive experience. A web application may be as simple as a key word search on a document archive or as complex as an electronic storefront.
  • 11. Web applications are being deployed on the internet and on corporate intranets and extranets, where they have the potential to increase productivity and change role of servlets in any web application it is necessary to understand the architecture of any current web application. Web Architecture 2-tier Architecture Typical client/server systems are all 2-tiered in nature where the application resides entirely on the client PC and database resides on a remote server. But 2-tier systems have some disadvantages such as:
  • 12. ◦ The processing load is given to the PC while more powerful server acts as a traffic controller between the application and the database. ◦ Maintenance is the greatest problem. Imagine a situation where there is a small modification to be done in the application program. Then in case of a 2-tier architecture system, it is necessary to go to each client machine and make the necessary modifications to the programs loaded on them. ◦ That is the reason why the modern web applications are all developed based on 3-tier architecture.
  • 13. N-tier Architecture Although the title of this section is given as N-Tier architecture, here the concentration is on the 3-tier architecture. Basic reason for this is that any web application developed based on N-tier architecture functions just similar to typical 3-tier architecture.
  • 14. 1. First-Tier: 1. Basically the presentation Layer. 2. Represented by the GUI kind of thing. 1. Middle-Tier : 1. Application Logic 2. Third-Tier : 1. Data that is needed for the application.
  • 15. The basic idea behind 3-tier architecture is that to separate application logic from the user interface. This gives the flexibility to the design of the application as well as ease of maintenance. If you compare this with 2-tier architecture, it is very clear that in 3-tier architecture the application logic can be modified without affecting the user interface and the database.
  • 16. Typical Web Application A typical web application consists of following steps to complete a request and response. 1. Web application will collect data from the user. (First tier) 2. Send a request to the web server. 3. Run the requested server program. (Second and third tier) 4. Package up the data to be presented in the web browser. 5. Send it back to the browser for display. (First tier)
  • 17. Servlet Life Cycle This process can be broken down into the nine steps as follows: The server loads the servlet when it is first requested by the client or if configured to do so, at server start-up. The servlet may be loaded from either a local or a remote location using the standard Java class loading facility.
  • 18. This step is equivalent to the following code: Class c=Class.forName(“com.sourcestream.MyServlet”); It should be noted that when referring to servlets, the term load often refers to the process of both loading and instantiating the servlet.
  • 19. 2. The server creates one or more instances of the servlet class. Depending on implementation. The server may create a single instance that services all requests through multiple threads or create a pool of instances from which one chosen to service each new request. This step is equivalent to the following Java code:
  • 20. Servlet s=(Servlet) c.newInstance (); where ,c is the same Class object created in previous step. The server constructs a ServerConfig object that provides initialization information to the servlet. The server calls the servlet’s init () method, passing the object constructed in step 3 as a parameter. The init () method is guaranteed to finish execution prior to the servlet processing the first request. If the server has created multiple servlet instances (step 2), the init () method is called one time for each instance.
  • 21. The server constructs a ServletRequest or HttpServletRequest object from the data included in the client’s request. It also constructs a ServletResponse or HttpServletResponse object that provides methods for customizing the server’s response. The type of object passed in these two parameters depends on whether the servlet extends the GenericServlet class or the HttpServlet class, respectively.
  • 22. The server calls the servlet’s service() method passing the objects constructed in step 5 as parameters. When concurrent requests arrive, multiple service() methods can run in separate threads.
  • 23. The service () method processes the client request by evaluating the ServletRequest or HttpServletRequest object and responds using ServletResponse or HttpServletResponse object. If the server receives another request for this servlet, the process begins again at step 5.
  • 24. When instructed to unload the servlet, perhaps by the server administrator or programmatically by the servlet itself, the server calls the servlet‟s destroy() method. The servlet is then eligible for garbage collection.
  • 26. The Java Servlet Development Kit The Java Servlet Development Kit (JSDK) contains the class libraries that you will need to create servlets. A utility known as the servletrunner is also included, which enables you to test some of the servlets that you create You can download the JSDK without charge from the Sun Microsystems Web site at java.sun.com. Follow the instructions to install this toolkit on your machine. For a Windows machine, the default location of Version 2 of the JSDK is c:Jsdk2.0. The directory c:Jsdk2.0bin contains
  • 27. servletrunner.exe. Update your Path environment variable so that it includes this directory. The directory c:Jsdk2.0lib contains jsdk.jar. This JAR file contains the classes and interfaces that are needed to build servlets. Update your Classpath environment variable so that it includes c:Jsdk2.0libjsdk.jar.
  • 28. A Simple Servlet To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet. The basic steps are the following: 1. Create and compile the servlet source code. 2. Start the servletrunner utility. 3. Start a Web browser and request the servlet.
  • 29. Create and Compile the Servlet Source Code To begin, create a file named HelloServlet.java that contains the following program: import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Hello!"); pw.close(); } }
  • 30. First, note that this program imports the javax.servlet package, which contains the classes and interfaces required to build servlets. You will learn more about these classes and interfaces later in this chapter. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses. Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables a servlet to read data that is provided via the client request. The second argument is an ServletResponse object. This enables a servlet to formulate a response for the client.
  • 31. The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME type is text/html, which indicates that the browser should interpret the content as HTML source code. Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. Then, println( ) is used to write some simple HTML source code as the HTTP response.
  • 32. Compile this source code and place the HelloServlet.class file in the directory named c:Jsdk2.0examples. This ensures that it can be located by the servletrunner utility. Start the servletrunner Utility Open a command prompt window and type servletrunner to start that utility. This tool listens on port 8080 for incoming client requests. Start a Web Browser and Request the Servlet Start a Web browser and enter the URL shown here: http://localhost:8080/servlet/HelloServlet
  • 33. The appletviewer Tool Applets, as you have already learned in the earlier section, are programs written in Java that are designed to run embedded in Web pages. You can run these applets using Web browser. The appletviewer tool is a program that lets you run applets without the overhead of running a Web browser. It provides an easy way to test applets written in the Java language.
  • 34. java, The Java Interpreter java is the interpreter that is used to execute compiled .java applications. The bytecode (.class) that is the result of compiling a Java program is interpreted and executed. Syntax java [option] <classname> where <classname> only includes the name of the class and not the extension (.class)
  • 35. javap, The Java Disassembler The Java disassembler is used to disassembler the Java bytecode to display the member variables and the methods.
  • 36. javah, The C-Header File Creation The javah tool creates the C-header file necessary to extend you java code with the C language. Syntax javah [option] <classname>
  • 37. The javadoc Tool (Documentation Generator) The javadoc tool is used when you want to document the Java source file with proper comment entries. Javadoc creates HTML documents, which can be viewed using any Web browser
  • 38. Tiips and Triicks Java is an interpreted language, which means that the Java code needs to be read and interpreted during execution. This makes Java a platform-independent language but leaves the Java program slower than the programs developed in compiled language like „C‟ and „C++‟.
  • 39. Tip 1: General Rules Check the algorithm first. The highest improvements are in most cases derived from changing the algorithm. So check this first before you start “low-level” java code optimization. Use the profiler. Use a profiler to find out what code takes the most time. Normally less than 10 % of the code takes more than 90 % of the execution time. Check the results. Check the improvement after each change by using a profiler. Tips 2: Compiler Option First of all use the optimizing options of the compilers. Sun‟s Java Compiler has the –O option: javac –o Yourclass.java
  • 40. Tips 3: Profiling To find out where to start with optimization and get the best improvements, use a profiling tool. Use it also to check the result of each change in code. Sun‟s JDK has a profiling options built in the Java interpreter. java –prof Yourclass (for application) java –prof sun.applet.AppletViewer yourPage.html (for applets) The output is written to the file java.prof.
  • 41. Tips 4: Integer Arithmetic Whenever possible, use integer arithmetic instead of floating-point arithmetic. The data type you should use is init. Avoid using double or float, because integer operations are much faster than floating-point operations. Do not use short, because it often needs to be cast to init, since most methods returns int values.
  • 42. Try to convert floating-point calculations to integer calculations, e.g. Slow Fast double r = Math.random (); double x = Math.random () * r; double y = Math.random () * r; int r = Math.random () *100; int x = Math.random () * r /100; int y = Math.random () * r / 100; The double returned by Math.random () is immediately converted to int.
  • 43. Tips 5: Instantiation Creating new objects is time-consuming. Try to avoid new operators. Reuse the existing objects. This has advantages, because less memory and less collection are needed, both of which reduces the execution time.
  • 44. Tips 6: Pre-Calculation Move loop-invariant code outside the loop and method-invariant calculations into the constructor or the init () method, for example, Slow Fast for ( int i = 0 ; i < 360 ; i ++ ) { x = i* ( a / ( 180.0 / 3.14 ) ); } aRad = a / ( 180.0 / 3.14 ); for ( int i= 0 ; i < 360 ; i + + ) { x = i * aRad; }
  • 45. Tips 7: Loops First of all, make sure that the variable for the loop counter is a local integer variable and not an instance or class variable.
  • 46. Restructuring the loops may also improve the performance, because you can optimize the compare operation, for example, Slow Fast for ( int i = 0 ; i < max ; i+ +) for ( int i = max ; - - i > = 0 ; ) The second loop has two advantages: The comparison is with a constant, which is faster than comparison with another variable. Using the decrement operator directly in the comparison expression is faster than a special increment operation. Often , loops are used to move array elements to another array. In this case, the arraycopy () method is much faster.
  • 47. Tips 8: Methods/Classes Wherever possible declare your classes final. This increases the overall efficiency of a program, since the Java interpreter does not need to look for the overridden methods in the derived classes. Methods should be declared private, final or static, if possible. Public methods are only applicable if they need to be called from other classes. Private methods can only be called from the same class, final methods cannot be inherited, and static methods cannot be inherited, and static methods cannot access instance variables. Declare methods as synchronized only when necessary. Sometimes, it is better write inline code instead of calling the method, if the called method is small, for example, Math.max (). Slow Fast mVar = Math.max ( avar , bvar ); mVar = aVar > bVar ? aVar : bVar ;
  • 48. Tips 9: The. Operator Using the ‟.‟ operator to access objects and instance variables also takes time. Avoid using complex hierarchies. For example, Slow Fast a.b.c.d = 0; a.b.c.e = null ; a.b.c.f = “string”; o = a.b.c; o.d = 0; o.e = null ; o.f = “string”;