Unit - 3
Java Servlet
Servlets are server-side components that provide a flexible framework for building server-side web applications. CGI was originally created to provide server-side functionality to web applications. Although CGI was crucial in the Internet's growth, its performance, scalability, and reusability concerns made it a less than ideal alternative. All of that changes with Java Servlets. Java servlets are a server-side processing framework built from the ground up utilizing Sun's write once, run anywhere technology.
Web developers can use servlets to create quick and efficient server-side applications that can be launched on any servlet-capable web server. Servlet is completely contained within the Java Virtual Machine. Because the servlet operates on the server, it is not affected by browser compatibility.
Because Servlet Technology is based on Java, Servlet-based web applications are secure, scalable, and robust.
A web application is built using Servlet technology (resides at server side and generates a dynamic web page).
Because of the Java programming language, servlet technology is dependable and scalable. CGI (Common Gateway Interface) scripting language was widely used as a server-side programming language prior to Servlet. This technology, however, had a number of drawbacks.
The Servlet API has several interfaces and classes, such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, and so on.
Depending on the background, a servlet can be represented in a variety of ways.
● A web application is created using the Servlet technology.
● Servlet is an API that includes documentation as well as a variety of interfaces and classes.
● Any Servlet must have a Servlet interface that must be implemented.
● Servlet is a class that enhances the server's capabilities and responds to incoming requests. It is capable of responding to any message.
● A servlet is a server-side web component that allows you to build a dynamic web page.
Advantages
In comparison to CGI, Servlets have a lot of advantages. They are as follows:
- Platform Independent
Because servlets are built entirely in Java, they are platform agnostic. Servlets can run on any web server that supports Servlets. Assuming you construct a web application on a Windows PC using the Java web server, you can easily run it on an Apache web server (if Apache Serve is installed) without having to modify or compile the code. Servlets' platform independence gives them a significant edge over other servlet alternatives.
2. Performance
Java programs are slow due to the interpreted nature of the language. The java servlets, on the other hand, are extremely fast. These issues arise as a result of the way servlets operate on a web server. The initialization of any software takes a large amount of time. However, when a servlet receives a request, it is initialized the first time it receives it and remains in memory until it times out or the server shuts down. To handle a new request, the servlet simply spawns a new thread and calls the servlet's service function. Traditional CGI scripts, on the other hand, launch a new process to serve the request.
3. Extensibility
Java Servlets are written in Java, an object-oriented programming language that may be expanded or polymorphed to create new objects. As a result, java servlets take advantage of all of these benefits and can be extended from existing classes to deliver the best possible solutions.
4. Safety
Memory management, exception handling, and other security features are all available in Java. Servlets inherited all of these characteristics and has grown to be a very powerful web server extension.
5. Secure
Because servlets are server-side components, they inherit the web server's security. Java Security Manager is also beneficial to servlets.
Key takeaway
- Servlets are server-side components that provide a flexible framework for building server-side web applications.
- CGI was originally created to provide server-side functionality to web applications.
Static Vs Dynamic website
A website is a grouping of related web pages that may include text, graphics, audio, or video. The home page is the first page of a website. To access a website, you must type the website's unique internet address (URL) into your browser.
There are two sorts of websites:
● Static Website
● Dynamic Website
Static website
A static website is the most basic and straightforward sort of website. To make a static website, you don't need to know anything about web programming or database architecture. HTML is used to code its web pages.
The codes are fixed for each page, ensuring that the information on the page does not change and that it appears to be printed.
Fig 1: Static website
Dynamic website
A dynamic website is a collection of dynamic web pages with dynamic content. It uses a database or a Material Management System to get content (CMS). As a result, when you change or update the database's content, the website's content is likewise changed or updated.
To generate dynamic content, dynamic websites use client-side scripting, server-side scripting, or both.
Client-side scripting creates material on the client computer based on the user's input. The web browser retrieves a web page from the server and interprets the code to display information to the user.
As server side scripting, the software runs on the server, where it is processed before being transmitted to the user in plain pages.
Fig 2: Dynamic website
Static Vs Dynamic website
Static | Dynamic |
Every time the page is loaded, the prebuilt content remains the same. | Content is produced in a timely manner and is updated on a regular basis. |
Every request receives the exact identical response. | It's possible that it'll generate different HTML for each request. |
The biggest benefit of a static website is its flexibility. | The key benefit of a dynamic website is the Content Management System (CMS). |
The HTML code is used to create a website. | It develops a website using server-side languages such as PHP,SERVLET, JSP, and ASP.NET, among others. |
Only when someone publishes and edits the file does the content change (sends it to the web server). | When the page is loaded, the page contains "server-side" code that allows the server to generate unique content. |
HTTP
The Hypertext Transfer Protocol (HTTP) is an application-level protocol for hypermedia information systems that are collaborative and distributed. It is a data communication protocol that is used to connect a client and a server.
HTTP is a TCP/IP-based communication protocol that is used on the World Wide Web (WWW) to deliver data such as picture files, query results, HTML files, and so on. The default port is TCP 80. It establishes a common method for computers to communicate with one another.
Fig 3: HTTP
Characteristics
HyperText Transfer Protocol's Basic Characteristics:
● It's the protocol that lets web servers and browsers communicate across the internet.
● It's a protocol for sending and receiving requests.
● By default, it uses TCP port 80 for reliable TCP communications.
● It is stateless, which means that each request is treated as a new one. In other words, by default, the server does not recognise the user.
Features
The HTTP protocol has three basic characteristics that make it a simple and powerful communication system:
● HTTP is media independent: It defines that HTTP can send any sort of media content as long as both the server and the client can process the data.
● HTTP is connectionless: It's a connectionless strategy in which an HTTP client, such as a browser, initiates an HTTP request, then disconnects from the server and waits for a response.
● HTTP is stateless: Only during the current request are the client and server aware of each other. Both of them forget about each other after that. Because of the protocol's stateless nature, neither the client nor the server can keep track of various requests across web pages.
Architecture
The figure below demonstrates the basic architecture of a web application and where HTTP is located:
The HTTP protocol is a request/response protocol with a client/server architecture. Web browsers, search engines, and other applications act as HTTP clients, whereas the Web server, such as Servlet, acts as a server.
HTTP request
HTTP requests are requests sent by a computer to a web server that contain a variety of potentially interesting information.
The request is sent to the server by the HTTP client in the form of a request message, which comprises the following information:
● The Request-line
● The analysis of source IP address, proxy and port
● The analysis of destination IP address, protocol, port and host
● The Requested URI (Uniform Resource Identifier)
● The Request method and Content
● The User-Agent header
● The Connection control header
● The Cache control header
The HTTP request method specifies how the resource defined by the Requested URI will be accessed (Uniform Resource Identifier). This approach is case-sensitive, and uppercase should be utilized.
Methods
The following are the HTTP request methods:
● GET - Requests the resource at the specified URL.
● POST - Requests that the server accept the supplied body information. It's similar to a GET request with additional information included.
● HEAD - Only the header portion of whatever a GET would return is requested. Like GET, but without the body.
● TRACE - For testing or debugging, this method requests the request message's loopback.
● PUT - It specifies that the enclosed data (the body) be inserted into the requested URL.
● DELETE - Declares that the resource at the requested URL should be deleted.
● OPTIONS - Requests a list of HTTP methods that the object at the request URL can respond to.
Get Vs Post
The Get and Post requests have a lot of differences. Let's have a look at the differences:
Get | Post |
Because data is sent in the header, only a limited amount of data can be transmitted in a Get request. | Because data is supplied in the body of a post request, a great quantity of data can be sent. |
Because data is exposed in the URL bar, the get request is not safe. | Data is not accessible in the URL bar, so the post request is secure. |
It's possible to save a request. | It is not possible to bookmark a post request. |
The GetRequest method is idempotent. It signifies that the second request will be ignored until the first request's response is received. | The post request is not irreversible. |
Get requests are more efficient and popular than Post requests. | Post request is less efficient and used less than get. |
Container
It gives JavaEE (j2ee) applications a runtime environment. Only static WebPages can be requested from the server by the client/user. In Java, the servlet container is used if the user wishes to consume web pages based on input.
The servlet container is a component of the web server that can be executed independently. There are three different types of servlet container states:
Servlet Container States
The servlet container is a component of the web server that can be executed independently. There are three different types of servlet container states:
● Standalone: This refers to Java-based servers in which the servlet container and web servers are both part of the same software. For instance, Tomcat running on its own.
● In-process: It is segregated from the web server because a different software operates as a plug-in within the main server's address space. For instance, Tomcat can operate inside JBoss.
● Out-of-process: The web server and servlet container are two separate programmes that operate in separate processes. The servlet container's plug-in is used by the web server to perform communications between them.
The Servlet Container can do the following operations:
● Life Cycle Management
● Multithreaded support
● Object Pooling
● Security etc.
Content types
MIME (Multipurpose Internet Mail Extension)Type is another name for Content Type. It's an HTTP header that gives the browser a description of what you're transmitting.
MIME is an internet standard that allows the inclusion of sounds, graphics, and text into email messages, extending the limiting capabilities of email.
The following are the features that MIME provides to email services:
● Non-ASCII characters are supported.
● Multiple attachments can be sent in a single message.
● It accepts attachments containing executable audio, picture, and video files, among other things.
● It allows you to send messages of any length.
List of Content Types
There are many different forms of content. The following are some of the most regularly utilized content types:
● text/html
● text/plain
● application/msword
● application/vnd.ms-excel
● application/jar
● application/pdf
● application/octet-stream
● application/x-zip
● images/jpeg
● images/png
● images/gif
● audio/mp3
● video/mp4
● video/quicktime etc.
There are five stages in the life cycle of a servlet:
1) Loading of Servlet
2) Creating instance of Servlet
3) Invoke init() once
4) Invoke service() repeatedly for each client request
5) Invoke destroy()
Fig 4: Servlet life cycle
Step 1: Loading of Servlet
The servlet container deploys and loads all the servlets when the web server (for example, Apache Tomcat) starts up.
Step 2: Creating instance of Servlet
The servlet container produces instances of each servlet class until all of the servlet classes have been loaded. The servlet container only generates one instance of each servlet class, and all servlet requests are handled by the same servlet instance.
Step 3: Invoke init() method
The init() method is called for each instantiated servlet until all of the servlet classes have been instantiated. The servlet is initialized with this form. In the deployment descriptor (web.xml) file, you can define those init parameters.
Syntax of init method
Public void init(ServletConfig config) throws ServletException
Step 4: Invoke service() method
When a servlet request is received, the web server creates a new thread that calls the service() function. If the servlet is GenericServlet, the request is handled directly by the service() process; if the servlet is HttpServlet, the request is received and dispatched to the appropriate handler method based on the request form.
Syntax
Public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
Step 5: Invoke destroy() method
When the servlet container shuts down (which normally occurs when the web server is stopped), it unloads all of the servlets and calls the destroy() method on each one that has been initialized.
Syntax
Public void destroy()
Key takeaway
There are five stages in the life cycle of a servlet.
Interfaces and classes for the servlet API are represented by the javax.servlet and javax.servlet.http packages.
The servlet or web container uses numerous interfaces and classes from the javax.servlet package. These aren't tied to any particular protocol.
Interfaces and classes in the javax.servlet.http package are only responsible for http requests.
Interfaces in javax.servlet package
The javax.servlet package has a large number of interfaces. The following are the details:
● Servlet
● ServletRequest
● ServletResponse
● RequestDispatcher
● ServletConfig
● ServletContext
● SingleThreadModel
● Filter
● FilterConfig
● FilterChain
● ServletRequestListener
● ServletRequestAttributeListener
● ServletContextListener
● ServletContextAttributeListener
Classes in javax.servlet package
The javax.servlet package contains a large number of classes. The following are the details:
● GenericServlet
● ServletInputStream
● ServletOutputStream
● ServletRequestWrapper
● ServletResponseWrapper
● ServletRequestEvent
● ServletContextEvent
● ServletRequestAttributeEvent
● ServletContextAttributeEvent
● ServletException
● UnavailableException
Interfaces in javax.servlet.http package
The javax.servlet.http package has a large number of interfaces. The following are the details:
● HttpServletRequest
● HttpServletResponse
● HttpSession
● HttpSessionListener
● HttpSessionAttributeListener
● HttpSessionBindingListener
● HttpSessionActivationListener
● HttpSessionContext
Classes in javax.servlet.http package
The javax.servlet.http package contains a large number of classes. The following are the details:
● HttpServlet
● Cookie
● HttpServletRequestWrapper
● HttpServletResponseWrapper
● HttpSessionEvent
● HttpSessionBindingEvent
● HttpUtils
Key takeaway
Interfaces and classes for the servlet API are represented by the javax.servlet and javax.servlet.http packages.
The Servlet interface unifies the behaviour of all servlets. The Servlet interface specifies the methods that must be implemented by all servlets.
For every servlet to be created, the Servlet interface must be implemented (either directly or indirectly). It has three life cycle methods for initializing the servlet, servicing requests, and destroying the servlet, as well as two non-life cycle methods.
Methods of Servlet interface
The Servlet interface has five methods. The life cycle methods of a servlet are init, serve, and destroy. The web container calls these functions.
● public void init(ServletConfig config) - the servlet's initialization It is a servlet's life cycle method that is only called once by the web container.
● public void service(ServletRequest request,ServletResponse response) - gives a response to an incoming request The web container calls it with each request.
● public void destroy() - is only called once and signifies that the servlet is about to be deleted.
● public ServletConfig getServletConfig() - ServletConfig's object is returned.
● public String getServletInfo() - provides details about the servlet, such as the author, copyright, and version.
Example
Let's look at a simple servlet example using the servlet interface.
Import java.io.*;
Import javax.servlet.*;
Public class First implements Servlet{
ServletConfig config=null;
Public void init(ServletConfig config){
This.config=config;
System.out.println("servlet is initialized");
}
Public void service(ServletRequest req,ServletResponse res)
Throws IOException,ServletException{
Res.setContentType("text/html");
PrintWriter out=res.getWriter();
Out.print("<html><body>");
Out.print("<b>hello simple servlet</b>");
Out.print("</body></html>");
}
Public void destroy(){System.out.println("servlet is destroyed");}
Public ServletConfig getServletConfig(){return config;}
Public String getServletInfo(){return "copyright 2007-1010";}
}
ServletConfig
For each servlet, the web container creates a ServletConfig object. The web.xml file can be used to retrieve configuration information using this object.
We don't need to replace the servlet if the configuration information in the web.xml file is changed. As a result, if any specific material is amended from time to time, it is easier to administer the web application.
Advantage of ServletConfig
The main benefit of ServletConfig is that if information in the web.xml file changes, you don't have to alter the servlet file.
Methods
● public String getInitParameter(String name): The parameter value for the supplied parameter name is returned.
● public Enumeration getInitParameterNames(): Returns a list of all the names of the initialization parameters.
● public String getServletName(): The name of the servlet is returned.
● public ServletContext getServletContext(): Returns a ServletContext object.
How to get the object of ServletConfig
The Servlet interface's getServletConfig() method returns a ServletConfig object.
Syntax of getServletConfig() method
Public ServletConfig getServletConfig();
Example of getServletConfig() method
ServletConfig config=getServletConfig();
Syntax to provide the initialization parameter for a servlet
The init-param sub-element of the servlet element is used to indicate a servlet's initialization argument.
<web-app>
<servlet>
......
<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>
Example of ServletConfig to get initialization parameter
We are receiving one initialization parameter from the web.xml file and printing it in the servlet in this example.
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class DemoServlet extends HttpServlet {
Public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
String driver=config.getInitParameter("driver");
out.print("Driver is: "+driver);
out.close();
}
}
Web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
ServletContext
When the project is deployed, the web container creates a ServletContext object. The web.xml file can be used to retrieve configuration information using this object. Each web application has just one ServletContext object.
If any information is shared across many servlets, the context-param> element in the web.xml file should be used.
Advantage of ServletContext
Simple to keep up with If any information is shared by all servlets, it is preferable to make it available to them all. We get this information from the web.xml file, so we don't have to replace the servlet if the data changes. As a result, the issue of maintenance is no longer an issue.
Usage of ServletContext Interface
The ServletContext object can be used in a variety of ways. The following are a few of them:
● The ServletContext object serves as a link between the container and the servlet.
● The web.xml file's configuration information can be retrieved via the ServletContext object.
● Set, get, and remove attributes from the web.xml file using the ServletContext object.
● The ServletContext object can be used to communicate across applications.
Methods
Some of the most regularly utilized ServletContext interface methods are listed below.
● public String getInitParameter(String name): The parameter value for the supplied parameter name is returned.
● public Enumeration getInitParameterNames(): The names of the context's initialization arguments are returned.
● public void setAttribute(String name,Object object): sets the application's scope to the provided object.
● public Object getAttribute(String name): The attribute for the supplied name is returned.
● public Enumeration getInitParameterNames(): As an Enumeration of String objects, returns the names of the context's initialization parameters.
● public void removeAttribute(String name): The attribute with the specified name is removed from the servlet context.
Syntax to provide the initialization parameter in Context scope
The initialization parameter in the application scope is defined using the context-param element, a subelement of web-app. The context-param has two sub-elements: param-name and param-value. The parameter name is defined by the param-name element, while the value is defined by the param-value element.
<web-app>
......
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
......
</web-app>
Example of ServletContext to get the initialization parameter
We are retrieving the initialization parameter from the web.xml file and printing the value of the initialization parameter in this example. The application scope is represented by the ServletContext object. So, if we modify the value of the parameter in the web.xml file, it will affect all servlet classes. As a result, we won't need to change the servlet. As a result, having the common information for the majority of the servlets in the web.xml file via the context-param element is preferable. Let's take a look at a simple example:
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class DemoServlet extends HttpServlet{
Public void doGet(HttpServletRequest req,HttpServletResponse res)
Throws ServletException,IOException
{
Res.setContentType("text/html");
PrintWriter pw=res.getWriter();
//creating ServletContext object
ServletContext context=getServletContext();
//Getting the value of the initialization parameter and printing it
String driverName=context.getInitParameter("dname");
Pw.println("driver name is="+driverName);
Pw.close();
}}
Web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
The Servlet, ServletConfig, and Serializable interfaces are all implemented by the GenericServlet class. With the exception of the service method, it implements all of these interfaces' methods.
Because the GenericServlet class may process any form of request, it is protocol agnostic.
By inheriting the GenericServlet class and giving the service method implementation, you can create a generic servlet.
Methods
The GenericServlet class has a lot of methods. The following are the details:
● public void init(ServletConfig config): The servlet is initialized with this method.
● public abstract void service(ServletRequest request, ServletResponse response): ensures that the incoming request is met. When a user requests a servlet, this method is called.
● public void destroy(): is only called once during the life cycle and signifies that the servlet is about to be destroyed.
● public ServletConfig getServletConfig(): returns the object of ServletConfig.
● public String getServletInfo(): provides details about the servlet, such as the author, copyright, and version.
● public void init(): It is a useful function for servlet programmers because it eliminates the requirement to call super.init (config).
● public ServletContext getServletContext(): ServletContext's object is returned.
● public String getInitParameter(String name): returns the value of the parameter with the supplied name.
● public Enumeration getInitParameterNames(): All of the parameters defined in the web.xml file are returned.
● public String getServletName(): The name of the servlet object is returned.
● public void log(String msg): The specified message is written to the servlet log file.
● public void log(String msg,Throwable t): The explanatory message is written to the servlet log file, along with a stack trace.
Example
Let's look at a simple servlet example using the GenericServlet class.
Import java.io.*;
Import javax.servlet.*;
Public class First extends GenericServlet{
Public void service(ServletRequest req,ServletResponse res)
Throws IOException,ServletException{
Res.setContentType("text/html");
PrintWriter out=res.getWriter();
Out.print("<html><body>");
Out.print("<b>hello generic servlet</b>");
Out.print("</body></html>");
}
}
HttpServletRequest
A Servlet's primary function is to handle client requests. To encapsulate client requests, the Servlet API provides two key interfaces: javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest. These APIs are used to give critical information about a client's request to a servlet.
Methods
● Object getAttribute(String name) - By name, the return attribute is placed on the request object.
● Enumeration getAttributeName() - return an Enumeration with the names of the characteristics that are available in this request.
● int getContentLength() - return the request body's size.
● int getContentType() - return the request content's media type.
● ServletInputStream getInputStream() - returns a binary data reading input stream.
● String getParameter(String name) - returns the name of the parameter's value.
● String getLocalAddr() - The return value is the Internet Protocol (IP) address of the interface that received the request.
● Enumeration getParameterNames() - An enumeration of all parameter names is returned.
● String[] getParameterValues(String name) - produces an array of String objects containing all of the values associated with the provided request parameter, or null if the parameter does not exist.
● ServletContext getServletContext() - return the current request's servlet context.
● String getServerName() - The hostname of the server to which the request was submitted is returned.
● int getServerPort() - The port number to which the request was sent is returned.
● boolean isSecure() - If this request was made over a secure channel, such as HTTPS, it returns a boolean value.
● void removeAttribute(String name) - This request's attribute is removed.
● void setAttribute(String name, Object o) - This request contains an attribute.
Example
We'll illustrate how a parameter is sent to a Servlet in a request object from an HTML website in this example.
Index.html
<form method="post" action="check">
Name <input type="text" name="user" >
<input type="submit" value="submit">
</form>
Web.xml
<servlet>
<servlet-name>check</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
MyServlet.java
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String user = request.getParameter("user");
out.println("<h2> Welcome "+user+"</h2>");
} finally {
out.close();
}
}
}
Output
HttpServletResponse
To assist in sending responses to clients, the Servlet API includes two crucial interfaces: ServletResponse and HttpServletResponse.
● PrintWriter getWriter() - The PrintWriter object is used to send character text to the client.
● void setBufferSize(int size) - Sets the response's desired buffer size for the body.
● void setContentLength(int len) - Sets the length of the response's content body. This function sets the HTTP Content-Length header in HTTP servlets.
● void setContentType(String type) - before sending the response to the client, sets the content type of the response.
● void setBufferSize(int size) - specifies the recommended buffer size for the response's body.
● boolean isCommitted() - If the response has been committed, this method returns a boolean.
● void setLocale(Locale loc) - If the response hasn't been committed yet, it sets the response's locale.
HttpServletResponse Interface
The HttpServletResponse interface includes methods for handling HTTP responses. The ServletResponse interface is extended. The HttpServletResponse object is created in the servlet container.
Example of HttpServletResponse interface on Eclipse
The directory structure of the application for constructing a HttpServletResponse interface is as follows:
The steps for constructing the programme are as follows.
Step 1: In Eclipse, go to File => New => Dynamic Web Project and create a dynamic project.
Step 2: Now you'll need to make an HTML file.
Right-click the project and select HTML file from the drop-down menu. After you've given the file a name, click the Finish button.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>studytonight.com</title>
</head>
<body>
<form align="center" action="display" method="get">
<h3>studytonight.com</h3>
<hr>
Enter User name: <input type="text" name="val1"><br><br>
Enter Password: <input type="password" name="val2" ><br><br>
<input type="submit" value="login">
</body>
</html>
Step 3: In the web.xml file, paste the following code.
A deployment descriptor is the web.xml file. All of the configurations may be found here.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>ServletResponse</display-name>
<servlet>
<servlet-name>abc3</servlet-name>
<servlet-class>demo4</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc3</servlet-name>
<url-pattern>/display</url-pattern>
</servlet-mapping>
</web-app>
Step 4: Create a servlet now. Make a class for this. Give the name of the package and the class.
Import javax.servlet.http.*;
Import javax.servlet.*;
Import java.io.*;
Public class demo4 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
String uname=req.getParameter("val1");
String pw=req.getParameter("val2");
pwriter.println("User Details Page:");
pwriter.println("Hello "+uname);
pwriter.println("Your Password is **"+pw+"**");
pwriter.close();
}
}
Classes (HttpServlet)
The Serializable interface is implemented by the HttpServlet class, which extends the GenericServlet class. It has http-specific methods like doGet, doPost, doHead, doTrace, and so on.
Methods of HttpServlet class
The HttpServlet class has a lot of methods. The following are the details:
● public void service(ServletRequest req,ServletResponse res) - By changing the request and response objects to http type, it sends the request to the protected service function.
● protected void service(HttpServletRequest req, HttpServletResponse res) - based on the incoming http request type, receives the request from the service method and sends it to the doXXX() function.
● protected void doGet(HttpServletRequest req, HttpServletResponse res) - takes care of the GET request. The web container is the one who calls it.
● protected void doPost(HttpServletRequest req, HttpServletResponse res) - takes care of the POST request. The web container is the one who calls it.
● protected void doHead(HttpServletRequest req, HttpServletResponse res) - takes care of the HEAD request. The web container is the one who calls it.
● protected void doOptions(HttpServletRequest req, HttpServletResponse res) - takes care of the OPTIONS request. The web container is the one who calls it.
● protected void doPut(HttpServletRequest req, HttpServletResponse res) - takes care of the PUT request. The web container is the one who calls it.
● protected void doTrace(HttpServletRequest req, HttpServletResponse res) - TRACE is a request that is handled by this programme. The web container is the one who calls it.
● protected void doDelete(HttpServletRequest req, HttpServletResponse res) - takes care of the DELETE request. The web container is the one who calls it.
● protected long getLastModified(HttpServletRequest req) - since midnight January 1, 1970 GMT, returns the time when HttpServletRequest was last changed.
● A session is essentially a time frame, and tracking refers to keeping user data for a set length of time.
● Web servers and the HTTP protocol are stateless.
● All requests and responses are distinct from one another.
● Each request to the web server is considered a separate request.
● Session tracking is a method used by the web container to keep track of a user's session information. It's used to identify a certain user.
Session Tracking
A Servlet can associate a request with a user using Session Tracking. A session can span several stateless HYPERLINK "http://www.novocode.com/doc/servlet-essentials/appendix.html#a d HTTP" HTTP requests and connections. There are two ways to keep sessions going:
1. By utilizing cookies. A cookie is a string that is delivered to a client to start a session (in this example, the session ID). If the client wants to keep the session going, it sends the Cookie back with each subsequent request. This is the most typical method for tracking sessions.
2. Using URL rewriting. All links and redirections made by a Servlet must be encoded in order to include the session ID. Because the session cannot be preserved by requesting a well-known URL or picking a URL that was formed in a different (or no) session, this is a less elegant option (both for Servlet implementors and users). It also prohibits the creation of static pages. All HTML pages delivered within a session must be dynamically generated.
Our next Servlet is in charge of maintaining a virtual shopping cart. HTML forms allow users to add numerous things to their shopping cart. The contents of each user's shopping cart are saved on the server, and each user has his own shopping cart, which is automatically picked every time he makes a request to the Servlet.
Technique of Session Tracking
Session Tracking employs four different techniques:
1) Cookies
2) Hidden Form Field
3) URL Rewriting
4) HttpSession
Cookies
Cookies are little pieces of data sent by the web server in the response header and kept by the browser. Each web client can be assigned a unique session ID by a web server. Cookies are used to keep the session going. Cookies can be turned off by the client.
Hidden From Field
The information is inserted into the web pages via the hidden form field, which is then transferred to the server. These fields are hidden from the user's view.
For example:
<input type = hidden' name = 'session' value = '12345' >
URL Rewriting
With each request and return, append some extra data via URL as request parameters. URL rewriting is a better technique to keep session management and browser work in sync.
HttpSession
A user session is represented by the HttpSession object. A session is established between an HTTP client and an HTTP server using the HttpSession interface. A user session is a collection of data about a user that spans many HTTP requests.
For example:
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");
Key takeaway
A session is essentially a time frame, and tracking refers to keeping user data for a set length of time.
Web servers and the HTTP protocol are stateless.
● Cookies are the mostly used technology for session tracking. A cookie is a small text file that contains small amount of information about a user visiting your site and is stored on the site visitor’s computer by their web browser.
● In Cookie, data comes in name value pair, sent by the server to the web browser.
● Browser saves it in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it.
● Then the server can identify the client using the cookie. A web server can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. By default, each request is considered as a new request.
● In cookies technique, you can add cookie with response from the servlet. So cookie is stored in the cache of the browser.
● After that if request is sent by the user, cookie is added with request by default. Thus, we identify the user as the old user. See the following fig. 5.4 which shows this scenario:
● Adds the specified cookie to the response.
Following steps are required for creating a new cookie:
- Create a new Cookie Object
● Cookie cookie = new Cookie (name, value);
2. Set any cookie attributes
● Cookie.SetMaxAge (40);
3. Add your cookie to the response object:
● response.addCookie (cookie)
Session tracking is easy to implement and maintain using the cookies. Cookies can be deleted or disabled by the client. In such case, the browser will not save the cookie at the client computer and Cookies are sent from the server to the client via “Set-Cookie” headers.
∕∕ CookieQ
Cookie cookie = new Cookie (String name, String value);
For example,
Cookie cookie = new Cookie("ID n , ”1234”);
Syntax:
Setcookie(name,value,expire,path,domain,secure)
Description of all parameters mentioned in setcookie() method is given in following table.
Parameter Description
Name Specifies the name of the cookie
Value Specifies the value of the cookie
Expire Specifies when the cookie expires.
If this parameter is not set, the cookie will expire at the end of the session. This field is optional.
PathSpecifies the server path of the cookie.
If set to the cookie will be available within the entire domain. The default value is the current directory that the cookie is being set in. This field is optional.
Domain Specifies the domain name of the cookie. This field
Is optional.
SecureSpecifies whether or not the cookie should only be
Transmitted over a secure HTTPS connection. TRUE value indicates that the cookie will only be set if a secure connection exists. Default is FALSE. This field is optional.
Cookie cookie = new
Cookie(“ID”, ”123”);
Response.addCookie(cookie);
Types of Cookies
We can categorize cookies depending on their expiration date:
● Session
● Persistent
1) Session Cookies:
Session cookies do not have an expiration date attached to them. It can be found in the browser's memory. This cookie is deleted as soon as the web browser is closed.
2) Persistent Cookies:
Unlike session cookies, they have an expiration date, are stored on the user's hard disc, and are deleted after the expiration date passes.
Advantage of Cookies
● Maintaining the state in the simplest way possible.
● Cookies are stored on the client's computer.
Disadvantage of Cookies
● If you disable cookies in your browser, it will not operate.
● Only textual data can be stored in the Cookie object.
Key takeaway
Cookies are the mostly used technology for session tracking. A cookie is a small text file that contains a small amount of information about a user visiting your site and is stored on the site visitor’s computer by their web browser.
References:
- Herbert Schildt, Java2: The Complete Reference, Tata McGraw-Hill
- Object Oriented Programming with JAVA Essentials and Applications , McGraw Hill
- Core and Advanced Java, Black Book- dreamtech
- Murach’s Java Servlets and JSP