Tuesday 25 September 2018

Java Servlet


Java servlet are programs that run on Web or Application server and act as a middle layer between an invitation coming from an internet browser or other client and database or applications on the HTTP Server.

Simple Servlet: 

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 pro = response.getWriter();
           pw.println("<B> Hello! </B>");
           pw.close();

      }
}

Writing Servlet: 

Servlet Types: 


Servlet related classes are included in two main Packages.
  • javax.servlet
  • javax.servlet.http
Every servlet must implements the javax.       
 servlet.Servlet interface, it contains the servlet's life cycle method. 

In order to write down your own servlet, you'll be  subclass from GenericServlet or HttpServlet 

Genereric Servlet class 

  • Available in javax.servlet package 
  • Implements javax.servlet.Servlet
  • Extend your class from this class if you're curious about writing protocol independent servlet.

HttpServlet Class: 

  • Available in javax.servlet.http package
  • Extends from GenericServlet class            
  • Add functionality for writing Http specific servlet as compared to GenericServlet. 
  • Extends your class from HttpServlet, if you would like to write down http based Servlet. 
 
     

GET: 

       Request a page from server. This is the normal request used when browsing web pages.

POST: 

         This request is used to pass information to the server. Its most common use is with HTML forms.

PUT: 

       Use to put a replacement webpage on a server.

DELETE: 

           Used to delete a webpage from the server.

Reading HTML from Data using Servlet:

Types of data send to a WebServer

  • From Data
  • HTTP Request Header Data. 
The HTTPServletRequest object contain three main methods for extracting from data submitted by the user.

  1.  getParameter(String name): 

  • used to retrieve single from parameter and return String like  name specified. 
  • Empty String is returned in the case when user does not enter within the specified form field.   

     2.  getParameterValue(String name): 

  • return an array of string object containing all of the given values of the given request parameter. 
  • if the name specified does not exist, null is returned. 

     3.   getParameterNames(): 

  • it returns enumeration of string object containing the names of the parameters that come with the request. 
  • if the request has no parameters, the function return an empty enumeration.



No comments:

Post a Comment

If you have any doubt please let me know

Methods in JAVA Language

 In general, a way may be thanks to perform some task. Similarly, the tactic in Java may be a collection of instructions that performs a sel...