Professional Documents
Culture Documents
Unit-II Servlets2
Unit-II Servlets2
1
A Servlet in Web Application
2
What can Servlets do?
• Read data sent by the user (e.g., form data)
• Look up other information about the request in the
HTTP request (e.g. authentication data, cookies,
etc.)
• Generate the result (may do this by talking to a
database, file system, etc.)
• Format the result as a document (e.g., convert it
into HTML format)
• Set the appropriate HTTP response parameters
(e.g. cookies, content-type, etc.)
3
• Send the resulting document to the user
Servlet Terminology
• HTTP
• Http Request Methods
• Difference between Get and Post
• Anatomy of Get Request
• Anatomy of Post Request
• Content Type
• Server (Web And Application)
• Container
• Servlet Interface
4
HTTP
• HTTP (Hyper Text Transfer Protocol)
• Http is the protocol that allows web servers and browsers to
exchange data over the web.
• It is a request response protocol.
• Http uses reliable TCP connections by default on TCP port
80.
• It is stateless means each request is considered as the new
request.
• Version : 1.0/1.1
5
HTTP
6
HTTP
• HTTP Request Methods:
GET
• Asks to get the resource at the requested URL.
POST
• Asks the server to accept the body info attached. It is like GET request
with extra info sent with the request.
7
HTTP GET request
8
HTTP POST request
9
HTTP
GET POST
5) Get request is more efficient and Post request is less efficient and
used more than Post used less than get.
10
HTTP Request Methods
11
HTTP Request Packets
17
Server
• Web Server
• Web server contains only web or servlet container. It can be used for
servlet, jsp, struts etc. It can't be used for EJB( development
architecture for building highly scalable and robust enterprise level
applications)
• Examples of Web Servers are: Apache Tomcat and Resin.
• Application Server
• Application server contains Web and EJB containers. It can be used for
servlet, jsp, struts, EJB etc.
• Example of Application Servers are:
• JBoss Open-source server from JBoss community.
• Glassfish provided by Sun Microsystem. Now acquired by Oracle.
• Weblogic provided by Oracle. It more secured.
• Websphere provided by IBM. 18
Container
• Servlet Container : A servlet container (also called a servlet
engine) is a separate module used by the web server to
load and run servlets.
19
Servlet Container Architecture
javax.servlet java.servlet.http
«interface» Servlet
«abstract» GenericServlet «abstract» HttpServlet
• Interface Servlet: The main interface that every servlet must implement.
It defines the key methods that a servlet container calls to control the
servlet.
• Abstract class GenericServlet :This abstract class can be used as the
starting point for implementing servlets. In particular, it implements all
the methods of the Servlet interface except the service() method. This
abstract class also implements the ServletConfig interface which allows
the servlet container to pass information to the servlet.
• interface ServletRequest :This interface provides the methods to extract
information from a client request
• interface ServletResponse :This interface provides the methods to
create and send an appropriate response to a client request.
23
javax.servlet package
24
javax.servlet.http package
25
javax.servlet.http package
26
javax.servlet.http package
30
Writing Hello World(2)
out.println("<html>");
out.println("<head><title>hello world</title></head>")
out.println("<body>");
out.println("<big>hello world</big>");
out.println("</body></html>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
}
}
31
Handling Form Data
<HTML>
<HEAD>
<TITLE> INTRODUCTION</TITLE>
<HEAD>
<BODY>
<FORM METHOD=GET ACTION=“/servlet/Hello”>
What is your name?
<INPUT TYPE=TEXT NAME=“name”<P>
<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
32
Writing Hello World(3)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
34
Servlet Life Cycle
35
Servlet Life Cycle
Generic Servlet & HTTP Servlet
GenericServlet
Client
request
Server service ( )
response
HTTPServlet
Browser
request doGet( )
HTTP service ( )
Server
response doPost( )
GenericServlet - Methods
41
Compile the Servlet
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testing</servlet-name>
<url-pattern>/servlet/TestingServlet</url-pattern>
</servlet-mapping>
</web-app>
Run the Servlet
47
(1) Request Line
• GET
http://localhost:8080/horoscope/SimpleHoroscope/index.html?parameter
=value&also=another HTTP/1.0
• Host: localhost:8080
• Context path:/horoscope
• Servlet path:/SimpleHoroscope
• Requsted URI:/horoscope/SimpleHoroscope
• Query: parameter=value&also=another
• Requested URL : http://localhost:8080/horoscope/SimpleHoroscope
• Extra path information: index.html
48
(2)Client HTTP Request Headers
Header Description
Accept This header specifies the MIME types that the browser or
other clients can handle. Values
of image/png or image/jpeg are the two most common
possibilities.
Accept-Charset This header specifies the character sets the browser can use
to display the information. For example ISO-8859-1.
Accept-Encoding This header specifies the types of encodings that the browser
knows how to handle. Values of gzip or compress are the
two most common possibilities.
Connection This header indicates whether the client can handle persistent
HTTP connections. Persistent connections permit the client or
other browser to retrieve multiple files with a single request. A
value of Keep-Alivemeans that persistent connections should
be used
Content-Length This header is applicable only to POST requests and gives
the size of the POST data in bytes.
Cookie This header returns cookies to servers that previously sent
them to the browser.
Host This header specifies the host and port as given in the original
URL
50
(2)Client HTTP Request
Headers
Header Description
If-Modified-Since This header indicates that the client wants the page only if it
has been changed after the specified date. The server sends
a code, 304 which means Not Modified header if no newer
result is available.
Referer This header indicates the URL of the referring Web page. For
• . example, if you are at Web page 1 and click on a link to Web
page 2, the URL of Web page 1 is included in the Referer
header when the browser requests Web page 2.
•User-Agent This header identifies the browser or other client making the
request and can be used to return different content to different
51
types of browsers.
Methods to read HTTP Request Line and
Request Headers
Enumeration getParameterNames()
an Enumeration of String objects, each String
containing the name of a request parameter; or an
empty Enumeration if the request has no
parameters
java.lang.String[] getParameterValues (java.lang.String name)
Returns an array of String objects containing all of
the values the given request parameter has, or
null if the parameter does not exist.
java.lang.String getParameter (java.lang.String name)
Returns the value of a request parameter as a
String, or null if the parameter does not exist.
Methods to read HTTP Request Line and
Request Headers
Cookie[] getCookies()
Returns an array containing all of the Cookie objects
the client sent with this request.
java.lang.String getMethod()
Returns the name of the HTTP method with which\thi
request was made, for example, GET, POST, or PUT.
java.lang.String getQueryString()
Returns the query string that is contained in the
request URL after the path.
HttpSession getSession()
Returns the current session associated with this
request, or if the request does not have a session,
creates one.
Methods to read HTTP Request Line and
Request Headers
• Advantage of ServletConfig
• The core advantage of ServletConfig is that you don't need to edit the
servlet file if information is modified from the web.xml file.
56
Retrieving Information about servlet
init parameters
• Methods of ServletConfig interface
• public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.
• public Enumeration getInitParameterNames():Returns an
enumeration of all the initialization parameter names.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
thows 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();
}
}
58
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> 59
Retrieving Information about
context init parameters
• ServletContext Interface
• An object of ServletContext is created by the web container at time of
deploying the project. This object can be used to get configuration
information from web.xml file. There is only one ServletContext object
per web application.
• If any information is shared to many servlet, it is better to provide it from
the web.xml file using the<context-param> element.
• Advantage of ServletContext
• Easy to maintain if any information is shared to all the servlet, it is
better to make it available for all the servlet. We provide this information
from the web.xml file, so if the information is changed, we don't need to
modify the servlet. Thus it removes maintenance problem.
60
Retrieving Information about
context init parameters
• Usage of ServletContext Interface
61
Retrieving Information about
context init parameters
• Commonly used methods of ServletContext interface
• public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.
• public Enumeration getInitParameterNames():Returns the names of the
context's initialization parameters.
63
Retrieving Information about
context init parameters
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(); }}
64
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>
65
Retrieving Information About the Server
String getServerName()
Returns the host name of the server that received the
request
int getServerPort()
Returns the port number on which this request was
received.
String ServletContext.getServerInfo()
Returns information about the server software and its
attributes
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the
client or last proxy that sent the request.
String getRemoteHost()
Returns the fully qualified name of the client or
the last proxy that sent the request.
int getRemotePort()
Returns the Internet Protocol (IP) source port of the
client or last proxy that sent the request.
String getRemoteUser()
Returns the login of the user making this request, if
the user has been authenticated, or null if the user
has not been authenticated.
java.lang.String getPathInfo()
Returns any extra path information associated with the
URL the client sent when it made this request.
java.lang.String getPathTranslated()
Returns any extra path information after the servlet
name but before the query string, and translates it to a
real path.
out.println("getServletContext().getServerInfo(): " +
getServletContext().getServerInfo());
Retrieving Information
//Retrieving Information about the Client Machine
out.println("req.getRemoteAddr(): " + req. getRemoteAddr());
out.println(“req.getRemoteHost(): " + req. getRemoteHost());
Enumeration getParameterNames()
Returns an Enumeration of String objects
containing the names of the parameters contained
in this request.
String[] getParameterValues(name)
Returns an array of string objects containing all of
the values the given request parameter has,
or null if the parameter does not exist
Retrieving Information Request Parameters
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ParameterSnoop extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("Query String:");
out.println(req.getQueryString());
out.println();
out.println("Request Parameters:");
}
Retrieving Information Request
Parameters
Enumeration enum = req.getParameterNames();
while (enum.hasMoreElements()) {
String name = (String) enum.nextElement();
String values[] = req.getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
out.println(name + " (" + i + "): " + values[i]);
}
}
}
}