Java Servlets and JSP
So You would have heard of Client and Server. So what is Client and Server?
- So a Client is a computer which is capable of receiving information or using a particular service from the service providers (Servers).
- Similarly, a Server is a remote computer which provides information (data) or access to particular services.
What happens between the client and server is pretty simple to understand , i.e , the Client requests for something and the Server serves it as long as its present in it’s database.
So let’s start with Client Server Architecture.
So What is Client-Server Architecture?
Client Server Architecture is a computing model in which the server hosts, delivers and manages most of the resources or services or data which is required by the client. This type of architecture has one or more client computers connected to a central server over a network or internet connection.
Such an architecture is also known as a networking computing model or client/server network because all the requests and services are delivered over a network.
Now, let’s dive into Servlets.
Servlets
Servlet is a java program that runs inside JVM on the web server. It is basically used for developing dynamic web applications. You need to use the Servlet API to create servlets.
There are two packages that you must remember while using API, the javax.servlet
package that contains the classes to support generic servlet (protocol-independent servlet) and the javax.servlet.http
package that contains classes to support http servlet.
LifeCycle of Servlet :
- Servlet class is loaded : A Servlet class is loaded when first request for the servlet is received by the Web Container.
- Servlet instance is created : After the Servlet class is loaded, Web Container creates the instance of it. Servlet instance is created only once in the life cycle.
- init() method is invoked : Step 1, Step 2, Step 3 are executed only once, when the servlet is initially loaded. The init() method is called by the Web Container on servlet instance to initialize the servlet. For e.g, Syntax :
public void init(ServletConfig config) throws ServletException
- service() method is invoked : executed multiple times — once for every HTTP request to the servlet. The containers call the service() method each time the request for servlet is received. The service() method will then call the doGet() or doPost() method based on the type of the HTTP request. Syntax :
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
- destroy() method is invoked : executed when the servlet container unloads the servlet. The Web Container call the destroy() method before removing servlet instance, giving it a chance for cleanup activity.
ServletRequest Interface
ServletRequest interface is used to provide client request information to the servlet. Servlet container creates ServletRequest object from client request and pass it to the servlet service() method for processing. The child interface of ServletRequest is HttpServletRequest interface which adds the methods that relates to the HTTP protocol. It contains methods for session management, cookies and authorization of request.
Following are some of the methods of ServletRequest Interface :
- String getParameter(String name) — This method returns the request parameter as String.
- Object getAttribute(String name) — This method returns the value of named attribute as Object and null if it’s not present. This interface also provide methods for setting and removing attributes.
- setAttribute(String name, Object o) — stores an attribute in this request.
- String getServerName() — returns the hostname of the server.
- int getServerPort() — returns the port number of the server on which it’s listening.
- Cookies getCookies() — returns an array containing all of the Cookie objects the client sent with this request
- String getMethod() — Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
- HttpSession getSession() — returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session
ServletResponse Interface
Servlet API provides two important interfaces ServletResponse and HttpServletResponse to assist in sending response to client. In HttpServletResponse, Servlet container creates the ServletResponse object and passes it to Servlet service() method and later uses the response object to generate the HTML response for client.
Following are some of the methods of ServletResponse Interface :
- PrintWriter
getWriter()
returns a PrintWriter object that can send character text to the client. - void addCookie(Cookie cookie) — Used to add cookie to the response.
- void addHeader(String name, String value) — used to add a response header with the given name and value.
- String encodeURL(java.lang.String url) — encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
- String getHeader(String name) — return the value for the specified header, or null if this header has not been set.
- void sendRedirect(String location) — used to send a temporary redirect response to the client using the specified redirect location URL.
void setStatus(int sc) — used to set the status code for the response.
Request Dispatcher Interface
Request Dispatcher can be used whenever we want to call a servlet from another servlet. It is used to forward the request to another resource that can be HTML, JSP or another servlet in the same context.
Following are the methods of Request Dispatcher Interface :
- void forward(ServletRequest request, ServletResponse response) — forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
- void include(ServletRequest request, ServletResponse response) — includes the content of a resource (servlet, JSP page, HTML file) in the response.
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rs.forward(request,response);RequestDispatcher rd = request.getRequestDispatcher("index.html");
rs.include(request,response);
sendRedirect()
Method
sendRedirect() method redirects the response to another resource. This method actually makes the client(browser) to create a new request to get to the resource. The client can see the new url in the browser.
Session Management
Session Management is a mechanism used by the Web container to store session information for a particular user. There are four different techniques used by Servlet application for session management. They are as follows:
- Cookies : Cookies are small pieces of information that are sent in response from the web server to the client. They are stored on client’s computer.
pCookies ck = new Cookie("username", Suyash); //Create a Cookie object
ck.setMaxAge(30*60); //Set the maximum Age:
response.addCookie(ck); //Place the Cookie in HTTP response header:
Cookie[] cks = request.getCookies(); // getting the cookie for response object.
2. Hidden form field : Hidden form field can also be used to store session information for a particular client. In case of hidden form field a hidden field is used to store client state. In this case user information is stored in hidden field value and retrieved from another servlet.
3. URL Rewriting : In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of name/value pair seperated by an equal(=)
sign. When the User clicks on the URL having parameters, the request goes to the Web Container with extra bit of information at the end of URL. The Web Container will fetch the extra part of the requested URL and use it for session management. The getParameter() method is used to get the parameter value at the server side.
4. HttpSession : HttpSession object is used to store entire session with a specific client. We can store, retrieve and remove attribute from HttpSession object. Any servlet can have access to HttpSession object throughout the getsession() method of the HttpServletRequest object.
protected void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
}
Sevlet Filter
Filter is a compontent that you can use and configure to perform some filtering tasks. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. The Filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don’t need to change the servlet. The filtering API is defined by the Filter
, FilterChain
, and FilterConfig
interfaces in the javax.servlet
package. For creating a filter, we must implement Filter interface.
Following are the methods of filter life cycle :
- void
init(FilterConfig filterConfig)
: invoked by the web container to indicate to a filter that it is being placed into service. - void
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
: invoked by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. - void
destroy()
: invoked by the web container to indicate to a filter that it is being taken out of service.
Java Server Pages
Now, Java Server Pages (JSP) also follow a similar client-server architecture. However, unlike client-server , it is a 3 -tier architecture. It can be thought of as an extension to Servlet because it provides more functionality than servlet such as expression language, JSTL, etc.
A server (generally referred to as application or web server) supports the Java Server Pages. This server will act as a mediator between the client browser and a database. The following diagram shows the JSP architecture.
Here’s what happens 👇
- The user goes to a JSP page and makes the request via internet in user’s web browser.
- The JSP request is sent to the Web Server.
- Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet Engine.
- If the JSP file has been called the first time then the JSP file is parsed otherwise servlet is instantiated. The next step is to generate a servlet from the JSP file.
- The generated servlet output is sent via the Internet form web server to users web browser.
- Now in last step, HTML results are displayed on the users web browser.
jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
What differentiates JSP from HTML is the ability to use java code inside HTML. In JSP, you can embed Java code in HTML using JSP tags.
<HTML>
<BODY>
Hello World!
Current time is: <%= new java.util.Date() %>
</BODY>
</HTML>
Here’s how the life cycle flows in JSP :
1) Whenever container receives request from client, it does translation only when servlet class is older than JSP page otherwise it skips this phase.
2) Then the container –
- Compiles the corresponding servlet program
- Loads the corresponding servlet class
- Instantiates the servlet class
- Calls the jspInit() method to initialize the servlet instance (JSP container will do this job only when the instance of servlet file is not running or if it is older than the JSP file.)
3) A new thread then gets created, which invokes the_jspService() method, with a request (HttpServletRequest) and response (HttpServletRespnse) objects as parameters.
4) And finally, invokes the jspDestroy() method to destroy the instance of the servlet class.
The scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements:
1.Directives — JSP directives are used for controlling the processing of a JSP page. Directives provide information to the server on how the page should be processed. There are three types of directives:
- page directive : The page directive defines attributes that apply to an entire JSP page.
<%@ page attribute=”value” %>
- include directive : The include directive is used to include the contents of any resource it may be jsp file, html file or text file.
<%@ include file="header.html" %>
- taglib directive : The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags.
<%@ taglib uri = "http://www.myWebPage.com/tags" prefix="mytag" %>
2. Scriptlets — We can use java code in JSP using scriptlets. The JSP container moves the scriptlet content into the _jspService() method which is available to the server during processing of the request. In Scriplets there are these 3 tags :
- scriptlet tag : A scriptlet tag is used to execute java source code in JSP.
<% out.print("welcome to jsp"); %>
- expression tag : The code placed within JSP expression tag is written to the output stream of the response. It is mainly used to print the values of variable or method.
<%= “welcome to jsp” %>
- declaration tag : The JSP declaration tag is used to declare fields and methods.
<%! int cube(int n){ return n*n*n*; } %>
- Action Tags — They are used for performing an action during request processing phase of JSP life cycle. There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks. The action tags are used to control the flow between pages and to use Java Bean.
<jsp:forward page="relativeURL | <%= expression %>" />
//used to forward the request to another resource it may be jsp, html or another resource.
<jsp:include page="relativeURL | <%= expression %>" />
//used to include the content of another resource it may be jsp, html or servlet.
<jsp:useBean id= "instanceName" scope= "page | request | session | application" class= "packageName.className" type= "packageName.className" beanName="packageName.className | <%= expression >" > </jsp:useBean>
//used to locate or instantiate a bean class.
<jsp:setProperty name="instanceOfBean" property= "*" | property="propertyName" param="parameterName" | property="propertyName" value="{ string | <%= expression %>}" />
//sets a property value or values in a bean using the setter method.<jsp:getProperty name="instanceOfBean" property="propertyName" />
//returns the value of the property.
So this was all about Servlets and JSP, Thank You so much for taking out time for reading this article, will see you guys in the next blog!!