SlideShare une entreprise Scribd logo
1  sur  48
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.
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.
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”;

Contenu connexe

Tendances

Java servlets
Java servletsJava servlets
Java servletslopjuan
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml Sah
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Core web application development
Core web application developmentCore web application development
Core web application developmentBahaa Farouk
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 

Tendances (20)

Servlets
ServletsServlets
Servlets
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
JDBC
JDBCJDBC
JDBC
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Servlets lecture1
Servlets lecture1Servlets lecture1
Servlets lecture1
 
Servlets
ServletsServlets
Servlets
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Core web application development
Core web application developmentCore web application development
Core web application development
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Weblogic
WeblogicWeblogic
Weblogic
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 

Similaire à Jsp and Servlets

Online grocery store
Online grocery storeOnline grocery store
Online grocery storeKavita Sharma
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache TomcatAuwal Amshi
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music storeADEEBANADEEM
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course JavaEE Trainers
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.pptsindhu991994
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
JEE Course - The Web Tier
JEE Course - The Web TierJEE Course - The Web Tier
JEE Course - The Web Tierodedns
 
Liit tyit sem 5 enterprise java unit 1 notes 2018
Liit tyit sem 5 enterprise java  unit 1 notes 2018 Liit tyit sem 5 enterprise java  unit 1 notes 2018
Liit tyit sem 5 enterprise java unit 1 notes 2018 tanujaparihar
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0megrhi haikel
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)Manisha Keim
 
Servlets and jsp pages best practices
Servlets and jsp pages best practicesServlets and jsp pages best practices
Servlets and jsp pages best practicesejjavies
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deploymentelliando dias
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGPrabu U
 

Similaire à Jsp and Servlets (20)

Online grocery store
Online grocery storeOnline grocery store
Online grocery store
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
JEE Course - The Web Tier
JEE Course - The Web TierJEE Course - The Web Tier
JEE Course - The Web Tier
 
Servlets
ServletsServlets
Servlets
 
Liit tyit sem 5 enterprise java unit 1 notes 2018
Liit tyit sem 5 enterprise java  unit 1 notes 2018 Liit tyit sem 5 enterprise java  unit 1 notes 2018
Liit tyit sem 5 enterprise java unit 1 notes 2018
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
 
JSP overview
JSP overviewJSP overview
JSP overview
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Servlets and jsp pages best practices
Servlets and jsp pages best practicesServlets and jsp pages best practices
Servlets and jsp pages best practices
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 

Plus de Raghu nath

Ftp (file transfer protocol)
Ftp (file transfer protocol)Ftp (file transfer protocol)
Ftp (file transfer protocol)Raghu nath
 
Javascript part1
Javascript part1Javascript part1
Javascript part1Raghu nath
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaghu nath
 
Selection sort
Selection sortSelection sort
Selection sortRaghu nath
 
Binary search
Binary search Binary search
Binary search Raghu nath
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)Raghu nath
 
Stemming algorithms
Stemming algorithmsStemming algorithms
Stemming algorithmsRaghu nath
 
Step by step guide to install dhcp role
Step by step guide to install dhcp roleStep by step guide to install dhcp role
Step by step guide to install dhcp roleRaghu nath
 
Network essentials chapter 4
Network essentials  chapter 4Network essentials  chapter 4
Network essentials chapter 4Raghu nath
 
Network essentials chapter 3
Network essentials  chapter 3Network essentials  chapter 3
Network essentials chapter 3Raghu nath
 
Network essentials chapter 2
Network essentials  chapter 2Network essentials  chapter 2
Network essentials chapter 2Raghu nath
 
Network essentials - chapter 1
Network essentials - chapter 1Network essentials - chapter 1
Network essentials - chapter 1Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
Linux Shell Scripting
Linux Shell ScriptingLinux Shell Scripting
Linux Shell ScriptingRaghu nath
 

Plus de Raghu nath (20)

Mongo db
Mongo dbMongo db
Mongo db
 
Ftp (file transfer protocol)
Ftp (file transfer protocol)Ftp (file transfer protocol)
Ftp (file transfer protocol)
 
MS WORD 2013
MS WORD 2013MS WORD 2013
MS WORD 2013
 
Msword
MswordMsword
Msword
 
Ms word
Ms wordMs word
Ms word
 
Javascript part1
Javascript part1Javascript part1
Javascript part1
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Selection sort
Selection sortSelection sort
Selection sort
 
Binary search
Binary search Binary search
Binary search
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)
 
Stemming algorithms
Stemming algorithmsStemming algorithms
Stemming algorithms
 
Step by step guide to install dhcp role
Step by step guide to install dhcp roleStep by step guide to install dhcp role
Step by step guide to install dhcp role
 
Network essentials chapter 4
Network essentials  chapter 4Network essentials  chapter 4
Network essentials chapter 4
 
Network essentials chapter 3
Network essentials  chapter 3Network essentials  chapter 3
Network essentials chapter 3
 
Network essentials chapter 2
Network essentials  chapter 2Network essentials  chapter 2
Network essentials chapter 2
 
Network essentials - chapter 1
Network essentials - chapter 1Network essentials - chapter 1
Network essentials - chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Linux Shell Scripting
Linux Shell ScriptingLinux Shell Scripting
Linux Shell Scripting
 
Perl
PerlPerl
Perl
 

Dernier

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 

Dernier (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

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.
  • 7.
  • 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.
  • 25.
  • 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”;