Servlet
Servlet
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
<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
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.