0% found this document useful (0 votes)
17 views80 pages

Servlet

The document provides an overview of the Servlet API, detailing the differences between applets and servlets, the lifecycle of a servlet, and session tracking techniques. It outlines the steps to create and run a servlet program, including the creation of a deployment descriptor and the use of HTTP methods like doGet() and doPost(). Additionally, it discusses JSP technology as an extension of servlets, highlighting its advantages in web application development.

Uploaded by

arati.sandbhor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views80 pages

Servlet

The document provides an overview of the Servlet API, detailing the differences between applets and servlets, the lifecycle of a servlet, and session tracking techniques. It outlines the steps to create and run a servlet program, including the creation of a deployment descriptor and the use of HTTP methods like doGet() and doPost(). Additionally, it discusses JSP technology as an extension of servlets, highlighting its advantages in web application development.

Uploaded by

arati.sandbhor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Servlet API

The javax.servlet and javax.servlet.http packages represent interfaces


and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are
used by the servlet or web container. These are not specific to any
protocol.
The javax.servlet.http package contains interfaces and classes that are
responsible for http requests only.
Applets Servlets

Applets are executed on client-side Servlets on other hand executed on


i.e applet runs within a Web the server-side i.e servlet runs on the
browser on the client machine. web Page on server.
Parent package of Servlet includes javax.servlet.* and
Parent package of Applet includes java.applet.* and java.awt.*
java.servlet.http.*

Important methods of applet includes init(), stop(), paint(), start(),


Lifecycle methods of servlet are init( ), service( ), and destroy( ).
destroy().

For the execution of the applet, a user interface is required such as AWT or
No such interface is required for the execution of servlet.
swing.

The applet requires user interface on the client machine for execution so it On the other hand, Servlets are executed on the servers and hence
requires more bandwidth. require less bandwidth.

Applets are more prone to risk as execution is on the client machine. Servlets are more secure as execution is under server security.
Life Cycle of a Servlet (Servlet
Life Cycle)
• The web container maintains the life cycle of a servlet instance. Let's
see the life cycle of the servlet:
1.Servlet class is loaded.
2.Servlet instance is created.
3.init method is invoked.
4.service method is invoked.
5.destroy method is invoked.
1.destroy method is invoked.
• 1) Servlet class is loaded
• The classloader is responsible to load the servlet class. The servlet
class is loaded when the first request for the servlet is received by the
web container.
• 2) Servlet instance is created
• The web container creates the instance of a servlet after loading the
servlet class. The servlet instance is created only once in the servlet
life cycle.
• 3) init method is invoked
• The web container calls the init method only once after creating the
servlet instance. The init method is used to initialize the servlet. It is
the life cycle method of the javax.servlet.Servlet interface. Syntax of
the init method is given below:
• public void init(ServletConfig config) throws ServletException
4) service method is invoked

• The web container calls the service method each time when request
for the servlet is received. If servlet is not initialized, it follows the first
three steps as described above then calls the service method. If
servlet is initialized, it calls the service method. Notice that servlet is
initialized only once. The syntax of the service method of the Servlet
interface is given below:
1.public void service(ServletRequest request, ServletResponse response
) throws ServletException, IOException
• 5) destroy method is invoked
• The web container calls the destroy method before removing the
servlet instance from the service. It gives the servlet an opportunity
to clean up any resource for example memory, thread etc. The syntax
of the destroy method of the Servlet interface is given below:
• public void destroy()
Steaps To Run Servlet Program
1.Create a directory structure
2.Create a Servlet
3.Compile the Servlet
4.Create a deployment descriptor
5.Start the server and deploy the project
6.Access the servlet
directory structure that must be followed to create the servlet.
2)Create a Servlet

There are three ways to create the servlet.


1.By implementing the Servlet interface
2.By inheriting the GenericServlet class
3.By inheriting the HttpServlet class
• The HttpServlet class is widely used to create the servlet because it
provides methods to handle http requests such as doGet(), doPost,
doHead() etc.
• In fact, the HTTP specification defines 8 standard HTTP request
methods (GET, PUT, POST, DELETE, HEAD, OPTIONS, TRACE &
CONNECT) each of which has a different meaning.
• In doGet(), the parameters are appended to the URL and sent along
with header information.
• This does not happen in case of doPost().
• In doPost(), the parameters are sent separately. Since most of the
web servers support only a limited amount of information to be
attached to the headers, the size of this header should not exceed
1024 bytes.
• doPost() does not have this constraint. Usually programmers find it
difficult to choose between doGet() and doPost().
• doGet() shall be used when small amount of data and insensitive data
like a query has to be sent as a request. doPost() shall be used when
comparatively large amount of sensitive data has to be sent. Examples
are sending data after filling up a form or sending login id and
password.
• DemoServlet.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10.
11.//writing html in the stream
12.pw.println("<html><body>");
13.pw.println("Welcome to servlet");
14.pw.println("</body></html>");
15.
16.pw.close();//closing the stream
3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:

Jar file Server


1) servlet-api.jar Apache Tomcat
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
• Two ways to load the jar file
1.set classpath
2.paste the jar file in JRE/lib/ext folder
• Put the java file in any folder. After compiling the java file, paste the
class file of servlet in WEB-INF/classes directory.
• 4)Create the deployment descriptor (web.xml file)
• The deployment descriptor is an xml file, from which Web Container
gets the information about the servet to be invoked.
• The web container uses the Parser to get the information from the
web.xml file. There are many xml parsers such as SAX, DOM and Pull.
• There are many elements in the web.xml file. Here is given some
necessary elements to run the simple servlet program.
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10.<url-pattern>/welcome</url-pattern>
11.</servlet-mapping>
12.
13.</web-app>
<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.
• 5)Start the Server and deploy the project
• To start Apache Tomcat server, double click on the startup.bat file
under apache-tomcat/bin directory.
• One Time Configuration for Apache Tomcat Server
• You need to perform 2 tasks:
1.set JAVA_HOME or JRE_HOME in environment variable (It is required
to start server).
2.Change the port number of tomcat (optional). It is required if another
server is running on same port (8080).
• How to set JAVA_HOME in environment variable?
• To start Apache Tomcat server JAVA_HOME and JRE_HOME must be
set in Environment variables.
• Go to My Computer properties -> Click on advanced tab then
environment variables -> Click on the new tab of user variable ->
Write JAVA_HOME in variable name and paste the path of jdk folder
in variable value -> ok -> ok -> ok.
http://localhost:9999/demo/
welcome
1.http://localhost:9999/demo/welcome
• The server checks if the servlet is requested for the first time.
• If yes, web container does the following tasks:
• loads the servlet class.
• instantiates the servlet class.
• calls the init method passing the ServletConfig object
• Else
• calls the service method passing request and response objects
• The web container calls the destroy method when it needs to remove
the servlet such as at time of stopping server or undeploying the project.
Session Tracking in Servlets

• Session simply means a particular interval of time.


• Session Tracking is a way to maintain state (data) of an user. It is also
known as session management in servlet.
• Http protocol is a stateless so we need to maintain state using session
tracking techniques. Each time user requests to the server, server
treats the request as the new request. So we need to maintain the
state of an user to recognize to particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:

1.Cookies
2.Hidden Form Field
3.URL Rewriting
4.HttpSession
• index.html
1.<form action="servlet1" method="post">
2.Name:<input type="text" name="userName"/><br/>
3.<input type="submit" value="go"/>
4.</form>
• FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
1. Cookie ck=new Cookie("uname",n);//creating cookie object
2. response.addCookie(ck);//adding cookie in the response
3.
4. //creating submit button
5. out.print("<form action='servlet2'>");
6. out.print("<input type='submit' value='go'>");
7. out.print("</form>");
8.
9. out.close();
10.
11. }catch(Exception e){System.out.println(e);}
12. }
13.}
SecondServlet.java

•import java.io.*;
•import javax.servlet.*;
•import javax.servlet.http.*;

•public class SecondServlet extends HttpServlet {

•public void doPost(HttpServletRequest request, HttpServletResponse response){
• try{
• response.setContentType("text/html");
• PrintWriter out = response.getWriter();

• Cookie ck[]=request.getCookies();
• out.print("Hello "+ck[0].getValue());

• out.close();

• }catch(Exception e){System.out.println(e);}
• }


•}
web.xml

•<web-app>

•<servlet>
•<servlet-name>s1</servlet-name>
•<servlet-class>FirstServlet</servlet-class>
•</servlet>

•<servlet-mapping>
•<servlet-name>s1</servlet-name>
•<url-pattern>/servlet1</url-pattern>
•</servlet-mapping>
•<servlet>
•<servlet-name>s2</servlet-name>
•<servlet-class>SecondServlet</servlet-class>
•</servlet>

•<servlet-mapping>
•<servlet-name>s2</servlet-name>
•<url-pattern>/servlet2</url-pattern>
•</servlet-mapping>

•</web-app>
• 2) Hidden Form Field
• In case of Hidden Form Field a hidden (invisible) textfield is used for
maintaining the state of an user.
• In such case, we store the information in the hidden field and get it
from another servlet. This approach is better if we have to submit
form in all the pages and we don't want to depend on the browser.
• Let's see the code to store value in hidden field.
1.<input type="hidden" name="uname" value="Vimal Jaiswal">
Real application of hidden form
field
It is widely used in comment form of
a website. In such case, we store
page id or page name in the hidden
field so that each page can be
uniquely identified.
• Advantage of Hidden Form Field
1.It will always work whether cookie is disabled or not.
• Disadvantage of Hidden Form Field:
1.It is maintained at server side.
2.Extra form submission is required on each pages.
3.Only textual information can be used.
Example of using Hidden Form Field
In this example, we are storing the name of the user in a hidden textfield and getting that value from
another servlet.
• index.html
1.<form action="servlet1">
2.Name:<input type="text" name="userName"/><br/>
3.<input type="submit" value="go"/>
4.</form>
FirstServlet.java

•import java.io.*;
•import javax.servlet.*;
•import javax.servlet.http.*;

•public class FirstServlet extends HttpServlet {
•public void doGet(HttpServletRequest request, HttpServletResponse response){
• try{

• response.setContentType("text/html");
• PrintWriter out = response.getWriter();

• String n=request.getParameter("userName");
• out.print("Welcome "+n);
•//creating form that have invisible textfield
• out.print("<form action='servlet2'>");
• out.print("<input type='hidden' name='uname' value='"+n+"'>");
• out.print("<input type='submit' value='go'>");
• out.print("</form>");
• out.close();

• }catch(Exception e){System.out.println(e);}
• }

•}
SecondServlet.java

•import java.io.*;
•import javax.servlet.*;
•import javax.servlet.http.*;
•public class SecondServlet extends HttpServlet {
•public void doGet(HttpServletRequest request, HttpServletResponse response)
• try{
• response.setContentType("text/html");
• PrintWriter out = response.getWriter();

• //Getting the value from the hidden field
• String n=request.getParameter("uname");
• out.print("Hello "+n);

•out.close();
• }catch(Exception e){System.out.println(e);}
• }
•}
web.xml

•<web-app>

•<servlet>
•<servlet-name>s1</servlet-name>
•<servlet-class>FirstServlet</servlet-class>
•</servlet>

•<servlet-mapping>
•<servlet-name>s1</servlet-name>
•<url-pattern>/servlet1</url-pattern>
•</servlet-mapping>
•<servlet>
•<servlet-name>s2</servlet-name>
•<servlet-class>SecondServlet</servlet-class>
•</servlet>

•<servlet-mapping>
•<servlet-name>s2</servlet-name>
•<url-pattern>/servlet2</url-pattern>
•</servlet-mapping>

•</web-app>
JSP
• JSP technology is used to create web application just like Servlet
technology. It can be thought of as an extension to Servlet because it
provides more functionality than servlet such as expression language,
JSTL, etc.
• A JSP page consists of HTML tags and JSP tags. The JSP pages are
easier to maintain than Servlet because we can separate designing
and development. It provides some additional features such as
Expression Language, Custom Tags, etc.
• Advantages of JSP over Servlet
• There are many advantages of JSP over the Servlet. They are as
follows:
• 1) Extension to Servlet
• JSP technology is the extension to Servlet technology. We can use all
the features of the Servlet in JSP. In addition to, we can use implicit
objects, predefined tags, expression language and Custom tags in JSP,
that makes JSP development easy.
• 2) Easy to maintain
• JSP can be easily managed because we can easily separate our
business logic with presentation logic. In Servlet technology, we mix
our business logic with the presentation logic.
• 3) Fast Development: No need to recompile and redeploy
• If JSP page is modified, we don't need to recompile and redeploy the
project. The Servlet code needs to be updated and recompiled if we
have to change the look and feel of the application.
• 4) Less code than Servlet
• In JSP, we can use many tags such as action tags, JSTL, custom tags,
etc. that reduces the code. Moreover, we can use EL, implicit objects,
etc.
• The Lifecycle of a JSP Page
• The JSP pages follow these phases:
• Translation of JSP Page
• Compilation of JSP Page
• Classloading (the classloader loads class file)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( the container invokes jspInit() method).
• Request processing ( the container invokes _jspService() method).
• Destroy ( the container invokes jspDestroy() method).
scriptlet tag
• index.jsp Let's see the simple example of JSP where we are using the
scriptlet tag to put Java code in the JSP page. We will learn scriptlet
tag later.
1.<html>
2.<body>
3.<% out.print(2*5); %>
4.</body>
5.</html>
• It will print 10 on the browser.
• How to run a simple JSP Page?
• Follow the following steps to execute this JSP page:
• Start the server
• Put the JSP file in a folder and deploy on the server
• Visit the browser by the URL
http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp
• The Directory structure of JSP
• The directory structure of JSP page is same as Servlet. We contain the
JSP page outside the WEB-INF folder or in any directory.
Servlet JSP
Servlet is a java code. JSP is a HTML based code.
Writing code for servlet is harder than JSP as it is
JSP is easy to code as it is java in HTML.
HTML in java.
Servlet plays a controller role in the hasMVC JSP is the view in the MVC approach for showing
approach. output.
JSP is slower than Servlet because the first step in JSP
Servlet is faster than JSP. lifecycle is the translation of JSP to java code and then
compile.

Servlet can accept all protocol requests. JSP only accepts HTTP requests.

In Servlet, we can override the service() method. In JSP, we cannot override its service() method.

In Servlet by default session management is not


In JSP session management is automatically enabled.
enabled, user have to enable it explicitly.

In Servlet we have to implement everything like


In JSP business logic is separated from presentation
business logic and presentation logic in just one
logic by using javaBeans.
servlet file.

You might also like