Java Servlet Complete Guide
Servlet is a Java class which runs on a web server side where application resides. This is a middle layer between web browser from where HTTP request originate and application web server.
Servlet helps us to get data submit by end users using POST request and return data to web browser using GET request from application web server.
Java web application J2EE helps us to create servlet classes and deploy on web server in the form of war file.
Java Servlet classes Java provides javax.servlet and javax.servlet.http packages to implement servlet program.
HttpServlet
HttpServlet class is an abstract class belongs to javax.servlet.http.HttpServlet package and extends GenericServlet abstract class. We can create servlet using HttpServlet class. HttpServlet methods GET, POST, PUT etc. allows us to handle HTTP requests.
Over all flow / Architecture
Below architecture is all about send data from web browser to servlet program and back from servlet program to web browser.
- The request will get originate from web browser to get and send data from to server.
- Request will use HTTP or HTTPS protocol to get or send data to server.
- The request from web browser will first reach to web server(apache tomcat, JBoss, etc.).
- Web server will call specific servlet program depending on servlet URL mapping, request type(GET, POST, DELETE etc. ), content type etc.
- Web browser can send or get data from server in predefined formats such as JSON, XML, binary etc.
- Servlet class will collect data from web browser. Servlet class will process the data collected from browser. Servlet class will and save/store same data in database. Servlet class can also collect data from database and send back to browser in same predefined format.
- Servlet class will process data using third party API data and other classes within application server.
Java Servlet Life cycle:
The web container maintains below Servlet class life cycle:
init()
This method called once only on servlet initialization on instance creation.
service()
This method will get call every time when request reach to Servlet class.
Usually the service() method doesn’t come into the picture, and most of the time we override servlet class doGet() and doPost() methods.
doGet() → The method sent HTTP GET request and allows us to retrieve data from application web server. Limited amount of data can be send as data get send either as part of URL or header. Get request is limited to a maximum of 2,048 characters, minus the number of characters in the actual path. Get() method is not secure and method mostly use
doPost() → The method sent HTTP POST request allows to send large amount of data to application web server. e.g. submission of any form. Sent data is secure as it is not part of request url.
doPut() → The method sent HTTP PUT request allows to place a file on the server. This can be done with the help of doPost() method too, i personally didn’t see much usage of doPut().
doHead() → The web browser sends a HTTP HEAD request when it wants to see only the headers of a response, such as Content-Type, Content-Length or the resource exist depending on response status code.
doDelete() → This method get call as part of DELETE HTTP request allows to delete a document, webpage or information from the server.
doOptions() → The OPTIONS HTTP request determines which HTTP methods server supports and returns appropriate headers.
doTrace() → HTTP TRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging.
HttpServletRequest → HttpServletRequest object contains the request the client has made of the servlet.
- response — an HttpServletResponse object that contains the response the servlet sends to the client.
destroy()
This method called once at the end of the servlet life cycle. This gives us an opportuning to clean up the resources or perform action at the end of the servlet life cycle.
HttpServletrRequest
HttpServletRequest interface extends the ServletRequest interface.
HttpServletRequest breaks the complete request in below part:
- Request URI
- Parameters
- Attributes
- ServletInputStream
requestURI
The requestURI comes out of request URL as shown below:
For example:
Below is the sample HTTP servlet URL
http://localhost:8080/Myproject/address/info/top.html?studentId=1
In HTTP servlet we get parse below info from HttpServletRequest
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
String servletPath = request.getServletPath();
String pathInfo = request.getPathInfo();
String queryStr = request.getQueryString();
OUTPUT:
GetRequestURI → /Myproject/address/info/top.html
GetContextPath → /Myproject
GetServletPath → /address
GetPathInfo → /info/top.html
GetQueryString → info=intro
Parameter:
HttpsServletRequest provides methods to access request parameter (or query String).
Below are list of methods:
getParameter(String parameterName) → This method help us to get request parameter(or query string) value.
request.getParameter(“studentId”)
OUTPUT: 1
getParameterNames() → This method help us to get all request parameter(or query string) Names.
String[] paramNames = request.getParameterNames();
OUTPUT: [“studentId”]
getParameterValues() → This method help us to get all request parameter(or query string) values.
String[] paramValues = request.getParameterValues();
OUTPUT: [“1”]
getHeader() → The HttpServletRequest object also contains request headers as a key and value pairs. Request header contains information related to referrer, content type, content length, etc.
Below is the code snippet to collect header in Servlet class.
String contentType = request.getHeader(“Content-Type”);
OUTPUT: application/json
getSession() → This method returns the current session associated with the request.
getSession(true) →It will create brand new session if not session exist.
getSession(false) →This method will return null if no session exist.
Syntax:
HttpSession session = request.getSession();
session.setAttribute(“studentId”, request.getParameter(“studentId”));
InputStream
getInputStream() → HTTP POST request allows us to send huge data to server as part of request body. HTTP POST request data can be collect as part of InputStream as shown below:
Syntax:
InputStream requestBodyInput = request.getInputStream();
Hello World Servlet Example
Please click here to check for “Hello World” servlet code: Hello World
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.