Lecture 3.2
Lecture 3.2
DEPARTMENT : CSE
Bachelor of Engineering (Computer Science
& Engineering)
PROJECT BASED LEARNING IN JAVA WITH LAB
(22CSH-359/22ITH-359)
TOPIC OF PRESENTATION:
HttpServlet Request and Response,
Servlet with JDBC (CO 5)
DISCOVER . LEARN .
EMPOWER
Lecture Objectives
2
Servlets Request Interface
ServletRequest Interface
The ServletRequest Interface is used
to handle client request to access a
servlet. It provides the information of
a servlet like content type, content
length, parameter names and values
etc.
Servlets Request Interface
Servlets
Method init
Called exactly once, before client requests
Initialization parameters
Method destroy
Called automatically, cleanup method
Close files, connections to databases, etc.
Using JDBC from a Servlet
HTML files
<INPUT TYPE=CHECKBOX NAME=name
VALUE=value>
Creates checkbox, any number can be selected
Example servlet
Guest book to register for mailing lists
HTML document first tier
Get data from user
Use servlet as middle tier
Provides access to database
Set up connection in init
Microsoft Access database (third tier)
1// Fig. 19.16: GuestBookServlet.java
3import java.io.*;
4import javax.servlet.*;
5import javax.servlet.http.*;
6import java.util.*;
7import java.sql.*;
13
16 {
init called exactly once, before
17 super.init( config );
client requests are processed. Note
18
the first line format. 1. import
19 try {
21 connection = 2. init
23 }
24 catch ( Exception e ) {
25 e.printStackTrace();
26 connection = null;
Get connection to database (no name/password).
27 }
28 }
29
30 public void doPost( HttpServletRequest req,
31 HttpServletResponse res )
33 {
36 iwwwList;
37
47
49 res.setContentType( "text/html" );
3.1 getParameter
50
51 if ( email.equals( "" ) ||
3.2 getWriter
53 lastName.equals( "" ) ) {
56 "fields.</H3>" );
57 output.close();
58 return;
59 }
60
61 /* Note: The GuestBook database actually contains fields
62 * Address1, Address2, City, State and Zip that are not
63 * used in this example. However, the insert into the
64 * database must still account for these fields. */
65 boolean success = insertIntoDB(
66 "'" + email + "','" + firstName + "','" + lastName +
67 "','" + company + "',' ',' ',' ',' ',' ','" +
68 ( snailmailList != null ? "yes" : "no" ) + "','" +
69 ( cppList != null ? "yes" : "no" ) + "','" +
70 ( javaList != null ? "yes" : "no" ) + "','" +
71 ( vbList != null ? "yes" : "no" ) + "','" +
72 ( iwwwList != null ? "yes" : "no" ) + "'" );
73
74 if ( success )
75 output.print( "<H2>Thank you " + firstName +
76 " for registering.</H2>" );
77 else
78 output.print( "<H2>An error occurred. " + 4. insertIntoDB
79 "Please try again later.</H2>" );
80 4.1 createStatement
81 output.close();
82 }
83
84 private boolean insertIntoDB( String stringtoinsert )
85 {
86 try {
87 statement = connection.createStatement();
88 statement.execute(
93 catch ( Exception e ) {
94 System.err.println(
96 e.printStackTrace();
97 return false;
98 }
99
101 }
105 try {
106 connection.close();
4.2 INSERT INTO
107 }
111 }
112 }
1<!-- Fig. 19.17: GuestBookForm.html -->
2<HTML>
3<HEAD>
5</HEAD>
7<BODY>
8 <H1>Guest Book</H1>
9 <FORM
10 ACTION=http://lab.cs.siu.edu:8080/rahimi/GuestBookServlet
11 METHOD=POST><PRE>
16
18 </PRE>
19
20 <P>Select mailing lists from which you want checkboxes for user
1. <FORM>
23 Snail Mail<BR>
22
Agenda
4 Accessing database
23
Objectives
At the end of this module, you will be able to:
24
The doGet and doPost methods
• Methods doGet() and doPost() in HttpServlet class receives appropriate
client request, and formats a response using 2 arguments
• An HttpServletRequest object - encapsulates data from the
client
• An HttpServletResponse object - encapsulates response
to the
client
• Usage:
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
• Methods:
– getWriter
– setContentType
27
– sendRedirect
First Servlet Example -
Demo
28
Create the dynamic web project
29
Configure tomcat server in Eclipse? (One time Requirement)
30
Enable web.xml deployment descriptor
31
Create the servlet
32
Select the servlet option
33
Type class name
34
35
Select Finish
36
37
Source Code for First_Servlet_Program Example
38
Output response
39
Request Object
40
Create HTML file – index.html
41
Request object Parameters – Form Data
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
out.println("<body bgcolor=\"yellow\">");
out.println("<h1>"+"Request object Parameters: " + "</h1>"+"<br>");
out.println("<h2>" + "User Details" + "</h2>"); Enumeration<String> reqParams =
request.getParameterNames();
while (reqParams.hasMoreElements()) {
String name = (String)reqParams.nextElement(); String value = request.getParameter(name);
out.println("<b> "+name + "</b>"+ " = " +value+"<br>");
}
out.println("</body>"); out.println("</html>");
42
Request object Info
response.setContentType("text/html");
out.println("<html>"); out.println("<head>");
out.println("<title> Request Object example </title>");
out.println("</head>");
out.println("</body>");
out.println("</html>");
43
}
Request object Headers details
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
out.println("<body bgcolor=\"yellow\">");
while (reqHeaders.hasMoreElements()) {
String name = (String)reqHeaders.nextElement(); String value =
request.getHeader(name); out.println("<tr><td bgcolor=\"#CCCCCC\">");
out.println("<b>" + name + "</b>" +" = " + value); out.println("</td><td>");
out.println("</td></tr>");
}
out.println("</table>");
out.println("</body>"); out.println("</html>");
}
44
Handling Form Data
45
Handling Form
Data
• Write a Servlet that retrieves form parameters from the HTML
form
• Simpleform.html
<html>
<head><title>Simple Form</title></head>
<body>
<form method=“post” action=“SimpleFormServlet”>
<h3>Enter user details</h3>
<br>Name: <input type=“text” name=“userName” />
<br>Address: <input type=“text” name=“userAddress” />
<input type=“submit” value=“Submit” />
46
</form>
</body>
The getParameter() method
• Syntax: public String getParameter(String name)
returned
• If parameter does not exist, then null is returned
• Use this method when you are sure the parameter has only one value
47
• Example: String name = request.getParameter("userName");
Example Servlet: Handling Form
Data
• SimpleFormServlet's doPost method retrieves request
parameters such as user’s name and address having a
single value from the form
48
Demo for Handling Simple Form
Data
• Demonstrate a SimpleFormServlet with a doPost method that
retrieves request parameters such as user’s name and
address having a single value from the form (getParameter
method)
49
Reason it out
50
Form Data for different HTML Components
• Suppose a Job seeker Company needs basic information
about the user’s name, address, state, highest qualification
and skills
comp.html
<html>
<head><title>Information
Details</title></head>
<body>
<form action=“differentCompServlet"
method=POST>
<BR>Name: <input type=text name=”name” />
<BR>Address: <textarea name=”address”
rows=5 cols=20></textarea>
51
<BR>State: <select name="state">
Form Data for different HTML Components (Contd.).
comp.ht
ml
<BR><BR>Highest Qualification:<BR>
Under Graduate<input type=radio name=qualification value=”UG”> Post
Graduate<input type=radio name=qualification value=”PG”>
<BR><BR>Skills:<BR>
Java<input type=checkbox name=skills value=Java>
Servlets<input type=checkbox name=skills value=Servlets>
JSPs<input type=checkbox name=skills value=JSPs> EJB 3.0<input type=checkbox
name=skills value=EJB>
<BR><BR><input type=submit value=submit><input type=reset>
</form>
</body>
</html>
52
Methods: getParameterNames() and getParameterValues()
32 • checkbox
Use this method if a parameter has more than one value. Ex:
Example Servlet: Listing different Form Data
while(e.hasMoreElements()) {
String pname = (String) e.nextElement();
String pvalues[] = req.getParameterValues(pname); pw.println(pname+" :
");
// print parameter values by iterating through array
for(int count = 0; count < pvalues.length; count++)
{
54
pw.println(pvalues[count]);
}
Demo for Handling Different Form Data
• Demonstrate a DifferentFormServlet with a doPost
method that retrieves request parameters of various form
data using getParameterNames and getParameterValues
55
Using JDBC in a
Servlet
• A servlet can retrieve information from a database
or perform update/delete/insert queries to/from a
database Web Server
Servlet Container
Browser Database
DatabaseServlet
Request
Response
56
Demo for accessing database
• A servlet to display records from database table
import java.sql.*;
import javax.servlet.*; import javax.servlet.http.*; import
java.io.*;
public class DatabaseServlet extends HttpServlet {
Connection con; PreparedStatement st; Statement stmt;
ResultSet rs;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("Jdbc:Odbc:vdsn2", "scott",
"tiger");
System.out.println("Connected..");
} catch (Exception e) {
System.out.println("Error in connection.."); }}
57
Demo for accessing database (Contd.).
59
Quiz
1. The doGet() or doPost() method of a Servlet are invoked by
1. init() method
2. service() method
3. destroy() method
60
Thank
You
61
Summary: