Professional Documents
Culture Documents
Communication
Contents
1 Problem?
2 Variable declarations and initializations
3 Initialization
4 ServletConfig
5 init param for a particular servlet
6 ServletContext
7 Methods of ServletContext
8 Setting values for context variable : variable global to all the web components
9 Servlet-Browser Communication
10 Status 2xx
Contents
11 Status 4xx
12 Status 5xx
13 Status 3xx
14 Redirect through Servlet to Servlet Communication
15 Ways
16 forward
17 include
18 javax.servlet.RequestDispatcher
19 Request Attributes
20 web.xml
Contents
21 Register Servlet
22 Success Servlet
23 Error Servlet
24 Connecting to a database
25 JDBC 2.0 optional package
26 DataSource
27 JNDI and DataSources
28 Steps to get Connection object from DataSource
29 Advantages
30 J2EE Application Server’s support for DataSource
contents
31 Connection Pooling
32 J2EE Application Servers support for Connection Pooling
33 Distributed Transactions
Know
• How initialization is done
• How servlet-browser and servlet-servlet
communciation work
• How to connect to databases
Be Able To
• Write servlets that interact with databases
Problem?
//assume imports
public class Getdate extends HttpServlet{
java.util.Date d=new java.util.Date();
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException,
ServletException{
java.io.PrintWriter out=res.getWriter();
out.println("<html><body>Right now the date
and time of the server is "+ d);
out.println("</body></html>");}}
We have talked
about this
before… for sure!!
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)
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.
ServletConfig
• Getting ServletConfig object:
ServletConfig getServletConfig() method in
Servlet interface
<context-param>
<param-name>color</param-name>
<param-value>red</param-value>
</context-param>
</web-app>
init
public class Colors extends
javax.servlet.http.HttpServlet{
public void
doGet(javax.servlet.http.HttpServletRequest req,
javax.servlet.http.HttpServletResponse res)
throws java.io.IOException,
javax.servlet.ServletException{
java.io.PrintWriter out=res.getWriter();
out.println("<html>");
String title=getInitParameter("title");
String
color=getServletContext().getInitParameter("color")
;
out.println("<body bgcolor='"+color+"'>");
out.println("<h1>"+title+"</h1>");
out.println("</body></html>");
}}
Servlet-Browser Communication
Status 2xx
PondServer
Redirect through Servlet to
Servlet Communication
Ways
• 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
forward request
response
GET Request for servlet S1
S1
forward
S2
S2
Calls doGet() method of S2.
If the request was for POST, then
doPost() of S2 gets called.
<servlet>
<servlet-name>Success</servlet-name>
<servlet-class>Success</servlet-class>
</servlet>
<servlet>
<servlet-name>Failure</servlet-name>
<servlet-class>Error</servlet-class>
</servlet>
<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>
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");
request.getRequestDispatcher("error.do").inc
lude(request,response);
request.getRequestDispatcher("index.html").i
nclude(request,response);
}
}}
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>");
out.println("<head><body>");
out.println("Thanks <I>
"+request.getParameter("name")+"</I>" );
out.println("</body></html>");
}catch(Exception e){
out.println(e.toString()); }}
}
Error Servlet
public class Error 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>login
</title>");
out.println("<head><body><font
color=red><b>");
String
err=(String)request.getAttribute("error");
String
login=request.getParameter("login");
if(err!=null)
out.println(err);
out.println("</font><b><br></body></html>");
}catch(Exception
e){out.println(e.toString());
}
}
}
Connecting to a database
• We can connect to database from our servlet in
two ways:
JDBC 2.0 core package
(same as JDBC 1.0)
a. using traditional methods
b. using DataSources
Better way!
Connection con =
DriverManager.getConnection(url,"SYSTEM","
admin");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT
name, id FROM student");
JDBC 2.0 optional package
• javax.sql package
• Includes the following:
DataSource interface
Connection Pooling
Distributed Transactions
RowSet
Coming up !
J2EE Application Server’s support
for DataSource
• J2EE Application Server comes with some JNDI
naming and directory services (LDAP Server
etc.).
• Most Application Servers provide a tool that
allows application developers or administrators
to configure DataSources to this JNDI service.
• Advantage with this is that the application
developer can defer the decision of which
database to use until the deployment time!
Connection Pooling
• Connection Pooling is a mechanism whereby a
collection of connection objects is maintained
by the application
• Each time application requires a Connection
object, it gets it from the pool.
• In other words, when an application closes a
connection, that connection is recycled rather
than being destroyed
– improves performance
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.
J2EE Application Servers support
for Connection Pooling
• The size of the connection pool depends on the
application server.
• Application servers also provide a tool where
this size can be configured.
How does Connection pooling
improve performance?
Establishing connection is an
expensive operation. If connection
to a data source is required
throughout the application, it is
wise to retain and reuse the same
connection object. In a web
application (where many clients
request at the same time) it makes
sense to create a pool of
connection objects and reuse
these!
Distributed Transactions
• From an application developer’s point of view
there is no difference between Connection
obtained by the DataSource object and the
DriverManager except in case of transactions.
• With Connection object obtained from
DataSource, distributed transaction is
automatically supported.
• Therefore the application using Connection
object obtained from DataSource cannot call
commit or rollback methods directly.
Example using DataSource to
connect to Oracle