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

Java Servlets_New1

The document provides an overview of Java Servlets, explaining their role as server-side components that handle HTTP requests and responses. It details the differences between GET and POST methods, servlet lifecycle methods (init, service, destroy), and how to process form data. Additionally, it covers session tracking techniques, page redirection, and basic database access in web applications using servlets.

Uploaded by

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

Java Servlets_New1

The document provides an overview of Java Servlets, explaining their role as server-side components that handle HTTP requests and responses. It details the differences between GET and POST methods, servlet lifecycle methods (init, service, destroy), and how to process form data. Additionally, it covers session tracking techniques, page redirection, and basic database access in web applications using servlets.

Uploaded by

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

Java Servlets

WEB APPLICATIONS
INTRODUCTION TO WEB
► GET Request data is sent in header to the
server. POST data is sent in request body.
► Get request can send only limited amount of
data upto 1024 characters. POST method
Large amount of data can be sent.
► Get request is not secured because data is
exposed in URL Post request is secured
because data is not exposed in URL.
► Get should never be used when dealing with
sensitive data
HTTP requests

► When a request is submitted from a Web page, it is


almost always a GET or a POST request
► The HTTP <form> tag has an attribute action,
whose value can be "get" or "post"
► The "get" action results in the form information
being put after a ? in the URL
► Example:
http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=servlets
► The & separates the various parameters
► Only a limited amount of information can be sent this way

► "post" can send large amounts of information


What are Servlets?
► Java Servlets are programs that run on a
Web Server or Application server and act as
a middle layer between a requests coming
from a Web browser or other HTTP client
and databases or applications on the HTTP
server.
► Technology for generating Dynamic Web
pages.
► They are used to handle the request
obtained from the web server, process the
request, produce the response, then send
response back to the web server.
► Servlets work on the server-side.
Servlet Tasks
► Execution of Servlets involves the six basic steps:
► The clients send the request to the web server.
► The web server receives the request.
► The web server passes the request to the corresponding
servlet.
► The servlet processes the request and generate the
response in the form of output.
► The servlet send the response back to the web server.
► The web server sends the response back to the client
and the client browser displays it on the screen.
Servlet Tasks
► Read the explicit data sent by the clients (browsers).
This includes an HTML form on a Web page or it could
also come from an applet or a custom HTTP client
program.
► Read the implicit HTTP request data sent by the clients
(browsers). This includes cookies, media types and
compression schemes the browser understands, and so
forth.
► Process the data and generate the results. This process
may require talking to a database, executing an RMI
call, invoking a Web service, or computing the response
directly
Servlet Task Contd...
► Send the explicit data (i.e., the document)
to the clients (browsers). This document can
be sent in a variety of formats, including text
(HTML or XML), binary (GIF images), Excel,
etc.
► Send the implicit HTTP response to the
clients (browsers). This includes telling the
browsers or other clients what type of
document is being returned (e.g., HTML),
setting cookies and caching parameters, and
other such tasks.
Servlets Packages
► Servlets can be created using the
javax.servlet and javax.servlet.http
packages, which are a standard part of
the Java's enterprise edition,
► Java servlets have been created and
compiled just like any other Java class.
After you install the servlet packages and
add them to your computer's Classpath,
you can compile servlets with the JDK's
Java compiler
• Creates Web Application

• Provides interfaces and classes

• Responds to any incoming requests

• Deployed to create dynamic web

page

• Robust and Scaleable


Servlet Architecture
► Theweb container maintains the life
cycle of a servlet instance
Methods used

► init() :
⮚ The init method is called only once. It is
called only when the servlet is created,
and not called for any user requests.
⮚ This method allows the servlet to per
form any setup processing such as
opening files or establishing connections
to their servers. If a servlet has been
permanently installed in a server, it
loads when the server starts to run.
Methods used
► Service():
⮚ The service() method is the main method to perform
the actual task.
⮚ The service() method is the heart of the servlet.
Each request message from a client results in a single
call to the servlet’s service() method.
⮚ Each time the server receives a request for a servlet,
the server spawns a new thread and calls service.
The service() method checks the HTTP request type
(GET, POST, PUT, DELETE, etc.) and calls doGet,
doPost, doPut, doDelete, etc. methods as
appropriate.
► Service():
⮚ The service() method reads the request and
produces the response message from its two
parameters: A ServletRequest object with data
from the client. A ServletResponse represents the
servlet’s reply back to the client. The service()
method’s job is conceptually simple—it creates a
response for each client request sent to it from the
host server.
⮚ The servlet container calls the service() method to
handle requests coming from the client or browsers
and to write the formatted response back to the
client. The service() method checks the HTTP
request type such as GET, POST etc and calls
doGet, doPost etc.
Methods used

► destroy():It is called only once at the end of


the life cycle of a servlet. To destroy the
servlet
► The destroy() method is called to allow
your servlet to clean up any resources
(such as open files or database
connections) before the servlet is
unloaded. If you do not require any clean-
up operations, this can be an empty
method. The server waits to call the
destroy() method until either all service
calls are complete, or a certain amount of
time has passed.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet
{
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() { // do nothing. }
}
Form Processing

► Usually we come across many situations when we need


to pass some information from your browser to web
server
► The browser uses two methods to pass this information
to web server. These methods are GET Method and
POST Method.
GET Method
► The GET method sends the encoded user information appended to the page
request. The page and the encoded information are separated by the ?
(question mark) symbol
► Example
http://www.test.com/hello?key1=value1&key2=value2
► The GET method is the default method to pass information from browser to
web server and it produces a long string that appears in your browser's
Location: box.
► Never use the GET method if you have password or other sensitive information
to pass to the server
► The GET method has size limitation: only 1024 characters can be used in a
request string
► Servlet handles this type of requests using doGet() method
POST Method
► This packages the information in exactly the same way as GET
method, but instead of sending it as a text string after a ? (question
mark) in the URL it sends it as a separate message.
► A generally more reliable method of passing information to a backend
program is the POST method
► This message comes to the backend program in the form of the
standard input which you can parse and use for your processing
► Servlet handles this type of requests using doPost() method.
Reading Form Data using Servlet

► There are 3 methods used to access/Read


Form Data

1.getParameter(): You call


request.getParameter() method to get the
value of a form parameter.
2.getParameterValues(): Call this method if
the parameter appears more than once and
returns multiple values, for example
checkbox.
3.getParameterNames(): Call this method if
you want a complete list of all parameters in
the current request.
Example using GET method and
getParameter()
► simple URL which will pass two values to HelloForm program
using GET method.
► http://localhost:8080/ServletDemo/HelloForm?first_name
=KLE&last_name=BCA
► Lets see the program which handles the request with get
Parameter
Example using POST method
and getParameterValues()
with HTML Form
Example program on getParameterNames()
Session Tracking
► Session: A session can be defined as a series of
related interactions between a single client and
the Web server over a period of time
► Session Tracking: To track data among
requests in a session is known as session
tracking.
► Approaches to Session-Tracking:-
1. Using Session Tracking API
2. Cookies
3. Hidden Form Field
4. Using URL -rewriting
Session Tracking cotn....
► Cookies : Assign a unique session ID
► Hidden Form Fields:A web server can send a hidden HTML form field
along with a unique session ID as follows −
► <input type = "hidden" name = "sessionid" value = "12345">
► hypertext link does not result in a form submission, so hidden form fields
also cannot support general session tracking.
► URL Rewriting: You can append some extra data on the end of each URL
that identifies the session, and the server can associate that session
identifier with data it has stored about that session
► For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session
identifier is attached as sessionid = 12345 which can be accessed at the web
server to identify the client.
► The HttpSession Object:The servlet container uses this interface to
create a session between an HTTP client and an HTTP server. The
session persists for a specified time period, across more than one
connection or page request from the user.
► Java Servlet API provides an interface called
HttpSession that can be used to keep track of
sessions
1. HttpSession s=request.getSession()
2. boolean b=s.IsNew();
3. s.invalidate()
4. Long l=s.getCreationTime();
5. Long l=s.getLastAccessedTime();
6. s.setAttribute(“userid”,a)
7. Object o=s.getAtribute(“userid”);
8. S.removeAttribute(“userid”);
► Configure Session Time out in Deployment
Descriptor (i.e. web.xml file)
<session-config>
<session-timeout>15</session-timeout>
//15 min
</session-config>
Or
session.setMaxInactiveInterval (20*60); //20
minute
METHOD DESCRIPTION
Gets the HttpSession object. If the
request doesn’t have a session
public HttpSession getSession()
associated with it, a new session is
created
Gets the session associated with the
public HttpSession request. If not already present, then a
getSession(boolean create) new one is created based on the value
of the boolean argument passed into it
public String getId() Returns the unique session id
It returns the time when this session
public long getCreationTime() was created, measured in milliseconds
since midnight January 1, 1970 GMT.
It returns the time when this session
public long was last accessed, measured in
getLastAccessedTime() milliseconds since midnight January 1,
1970 GMT.
It returns the time when this session
public long was last accessed, measured in
getLastAccessedTime() milliseconds since midnight January 1,
►Program to Handle
Sessions
Page Redirection
► Page redirection is a technique where the client is
sent to a new location (page )other than requested
page
► The simplest way of redirecting a request to another
page is using method sendRedirect() of response
object
► Method signature
public void HttpServletResponse.sendRedirect
(String location)
throws IOException
► This method sends back the response to the browser
along with the status code and new page location.
You can also use setStatus() and setHeader() methods
together
►Programto Handle Page
Redirection
Database Access
► 1)Signup.html
► 2)signupdetailsentry.java
► 3)web.xml
► 4)ojdbc14.jar

You might also like