0% found this document useful (0 votes)
42 views

FALLSEM2021-22 CSE1007 ETH VL2021220104880 Reference Material I 22-Oct-2021 1. Java Servlets

The document provides an overview of Java servlets, including: 1) Servlets are Java programs that run on the server and handle requests from clients to dynamically generate web pages. They access databases or other resources to create and format responses sent back to users. 2) Servlets were created to provide a more efficient solution than CGI for powering dynamic websites. They offer advantages like single-threaded request handling, data sharing between servlets, and direct access to web servers. 3) Servlets require a Java server, such as Tomcat, to run and interact with clients. Java Server Pages (JSP) allow mixing static HTML with servlet code to separate the presentation from dynamic content generation.

Uploaded by

akshata bhat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

FALLSEM2021-22 CSE1007 ETH VL2021220104880 Reference Material I 22-Oct-2021 1. Java Servlets

The document provides an overview of Java servlets, including: 1) Servlets are Java programs that run on the server and handle requests from clients to dynamically generate web pages. They access databases or other resources to create and format responses sent back to users. 2) Servlets were created to provide a more efficient solution than CGI for powering dynamic websites. They offer advantages like single-threaded request handling, data sharing between servlets, and direct access to web servers. 3) Servlets require a Java server, such as Tomcat, to run and interact with clients. Java Server Pages (JSP) allow mixing static HTML with servlet code to separate the presentation from dynamic content generation.

Uploaded by

akshata bhat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Java Servlets

What Are Servlets?


 Basically, a java program that runs on the
server
 Creates dynamic web pages
What Do They Do?
 Handle data/requests sent by users
(clients)
 Create and format results
 Send results back to user
Who Uses Servlets?
 Servlets are useful in many business
oriented websites

 … and MANY others


History
 Dynamic websites were often created with
CGI
 CGI: Common Gateway Interface
 Poor solution to today’s needs
 A better solution was needed
Servlets vs. CGI
 Servlet Advantages
 Efficient
 Single lightweight java thread handles multiple requests
 Optimizations such as computation caching and keeping
connections to databases open
 Convenient
 Many programmers today already know java
 Powerful
 Can talk directly to the web server
 Share data with other servlets
 Maintain data from request to request
 Portable
 Java is supported by every major web browser (through plugins)
 Inexpensive
 Adding servlet support to a server is cheap or free
Servlets vs. CGI
 CGI Advantages
 CGI scripts can be written in any language
 Does not depend on servlet-enabled server
What Servlets Need
 JavaServer Web Development Kit (JSWDK)
 Servlet capable server
 Java Server Pages (JSP)
 Servlet code
Java Server Web Development Kit

 JSWDK
 Small, stand-alone server for testing servlets
and JSP pages
 The J2EE SDK
 Includes Java Servlets 2.4
Servlet capable server

Apache
 Popular, open-source server
 Tomcat
 A “servlet container” used with Apache

Other servers are available


Java Server Pages
 Lets you mix regular, static HTML pages with
dynamically-generated HTML
 Does not extend functionality of Servlets
 Allows you to separate “look” of the site from
the dynamic “content”
 Webpage designers create the HTML
 Servlet programmers create the dynamic content
 Changes in HTML don’t effect servlets
<head>
</head>
<body>
<%
// jsp sample code
out.println(" JSP, ASP, CF, PHP - you name it, we support it!");
%>
</body>
</html>

<html>
<head>
</head>
<body>
<b>
JSP, ASP, CF, PHP - you name it, we support it!
</b>
</body>
</html>
</font>
<head>
</head>
<body>
<%
// jsp sample code
out.println(" JSP, ASP, CF, PHP - you name it, we support it!");
%>
</body>
</html>

<html>
<head>
</head>
<body>
<b>
JSP, ASP, CF, PHP - you name it, we support it!
</b>
</body>
</html>
</font>
<head>
</head>
<body>
<%
// jsp sample code
out.println(" JSP, ASP, CF, PHP - you name it, we support it!");
%>
</body>
</html>

<html>
<head>
</head>
<body>
<b>
JSP, ASP, CF, PHP - you name it, we support it!
</b>
</body>
</html>
</font>
<head>
</head>
<body>
<%
// jsp sample code
out.println(" JSP, ASP, CF, PHP - you name it, we support it!");
%>
</body>
</html>

<html>
<head>
</head>
<body>
<b>
JSP, ASP, CF, PHP - you name it, we support it!
</b>
</body>
</html>
</font>
Servlet Code
 Written in standard Java
 Implement the javax.servlet.Servlet
interface
package servlet_tutorials.PhoneBook;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.net.*;

public class SearchPhoneBookServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

String query = null;


String where = null;
String firstname = null;
String lastname = null;
ResultSet rs = null;

res.setContentType("text/html");
PrintWriter out = res.getWriter();

// check which if any fields in the submitted form are empty


if (req.getParameter("FirstName").length() > 0)
firstname = req.getParameter("FirstName");
else firstname = null;
}
Main Concepts of Servlet
Programming
 Life Cycle
 Client Interaction
 Saving State
 Servlet Communication
 Calling Servlets
 Request Attributes and Resources
 Multithreading
Life Cycle
 Initialize
 Service
 Destroy
Life Cycle: Initialize
 Servlet is created when servlet container
receives a request from the client

 Init() method is called only once


Life Cycle: Service
 Any requests will be forwarded to the
service() method
 doGet()
 doPost()
 doDelete()
 doOptions()
 doPut()
 doTrace()
Life Cycle: Destroy
 destroy() method is called only once
 Occurs when
 Application is stopped
 Servlet container shuts down
 Allows resources to be freed
Client Interaction
 Request
 Client (browser) sends a request containing
 Request line (method type, URL, protocol)
 Header variables (optional)
 Message body (optional)
 Response
 Sent by server to client
 response line (server protocol and status code)
 header variables (server and response information)
 message body (response, such as HTML)
 Thin clients (minimize download)
 Java all “server side”

Servlets

Client
Server
Saving State
 Session Tracking
 A mechanism that servlets use to maintain
state about a series of requests from the
same user (browser) across some period of
time.
 Cookies
 A mechanism that a servlet uses to have
clients hold a small amount of state-
information associated with the user.
Servlet Communication
 To satisfy client requests, servlets
sometimes need to access network
resources: other servlets, HTML pages,
objects shared among servlets at the
same server, and so on.
Calling Servlets
 Typing a servlet URL into a browser
window
 Servlets can be called directly by typing their
URL into a browser's location window.
 Calling a servlet from within an HTML
page
 Servlet URLs can be used in HTML tags,
where a URL for a CGI-bin script or file URL
might be found.
Request Attributes and Resources

 Request Attributes
 getAttribute
 getAttributeNames
 setAttribute
 Request Resources - gives you access to
external resources
 getResource
 getResourceAsStream
Multithreading
 Concurrent requests for a servlet are handled by
separate threads executing the corresponding
request processing method (e.g. doGet or
doPost). It's therefore important that these
methods are thread safe.
 The easiest way to guarantee that the code is
thread safe is to avoid instance variables
altogether and instead use synchronized blocks.
Simple Counter Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

 public class SimpleCounter extends HttpServlet {


 int count = 0;
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
 res.setContentType("text/plain");
 PrintWriter out = res.getWriter();
 count++;
 out.println("This servlet has been accessed " + count + " times since
loading");
 }
 }
MultiThread Problems
 Problem - Synchronization between threads
count++; // by thread1
Two Requests will
count++; // by thread2
get the same
out.println.. // by thread1
value of counter
out.println.. // by thread2
 Solution - Use Synchronized Block!
 Synchronized Block
 Lock(Monitor)
Better Approach
 The approach would be to synchronize only the section
of code that needs to be executed automically:
PrintWriter out = res.getWriter();
synchronized(this)
{
    count++;
    out.println("This servlet has been accessed " +
             count + "times since loading");
}
This reduces the amount of time the servlet spends in its
synchronized block, and still maintains a consistent
count.
Example: On-line Phone Book
 Design
Example: On-line Phone Book
Search Form
Java server Page
Search_phone_book.jsp
<html>
<head>
<title>Search Phonebook</title>
</head>
<body bgcolor="#FFFFFF"> <p><b>
Search Company Phone Book</b></p>
<form name="form1" method="get"
action="servlet/servlet_tutorials.PhoneBook.SearchPhoneBookServlet">
<table border="0" cellspacing="0" cellpadding="6"> <tr> <td >Search by</td>
<td>
</td> </tr> <tr> <td><b>
First Name
</b></td> <td>
<input type="text" name="FirstName"> AND/OR</td> </tr> <tr> <td ><b>
Last Name
</b></td> <td >
<input type="text" name="LastName"></td> </tr> <tr> <td ></td> <td >
<input type="submit" name="Submit" value="Submit">
</td> </tr> </table>
</form>
</body>
</html>
Example: On-line Phone Book
Display Results
Java Server Page
Display_search_results.jsp
<html>
<%@page import ="java.sql.*" %>
<jsp:useBean id="phone" class="servlet_tutorials.PhoneBook.PhoneBookBean"/>
<%@ page buffer=35 %>
<%@ page errorPage="error.jsp" %>
<html>
<head>
<title>Phone Book Search Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head>
<body bgcolor="#FFFFFF"> <b>Search Results</b> <p>
<% String q = request.getParameter("query");
ResultSet rs = phone.getResultSet(q);
%>
<% if (rs.wasNull()) {
%>
"NO RESULTS FOUND"
<%
} else
%>
<table> <tr> <td> <div align="center">First Name</b></div> </td> <td> <div align="center">Last
Name</font></b></div> </td> <td> <div align="center">Phone Number</font></b></div> </td> <td>
<div align="center">Email</font></b></div> </td> </tr>
<% while(rs.next()) { %> <tr> <td>
<%= rs.getString("first_name") %></td> <td><%= rs.getString("last_name") %></td> <td><
%= rs.getString("phone_number") %>
</td> <td>
<%= rs.getString("e_mail") %>
</td> </tr>
<% } %>
</table>
Servlet
Listing 2 SearchPhoneBookServlet.java

package servlet_tutorials.PhoneBook;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.net.*;

public class SearchPhoneBookServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

String query = null;


String where = null;
String firstname = null;
String lastname = null;
ResultSet rs = null;

res.setContentType("text/html");
PrintWriter out = res.getWriter();

// check which if any fields in the submitted form are empty


if (req.getParameter("FirstName").length() > 0)
firstname = req.getParameter("FirstName");
else firstname = null;

if (req.getParameter("LastName").length() > 0)
lastname = req.getParameter("LastName");
else lastname = null;

// Build sql query string


if ((firstname != null) && (lastname != null)){
where = "first_name ='";
where += firstname;
where += "' AND ";
where += "last_name ='";
where += lastname;
where += "'";
}
else if ((firstname == null) && (lastname != null)){
where = "last_name ='";
where += lastname;
where += "'";
Java Bean & Database linked
Listing 4 PhoneBookBean.java Listing 5 ConnectDB.java

package servlet_tutorials.PhoneBook;
package servlet_tutorials.PhoneBook; import java.io.*;
import java.io.*; import java.net.*;
import java.sql.*;
import java.net.*; import java.util.*;
import java.sql.*;
import java.util.*; /**
* Re-usable database connection class
*/
public class PhoneBookBean { public class ConnectDB {
private Connection con = null; // setup connection values to the database
private Statement stmt = null; static final String DB_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
static final String URL = "jdbc:odbc:PhoneBook";
private ResultSet rs = null; static final String USERNAME = "anon_user";
private String query = null; static final String PASSWORD = "";

// Load the driver when this class is first loaded


public PhoneBookBean() {} static {
try {
public ResultSet getResultSet(String query) { Class.forName(DB_DRIVER).newInstance();
}
// grab a connection to the database catch (ClassNotFoundException cnfx) {
con = ConnectDB.getConnection(); cnfx.printStackTrace();
try{ }
catch (IllegalAccessException iaex){
stmt = con.createStatement(); iaex.printStackTrace();
// run the sql query to obtain a result set }
rs = stmt.executeQuery(query); catch(InstantiationException iex){
} iex.printStackTrace ();
}
catch(SQLException sqlex){ }
sqlex.printStackTrace();
} /**
* Returns a connection to the database
catch (RuntimeException rex) { */
rex.printStackTrace(); public static Connection getConnection() {
} Connection con = null;
try {
catch (Exception ex) { con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
ex.printStackTrace(); } }
return rs; catch (Exception e) {
e.printStackTrace();
} }
} finally {
return con;
References
 http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overview.html
 www.cis.upenn.edu/~matuszek/ cit597-2004/Lectures/21-servlets.ppt
 http://learning.unl.ac.uk/im269/lectures/week6servletsp1.ppt
 http://java.sun.com/docs/books/tutorialNB/download/tut-servlets.zip
 http://www.webdevelopersjournal.com/articles/intro_to_servlets.html

You might also like