Professional Documents
Culture Documents
Introduction To Java Programme
Introduction To Java Programme
Execute CGI
Program
get CGI code
Difference b/w CGI & Servlets
• CGI is extremely slow when handling a
large number of requests simultaneously,
because the web server must spawn a
process for executing each CGI program.
• Java servlets were developed to remedy
the performance problem of CGI
programs. Java servlets are basically
Java programs that behave like CGI
programs.
Difference between servlets and CGI
• Efficient, Convenient, Powerful, Portable,
Secure, Inexpensive
– Lightweight threads instead of OS threads created
– Single copy of code brought into memory for all
threads versus per thread
– Data (session state) can be stored across threads
within servlet container
– Java is portable and secure
– Requires little expense once servlet container
integrated with web server
• In CGI for each request the server creates one
process, whereas in Servlet for all the requests
the server creates only one process but multiple
threads.
Java Servlets
• Java servlets are executed upon request from a web
browser.
• All servlets execute inside a servlet container, also
referred to as a servlet server or a servlet engine.
• A servlet container is a single process that runs a JVM
(Java Virtual Machine).
• The JVM creates a thread to handle each servlet (recall
that threads have considerably less overhead than full-
blown processes).
• All the threads share the same memory allocated to the
JVM.
• The server that executes a servlet is referred to as
the servlet container or servlet engine.
• We’ll look at servlets that implement
the request-response model between
clients and servers using the HTTP
protocol. This architecture is shown
in the diagram below.
• A client application sends an
HTTP request to the server.
• The servlet container receives
the request and directs it to be
processed by the appropriate
servlet.
• The servlet does its processing,
which may include interacting
with a database or other
server-side components, such
as other servlets or JSPs.
• The servlet returns its results to
the client – normally in the form
of an HTML, XHTML, or XML
document to display in a
browser.
Skelton Structure of Servlets
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public lcass hi extends GenericServlet\
{
public void init(ServletConfig sc) throws ServletException;
{
}
void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException;
void destroy();
}
Setting up Tomcat
• Tomcat is a fully functional implementation of
servlets and JSP. It includes a Web server, so it
can be used as a standalone test container for
servlets and JSPs.
• After the Tomcat is installed you’re ready to run
a demonstration test that will tell you if you’ve got
everything set-up properly.
• During the install, Tomcat will ask you which TCP
port Tomcat should run on. To avoid any conflict
with standard Web servers which default to TCP
port 80, Tomcat is set to default to TCP port
8080. If you have any other service running on
this port change the port number at this time to
one on which no conflict will occur.
Starting Up Tomcat
• class HttpServlet
(from the package javax.servlet.http).
LIB DIRECTORY
Simple Servlet
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
javax.Servlet package
The servlet package consisting of
Servlet interface
• Servlet interface
ServletConfig interface
ServletContext interface
• ServletRequest interface
ServletResponse interface
Classes in servlet package
javax.servlet.http package
HttpServletRequest interface
HttpServletRequest interface
HTTPServletResponse Methods
• void addCookie (Cookie cookie) – adds a Cookie to
the header of the response to the client.
• ServletOutputStream getOutputStream() – gets a
byte-based output stream for sending binary data to the client.
• PrintWriter getWriter() – gets a character-based
output stream for sending text data (typically HTML formatted
text) to the client.
• void SetContentType (String type) – specifies the
content type of the response to the browser to assist in
displaying the data.
• void getContentType() – gets the content type of the
response.
HTTPServletRequest Methods
• Cookie[] getCookies() – returns an array of Cookie
objects stored on the client by the server. Cookies are used
to uniquely identify clients to the server.
• String getLocalName() – gets the host name on which
the request was received.
• String getLocalAddr() – gets the IP address on which
the request was received.
• int getLocalPort() – gets the IP port number on which
the request was received.
• String getParameter( String name) – gets the value
of a parameter set to the servlet as part of a get or post
request.
HttpSession interface
HttpSessionBindingListener Interface
setPath(string) Sets or retrieves the path to which the cookie applies. If you do not
specify a path, the browser returns the cookie only to URLs in or
getPath() below the directory containing the page that sent the cookie.
setSecure(boolean) Sets or retrieves the boolean value which indicates whether the
cookie should only be sent over encrypted connections. The default is
getSecure() false.
setValue(string)
Sets or retrieves the value associated with the cookie.
getValue()
Session Tracking
• As we mentioned before, HTTP is a “stateless” protocol: each time a
client retrieves a web page, the client opens a separate connection
to the web server and the server does not automatically maintain
contextual information about the client.
• Even with servers that support persistent (keep-alive) HTTP
connections and keep sockets open for multiple client requests that
occur in rapid succession, there is no built-in support for maintaining
contextual information.
• This lack of context causes a number of difficulties. For example,
when clients at an online store add an item to their shopping carts,
how does the server know what’s already in the carts? Similarly,
when clients decide to proceed to checkout, how can the server
determine which of the previously created shopping carts are theirs?
• Servlets provide an outstanding session tracking solution: the
HttpSession API. This high-level interface is built on top of
cookies (and URL rewriting). All servers are required to support
session tracking with cookies.
Session Tracking (cont.)
• Using sessions in servlets is straightforward and involves four
basic steps:
1. Accessing the session object associated with the current request.
Call request.getSession to get an HttpSession object,
which is a simple hash table for storing user-specific data.
2. Looking up information associated with a session. Call
getAttribute on the HttpSession object, cast the return
value to the appropriate type, and check whether the result is null.
3. Storing information in a session. Use setAttribute with a key
and a value.
4. Discarding session data. Call removeAttribute to discard a
specific value. Call invalidate to discard an entire session.
Call logout to log the client out of the web server and invalidate
all sessions associated with that user.
Html page for get request
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>ColorGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
</web-app>
Http post request
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
ColorPostServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>ColorPostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
</web-app>
Html document
<html>
<head></head>
<body>
<form action="/phani1/hello" method="get">
<p><label>click this button
<input type="submit" value="click" />
</label>
</p>
</body>
</html>
Some.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class some extends HttpServlet
{
public void doGet(HttpServletRequest
req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("hihihihihih");
out.close();
}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>some</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
</web-app>
Passing Parameter Using Html
Form
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<h2>Login</h2>
<p>Please enter your username and password</p>
<form method="GET" action="/htmlform/LoginServlet">
<p> Username <input type="text" name="username" size="20"></p>
<p> Password <input type="text" name="password" size="20"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
<p> </p>
</body>
</html>
Loginservlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String pass = request.getParameter("password");
out.println("<html>");
out.println("<body>");
out.println("Thanks Mr." + " " + name + " " + "for visiting vrsec<br>" );
out.println("Now you can see your password : " + " " + pass + "<br>");
out.println("</body></html>");
}
}
web.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
Redirect in servlet
Login.html
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<form method="POST"
action="/SendRedirect/SendRedirectServlet">
<p>Enter your name
<input type="text" name="username" size="20"></p>
<p>Enter your password
<input type="text" name="password" size="20"></p>
<p > <input type="submit" value="Submit"
name="B1"></p>
</form>
</body>
</html>
SendRedirectServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SendRedirectServlet extends HttpServlet{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
if(name.equals(“phani")&& password.equals("abc")){
response.sendRedirect("/SendRedirect/ValidUserServlet");
}
else{
pw.println("u r not a valid user");
}
}
}
ValidUserServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ValidUserServlet extends HttpServlet{
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException {
PrintWriter pw = response.getWriter();
pw.println("Welcome to IT " + " ");
pw.println("how are you");
}
}
Web.xml
<web-app>
<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>SendRedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>/SendRedirectServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>ValidUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/ValidUserServlet</url-pattern>
</servlet-mapping>
</web-app>
Getting InitInitServlet.java
Parameter Names
import java.io.*;
import javax.servlet.*;import javax.servlet.http.*;
import java.util.*;
public class InitServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.print("Init Parameters are : ");
Enumeration enumeration = getServletConfig().getInitParameterNames();
while(enumeration.hasMoreElements())
{
pw.print(enumeration.nextElement() + " ");
}
pw.println("\nThe email address is " +
getServletConfig().getInitParameter("AdminEmail"));
pw.println("The address is " +
getServletConfig().getInitParameter("Address"));
pw.println("The phone no is " +
getServletConfig().getInitParameter("PhoneNo"));
}
}
web.xml
<web-app>
<servlet>
<init-param>
<param-name>AdminEmail</param-name>
<param-value>it@yahoomail.com</param-value>
</init-param>
<init-param>
<param-name>Address</param-name>
<param-value>kanuru</param-value>
</init-param>
<init-param>
<param-name>PhoneNo</param-name>
<param-value>9948099480</param-value>
</init-param>
<servlet-name>hi</servlet-name>
<servlet-class>InitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>/InitServlet</url-pattern>
</servlet-mapping>
</web-app>
Program on Cookies
File Description
AddCookie.htm
Allows a user to specify a value for the
cookie named MyCookie.
AddCookieServlet.java
Processes the submission of
AddCookie.htm.
GetCookiesServlet.java
Displays cookie values.
AddCookie.htm
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/AddCookieServ
let">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}}
GetCookieServlet.java
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.