You are on page 1of 26

Initialization And

Communication
Initialization and Communication

Presenter: Deepika Nair

1
Initialization

• Servlet instance variables are initialized in init().


• The ServetConfig object is a configuration
object used by a servlet container to pass
information to a servlet during initialization. Most of
the time this information will be required to initialize
variables.
• There are two ways to initialize:
Override init(ServletConfig config)
Override init()and get config object
using getServletConfig() method(of
Servlet interface)

8
ServletConfig

• This object is used to fetch the initialization


parameters for individual servlets.
• This object is passed on by the application server to
the servlet during initialization when
init(ServletConfig) method is called.

9
ServletConfig

• Getting ServletConfig object:


ServletConfig getServletConfig() method in
Servlet interface

• Methods to get init parameters:


public String getInitParameter(String name)
of ServletConfig

10
init param for a particular servlet
<servlet>
<servlet-name>servlet-name</servlet-name>
<init-param>
<param-name>param-name</param-name>
<param-value>param-value</param-value>
</init-param>

</servlet>

In servlet servlet-name :
String var-name=getInitParameter(“param-name”);
11
ServletContext

• This object is global to all servlets and jsps in an


application context.
• It is used to set and get variables that are global
application variables.
• It is also used by the servlet to get info about the
servlet engine this servlet is running and info about
other servlets.

13
ServletContext

Getting ServletContext
• ServletContext getServletContext()
method of HttpServlet
or
• Initialize an instance of cxt by overriding
init(ServletContext) method.

14
Methods of ServletContext

• String getInitParameter(String name)


• void setAttribute(String name,Object
obj)
• Object getAttribute(String name)
• void removeAttribute(String name)

15
Status 2xx

GET Request for servlet s1


s1
Response packet
HTTP/1.1 200 OK
header

Client Server
<html>
…</html body HTTP status code 2xx
indicating the requested
resource is available.

19
Status 4xx

GET Request for servlet s2


s1
Response packet
HTTP/1.1 404 NOT FOUND
header

Client Server
body
HTTP status code 4xx
indicating the requested
resource is not available.

20
doPost(
Status 5xx ) not
defined!

POST Request for servlet s1


s1
Response packet
HTTP/1.1 500 Internal Server Error

Client Server

HTTP status code 5xx


server error. In this case
the request is made for
the method not defined
in the servlet.

21
Status 3xx

• HttpServletResponse has method called


sendRedirect(String url)
• This method sends a temporary redirect
response to client with status code 3xx. Location
specifies the URL page to which the redirection
is going to be.
• Usage:
response.sendRedirect(“http://localh
ost:8080/direct/s?name=‘Harry
Potter’”)

22
public class S1{

HTTP status code 3xx response.sendRedirect
indicating the redirect (“http://pondser/app2);

}

Request for servlet S1


S1
Response packet
HTTP/1.1 307 Temporary Redirect

Client Server

Request for http://pondser/app2

PondServer

23
Inter Servlet Communication

• Two servlets (or JSPs) can communicate with


each other.
• There are two ways in which the communicate
can happen based on where the control is finally
going to be:
– forward
– include

24
forward

request
response
GET Request for servlet S1
S1
forward

S2

Calls doGet() method of S2.


If the request was for POST, then
doPost() of S2 gets called.

Control finally is in S2. Response is generated by S2


25
include
request
response
GET Request for servlet S1
S1
include

S2
Calls doGet() method of S2.
If the request was for POST, then
doPost() of S2 gets called.

Control finally is in S1. Response is generated by S1

26
javax.servlet.RequestDispatcher
• RequestDispatcher is an interface that has methods to
forward or include.
• void forward(ServletRequest request,
ServletResponse response)
• void include(ServletRequest request,
ServletResponse response.
• RequestDispatcher instance is obtained through
– ServletContext or ServletRequest method-
RequestDispatcher getRequestDispatcher(String
path)
or w.r.t. to <url-pattern>
– ServletContext method
RequestDispatcher
getNamedDispatcher(String name)

w.r.t. to <servlet-name>
27
Request Attributes

• Request and Response objects are shared between


the servlets when they communicate. Needless to
say that form parameters etc. will be accessible by
both the servlets.
• In addition to this, request object can be used to
send additional data to the a servlet or a JSP while
forwarding (or including).
• HttpSessionRequest methods that allow this:
– Object getAttribute(String name)
– void setAttribute(String name ,
Object obj)
– void removeAttribute(String name)
29
Example

<html><head><title>Register</title></head>
<body>
<h2>Register</h2>
<table border=1><tr><td>
<form method=post action="register">
Name:<input type=text name=name>
Email:<input type=text name=email>
<input type=submit></form>
</body>
</html> On submitting this form, a servlet is invoked that checks for
the validity of data. If the data is invalid, the same form is
displayed with an error message, otherwise another servlet
is invoked that displays a friendly message.

30
web.xml
<web-app>
<display-name>Register</display-name>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>

<servlet>
<servlet-name>Success</servlet-name>
<servlet-class>Success</servlet-class>
</servlet>

<servlet>
<servlet-name>Failure</servlet-name>
<servlet-class>Error</servlet-class>
</servlet>

31
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/register.do</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>Success</servlet-name>
<url-pattern>/success.do</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>Failure</servlet-name>
<url-pattern>/error.do</url-pattern>
</servlet-mapping>

</web-app>

32
Register Servlet
// assume imports
public class Register extends HttpServlet {
public void doPost(HttpServletRequest
request,HttpServletResponse response) throws
IOException, ServletException {
PrintWriter out = response.getWriter();

String name=request.getParameter("name");
String email=request.getParameter("email");

if( (name!=null && name.trim().length()!=0) && (email!=null &&


email.trim().length()!=0))
request.getRequestDispatcher("success.do").forward(request,res
ponse);

33
else{
request.setAttribute("error","Name or
email not entered");
request.getRequestDispatcher("error.do"
).include(request,response);
request.getRequestDispatcher("index.htm
l").include(request,response);
}

}}

34
Success Servlet
//assume imports
public class Success extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException {
PrintWriter out = response.getWriter();
try{
response.setContentType("text/html");
out.println("<html><head><title>Success
</title>");
35
out.println("<head><body>");
out.println("Thanks <I>
"+request.getParameter("name")+"</I>" );

out.println("<BR>For further details we will


contact in the email-id
<B>"+request.getParameter("email")+"</B>");

out.println("</body></html>");
}catch(Exception e){out.println(e.toString());
}}
}

36
J2EE Application Servers support for
Connection Pooling

• Most application servers implement DataSource


interface that supports connection pooling.
• Therefore when you get connection form Data
Source instance, you get it from the pool and
when you close it, the connection goes back to
the pool.

48

You might also like