Java Servlets

in java •  3 years ago 

Servlets

Servlet introduction

  • Servlets are web pages generated by the web server in response to the request received from the clients. It extends the functionality of web server by dynamically generating web pages. It is a program that runs on the server side.
  • Content type of servlets is MIME(Multipurpose internet mail extension), for example text/plain, text/html
  • Before servlets, CGI(Common gateway interface) was used. For development of CGI, various languages were used such as C, C++, Perl.
  • But serious performance issues were noticed in CGI.
  • Hence servlets were used over CGI because it overcame many drawbacks of CGI.

Why are servlets preferred over CGI?

  • Performance of servlets is always better than CGI.
  • CGI is platform dependent while Servlets are platform independent as they are developed using java language.
  • Several web servers from popular vendors like Sun, Netscape and Microsoft offered servlet API.
  • Servlets are secured as the java security manager helps us to set restrictions to access resources of server machines.

There are two types of servlets

  • Generic servlets
  • HTTP servlets

Difference between Generic and HTTP

Generic servlets
Here we use javax.servlet package
Protocol independent
It will execute the service() method for handling requests.
Extends Object class and implements Servlet, ServletConfig, and Serializable interfaces.

HTTP servlets
Here we use javax.servlet.http package
Protocol dependent
It will execute doGet() and doPost() methods for handling requests.
Extends GenericServlet and implements Serializable interface.

Lifecycle of a servlet

  • The methods executed in the servlet life cycle are init(), service() and destroy()
  • Steps of a servlet lifecycle are as follows
  • The server class is loaded into the address space when first request for the servlet is received by the web container.
  • If instance is not present already then the web container creates an instance of servlet after loading the servlet class.
  • Initialisation takes place via the init() method. Here we can set the initialisation and configuration parameters.
    Syntax: public void init(ServletConfig config) throws ServletException
  • The service() method is invoked in order to handle the requests received from client. This method is called by the web container each time a request for servlet is received.
    Syntax: public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
  • In the last step, the destroy method is invoked and it gives the servlet the opportunity to clean up and release any resources allocated to it. Garbage collection takes place.
    Syntax: public void destroy()

Servlets can be created using two methods

  • By inheriting GenericServlet class
  • By inheriting HttpServlet class

Steps of creating a Servlet example

  • Create a directory structure
    • Root -> WEB-INF -> Classes -> .class file
    •       |                    |-> web.xml (This is the deployment descriptor)
      
    •       |                    |-> lib folder
      
    •       |-> html
      
    •       |-> static resources such as images, .css, etc.
      
  • Create a servlet
  • Compile the servlet
  • Create deployment descriptor
  • Start the server and deploy the project
  • Access the servlet

Key difference between doGet() and doPost()

  • In doGet(), the parameters are appended to the URL~~~1024 mb of data can be sent~~~Parameters are not encrypted~~~faster
  • In doPost(), parameters are sent separately and not as a part of URL~~~No restrictions for data~~~Parameters are encrypted~~~slower

doGet() doPost()
Used to get a resource from web server. Hence it is mostly read-only request. No updation takes place on the server side. Used to post information to the server. Hence performs update or write operation.
In get request, the data that we desire is sent as a part of query string. This give rise to many problems. In post request, the data is sent as to the server as a part of body. This has multiple advantages.
Only character data(ASCII) can be sent as a part of get request. Maximum number of characters that can be sent is 2048 bytes. ASCII characters and binary data both can be sent. No restriction on the amount of data that can be sent.
Security is less as query string is not encrypted. Security is more as data is sent as a part of body.

Cookies

  • A cookie is a small piece of information which is sent by the web server or servlet to the client and later sent back to the server.
  • Cookies are saved on the client side in the browser.
  • Each cookie can uniquely identify a client and hence it is commonly used for session management.
  • Cookie is a predefined class in the servlet-api present under javax.servlet.http package.
  • Disadvantage is that only textual information can be stored

Two types of cookies

  • Persistent - Stored permanently, deleted when browser is closed
  • Non-persistent - Not stored permanently, deleted only when user logs out

Simple code to create cookie

  • Cookie ck = new Cookie(“user”, “vjtech”); //(String cookieName, String cookieValue)
  • response.addCookie(ck); //adding cookie in response, addCookie(Cookie ck) belongs to HttpServletResponse

Simple code to get all cookies

  • Cookie[] ckArray = request.getCookies(); //getCookies() belongs to HttpServletRequest

Session and Session Tracking

  • getSession() - This method will create HttpSession object.

JSP (Java server page)

  • Jsps are similar to ASP(Active server pages)
  • Jsp is used on the server side.
  • Jsp do not use servlet tag in a html file.
  • Every block of code in jsp is called as scriplet.
  • Scriplet begins with <% and ends with %>.
  • Jsp has got four predefined variables
      1. request: This is servlet request and is object of HttpServletRequest class
      1. response: This is servlet response and is object of HttpServletResponse class
      1. out: It is an output reader and an object of PrintWriter class
      1. in : It is an input reader and an object of BufferedReader class
  • Extension for jsp files is .jsp
  • If we want to run jsp file then we can use URL: http://server:port/hello.jsp
  • Example of hello.jsp
    < html >< body >
    if(request.getParameter(“name”) == null) {
    out.println(“Hello - no specified user…”)
    } else {
    out.println(“Hello ” + request.getParameter(“name”));
    }

Expression and directives

  • As we know jsp use scriplets, similarly jsp also use expressions and directives.
  • A JSP expression begin with <%= and ends with %>
  • A JSP directive begin with <%@ and ends with %>
  • We use directives like <%%@varname = “value” %>
  • There are total six variables that can be used
      1. content_type:
      • Text/plain
      1. import
      • Java.io.*
      1. extends: used to mention the superclass
      • <%@ extends = “java.awt.Frame” %>
      1. implements
      • <%@ implements = “java.awt.event.ActionListener %>
      1. method
      • doGet, doPost
      1. language
      • java

JSP lifecycle

  • Step 1: Jsp compilation
    • Jsp code is parsed
    • That code is converted to a servlet code
    • That servlet code is compiled
  • Step 2: Jsp initialisation
    • In this step, jspInit() method is called. This method is called only once in the lifetime of JSP.
    • This method is generally used to initialise database connections, open files and create lookup tables.
  • Step 3: Jsp execution
    • The _jspService(HttpServletRequest req, HttpServletResponse res) method is called
    • It is responsible for generating responses for all the standard HTTP methods like GET, POST, DELETE, etc.
  • Step 4: Jsp cleanup
    • jspDestroy() method is called. It is jsp equivalent of destroy method for servlets.
    • It is used to perform any cleanup tasks such as releasing database connections or closing files.

THANK YOU ALL!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!