Unit 4
Unit 4
Web Application
Some of the web applications are entirely static due to which they not required any
processing on the server at all while, on the other hand, some web applications are
dynamic and require server-side processing.
To operate a web-application, we usually required a web server (or we can
say some space on the web-server for our programs/application's code) to manage
the clients' upcoming requests and required an application server.
The application server performs the task that requested by the clients, which
also may need a database to store the information sometimes.
Application server technologies range from ASP.NET, ASP, and ColdFusion to
PHP and JSP.
Web Server
A web server is software and hardware that uses HTTP (Hypertext Transfer
Protocol) and other protocols to respond to client requests made over the World
Wide Web.
The main job of a web server is to display website content through storing,
processing and delivering webpages to users.
Application Server
An application server enables a server to generate a dynamic, customized response
to a client request.
The application server collaborates with the web server to return a dynamic,
customized response to a client request.
MVC Architecture
• MVC separates the business logic and presentation layer from each other. It
was traditionally used for desktop graphical user interfaces (GUIs).
• Nowadays, MVC architecture in web technology has become popular for
designing web applications as well as mobile apps.
• The MVC is an architectural pattern that separates an application into
1) Model, 2) View and 3) Controller
– Model: It includes all the data and its related logic
– View: Present data to the user or handles user interaction
– Controller: An interface between Model and View components
– MVC architecture was first discussed in 1979 by T Reenskaug
• Some popular MVC frameworks are Rails, Zend Framework,
CodeIgniter, Laravel, Fuel PHP, etc.
Examples of MVC architecture in Real world :
Describing Servlets
• Servlets are not tied to a specific client-server protocol, but are most
commonly used with HTTP.
• Execution of servlet consists of 4 steps:
– The client sends request to server
– The server alerts appropriate servlet
– The servlet process the request and generates the output(if any), and
sends back to the Webserver
– The Webserver sends back response to the client
• Applets are downloaded from the server and executes in clients browser
– Uses JRE
– Problems with browsers (not compatible)
• Servlets run on the server machine and usually generates HTML code.
– So, even older version of browser can easily display
CGI :
Why Servlet?
Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically. Java
Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI).
Servlets can handle the cookies. CGI cannot handle the cookies.
Servlet Alternatives :
• CGI
• Proprietary API’s
– NETSCAPE NSAPI’s
– Microsoft ISAPI’s
– Orelly’s WSAPI’s
• These are not free, community is less, memory leak
• ASP
• Server Side JS
Advantages of Servlets :
Applications of Servlet :
Read the explicit data sent by the clients (browsers). This includes an HTML
form on a Web page or it could also come from an applet or a custom HTTP
client program.
Read the implicit HTTP request data sent by the clients (browsers). This
includes cookies, media types and compression schemes the browser
understands, and so forth.
Process the data and generate the results. This process may require talking to
a database, executing an RMI or CORBA call, invoking a Web service, or
computing the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or
XML), binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes
telling the browsers or other clients what type of document is being returned
(e.g., HTML), setting cookies and caching parameters, and other such tasks.
ServletInputStream i=req.getInputStream();
ServletOutputStream i=req.getOutputStream();
<web-app>
<init-param>
<param-name>Country</param-name>
<param-value>India</param-value>
</init-param>
<init-param>
<param-name>Age</param-name> <param-value>24</param-
value>
</init-param> </web-app>
getServletConfig().getInitParameter("Country");
getServletConfig().getInitParameter("Age");
• Usage Modes
– Servlets can be used in various modes:
• Servlets can be chained together into filter chains (recording all
incoming requests, logs the IP addresses of the computers from
which the requests originate, conversion, data compression,
encryption and decryption, input validation etc.) by the servers.
• Servlets can support protocols such as HTTP.
• Servlets are replacement of CGI.
• Servlets are used to generate dynamic HTML content
• Performance Features
– In CGI, for every request one process will be created
– But in Servlets, one thread will be created
– In Fast- CGI, child process wont be terminated after request
completion but wait for another incoming connection.
• 3-tier Applications
– Using Java Servlet we can opt for 3- tier architecture.
• The first tier – Web browser
• Second tier – Servlets – For Business logic
• Third – Database connectivity
javax.servlet package
Interfaces Classes
Classes available in javax.servlet package:
ServletConfig:
Example code:
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.javapapers.ServletConfigTest</servlet-class>
<init-param>
<param-name>sum</param-name>
<param-value>14 </param-value>
</init-param>
</servlet>
ServletContext:
The ServletContext object is contained within the ServletConfig object. That is, the
ServletContext can be accessed using the ServletConfig object within a servlet.
You can specify param-value pairs for ServletContext object in <context-param>
tags in web.xml file.
Example code:
<web-app>
<context-param>
<param-name>globalVariable</param-name>
<param-value>gv </param-value>
</context-param>
<web-app>
<web-app>
<servlet>
<servlet-name>redteam</servlet-name>
<servlet-class>mysite.server.TeamServlet</servlet-class>
<init-param>
<param-name>teamColor</param-name>
<param-value>red</param-value>
</init-param>
<init-param>
<param-name>bgColor</param-name>
<param-value>#CC0000</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>blueteam</servlet-name>
<servlet-class>mysite.server.TeamServlet</servlet-class>
<init-param>
<param-name>teamColor</param-name>
<param-value>blue</param-value>
</init-param>
<init-param>
<param-name>bgColor</param-name>
<param-value>#0000CC</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>redteam</servlet-name>
<url-pattern>/red/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>blueteam</servlet-name>
<url-pattern>/blue/*</url-pattern>
</servlet-mapping>
</web-app>
ServletConfig
Deployment Descriptor :
web. xml file is also called Deployment descriptor defines mappings
between URL paths and the servlets that handle requests with those paths. The web
server uses this configuration to identify the servlet to handle a given request and
call the class method that corresponds to the request method.
Servlet Mapping (Example web.xml)
<servlet>
<servlet-name>watermelon</servlet-name>
<servlet-class>myservlets.watermelon</servlet-class>
</servlet>
<servlet>
<servlet-name>garden</servlet-name>
<servlet-class>myservlets.garden</servlet-class>
</servlet>
<servlet>
<servlet-name>list</servlet-name>
<servlet-class>myservlets.list</servlet-class>
</servlet>
<servlet>
<servlet-name>kiwi</servlet-name>
<servlet-class>myservlets.kiwi</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>watermelon</servlet-name>
<url-pattern>/fruit/summer/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>garden</servlet-name>
<url-pattern>/seeds/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>kiwi</servlet-name>
<url-pattern>*.abc</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>list</servlet-name>
<url-pattern>/seedlist</url-pattern>
</servlet-mapping>
URL Servlet
Invoked
http://host:port/mywebapp/fruit/summer/index.html watermelon
http://host:port/mywebapp/fruit/summer/index.abc watermelon
http://host:port/mywebapp/seedlist list
http://host:port/mywebapp/seeds garden
http://host:port/mywebapp/seeds/index.html garden
http://host:port/mywebapp/index.abc kiwi
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloWorldServlet extends HttpServlet
{
public void service(HttpServletRequest req,
HttpServletResponse res)
throws IOException
{
// Must set the content type first
res.setContentType("text/html");
// Now obtain a PrintWriter to insert HTML into
PrintWriter out = res.getWriter();
out.println("<html><head><title>" +
"Hello World!</title></head>");
out.println("<body><h1>Hello World!</h1></body></html>");
}
}
Methods in ServletConfig Interface
As you see in the above figure, response of second servlet is sent to the client.
Response of the first servlet is not displayed to the user
Use of include() :
As you can see in the above figure, response of second servlet is included in the
response of the first servlet that is being sent to the client.
Methods in GenericServlet
javax.servlet.http :
Methods in HttpServlet
• GET
• POST – Create or adds the resource at server side
• HEAD – Server Sends only header, without Response body
• PUT – Update/replace the resource at Server Side
• DELETE
• TRACE – To trace the route/debugging
• OPTIONS – for Communication Purpose – What are the options available
such as GET,POST,HEAD, PUT, DELETE…..
GET POST
Data is visible to everyone in the URL Data is not displayed in the URL. Data is set
as part of message header.
GET is less secure compared to POST POST is a little safer than GET because
because data is appended as part of the added with header part.
URL
Methods in HttpServletResponse
Methods in HttpServletRequest
o String getContextPath()
o String getHeader(String name)
o Enumeration getHeaderNames()
o String getMethod()
o String getQueryString()
o String getRemoteUser()
o String getRequestURI()
o StringBuffer getRequestURL()
o String getServletPath()
o Cookie[] getCookies()
o HttpSession getSession()
o HttpSession getSession(boolean create)
o String getRequestedSessionId()
o boolean isRequestedSessionIdFromCookie()
o boolean isRequestedSessionIdFromUrl()
o boolean isRequestedSessionIdFromURL()
o boolean isRequestedSessionIdValid()
HttpServletRequest Interface
ServletException, IOException
Other Methods:
– ServletConfig getServletConfig();
– String getServletInfo();
Returns a string object containing info about servlet such as version, author and
so on.
Simple Example
Headers :
» getInputStream()
» getReader()
HTTPServletResponse Interface:
Response Header
Response Redirection
Ex: response.sendRedirect(“www.pvpsit.ac.in");
It sends the same request and response It always sends a new request.
objects to another servlet.
It can work within the server only. It can be used within and outside the
server.
Example: Example:
request.getRequestDispacher("servlet2") response.sendRedirect("servlet2")
.forward(request,response);
Auto-Refresh/Wait Pages :
• The other useful response header is to send a wait page or a page that
• automatically refreshes to a new page after a specified amount of time is
elapsed.
– Wait:
• response.setHeader(“Refresh”,10);
– 10 – value(10) in seconds
– Refresh
• response.setHeader(“refresh”, “10;URL=“pvpsit.ac.in”);
Session Tracking :
Constructor Description
Cookie() constructs a cookie.
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the
cookie in seconds.
public String getName() Returns the name of the cookie.
public String getValue() Returns the value of the cookie.
URL Rewriting
• In URL rewriting, we append a token or identifier to
the URL of the next Servlet or the next resource.
• Token or identifier - Parameter name/value pairs using
the following format:
url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign,
a parameter name/value pair is separated from
another parameter using the ampersand(&).
• When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server.
• From a Servlet, we can use getParameter() method to
obtain a parameter value.
• Advantage of URL Rewriting
– It will always work whether cookie is disabled or not (browser
independent).
– Extra form submission is not required on each pages.
• Disadvantage of URL Rewriting
– It will work only with links.
– It can send Only textual information.
HTTP Session Interface
• Web container creates a session id for each user.
• The container uses this id to identify the particular user.
• An object of HttpSession can be used to perform two tasks:
– bind objects
• setAttribute(name,value)
– view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
How to get the HttpSession object ?:
of HttpSession:
ServletConfig:
Example code:
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.javapapers.ServletConfigTest</servlet-class>
<init-param>
<param-name>sum</param-name>
<param-value>14 </param-value>
</init-param>
</servlet>
ServletContext:
The ServletContext object is contained within the ServletConfig object. That is, the
ServletContext can be accessed using the ServletConfig object within a servlet.
You can specify param-value pairs for ServletContext object in <context-param>
tags in web.xml file.
Example code:
<web-app>
<context-param>
<param-name>globalVariable</param-name>
<param-value>gv </param-value>
</context-param>
<web-app>
ServletConfig
<servlet>
<servlet-name>watermelon</servlet-name>
<servlet-class>myservlets.watermelon</servlet-class>
</servlet>
<servlet>
<servlet-name>garden</servlet-name>
<servlet-class>myservlets.garden</servlet-class>
</servlet>
<servlet>
<servlet-name>list</servlet-name>
<servlet-class>myservlets.list</servlet-class>
</servlet>
<servlet>
<servlet-name>kiwi</servlet-name>
<servlet-class>myservlets.kiwi</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>watermelon</servlet-name>
<url-pattern>/fruit/summer/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>garden</servlet-name>
<url-pattern>/seeds/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>list</servlet-name>
<url-pattern>/seedlist</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>kiwi</servlet-name>
<url-pattern>*.abc</url-pattern>
</servlet-mapping>
URL Servlet
Invoked
http://host:port/mywebapp/fruit/summer/index.html watermelon
http://host:port/mywebapp/fruit/summer/index.abc watermelon
http://host:port/mywebapp/seedlist list
http://host:port/mywebapp/seedlist/pear.abc kiwi
http://host:port/mywebapp/seeds garden
http://host:port/mywebapp/seeds/index.html garden
http://host:port/mywebapp/index.abc kiwi
<web-app>
<servlet>
<servlet-name>redteam</servlet-name>
<servlet-class>mysite.server.TeamServlet</servlet-class>
<init-param>
<param-name>teamColor</param-name>
<param-value>red</param-value>
</init-param>
<init-param>
<param-name>bgColor</param-name>
<param-value>#CC0000</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>blueteam</servlet-name>
<servlet-class>mysite.server.TeamServlet</servlet-class>
<init-param>
<param-name>teamColor</param-name>
<param-value>blue</param-value>
</init-param>
<init-param>
<param-name>bgColor</param-name>
<param-value>#0000CC</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>redteam</servlet-name>
<url-pattern>/red/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>blueteam</servlet-name>
<url-pattern>/blue/*</url-pattern>
</servlet-mapping>
</web-app>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloWorldServlet extends HttpServlet
{
public void service(HttpServletRequest req,
HttpServletResponse res)
throws IOException
{
// Must set the content type first
res.setContentType("text/html");
// Now obtain a PrintWriter to insert HTML into
PrintWriter out = res.getWriter();
out.println("<html><head><title>" +
"Hello World!</title></head>");
out.println("<body><h1>Hello World!</h1></body></html>");
}
}
Before beginning to work with the Servlets, it is useful to examine the runtime
organizations of Web applications. Before the Servlet API Specification and
version 2.2, across the servers, there was little consistency in the WAR file
structure. However, Web servers that conform to the Servlet API version 2.2 [or
later] the Web application ARchive must be in a standard format before it is
accepted. These are discussed below.
Web Resources
In the Java EE architecture, Web components and static Web content files such as
images are called Web resources. A web module is the smallest deployable and
usable unit of Web resources. A Java EE Web module corresponds to the Web
application as defined in the Java Servlet specification, And The top-level
directory of A Web application hierarchy is also a document root of the
application. Here, all the HTML files and JSP pages can be placed that comprise
the application’s user interface.
Deployment Descriptor
Servlet API version 3.0 onwards, the deployment descriptor of [web.xml] takes
precedence over the annotations. This deployment descriptor overrides
configuration information specified through the annotation mechanism. Version
3.0 of the web deployment descriptor contains a new attribute called metadata
complete on the <web-app> element, which defines whether the web descriptor is
complete or whether the class files of the web application should be examined for
its annotations that specify the deployment information, and if this attribute is set
to true, the deployment tool must be ignoring any servlet annotations are present
in the class files and it is used only the configuration details mentioned in the
descriptor. Otherwise, if the value is not specified or set to be false, the container
must scan all classes files of the application for annotations. This will provide a
way to enable or disable the scanning of the annotation and its processing during
the startup of the application.
Context Path
When the application is being deployed on the particular Web server, Then a
context path to the application has been assigned within it. Thus it means if the
application is assigned to the context path as a bookshop, then a request of URI
referring to /bookshop/index.html will retrieve the index.html file from that
document root.
Servletconfigure
Se
• A servlet is a Java program that runs in a Web server, as opposed to an
applet that runs in a client browser. Typically, the servlet takes an HTTP
request from a browser, generates dynamic content (such as by querying a
database), and provides an HTTP response back to the browser.