The Servlet API consists of:
javax.servlet package contains :
- Interfaces
- Classes
- Exceptions
javax.servlet.http package contains :
javax.servlet package contains following interfaces ,classes and Exceptions :-
Interfaces
Classes
- GenericServlet
- ServletInputStream
- ServletOutputStream
- ServletRequestWrapper
- ServletResponseWrapper
Exceptions
- ServletException :- Defines a general exception a servlet can throw when it encounters difficulty
- UnavailableException :- Defines an exception that a servlet or filter throws to indicate that it is permanently or temporarily unavailable.
-
Defines methods that all servlets must implement.
-
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP.
-
To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
-
This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
-
The servlet is constructed, then initialized with the init method.
-
Any calls from clients to the service method are handled.
-
The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
-
extends java.lang.Object
-
implements Servlet, ServletConfig, java.io.Serializable
-
Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.
-
GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it’s more common to extend a protocol-specific subclass such as HttpServlet.
-
Defines an object to provide client request information to a servlet.
-
The servlet container creates a ServletRequest object and passes it as an argument to the servlet’s service method.
-
A ServletRequest object provides data including parameter name and values, attributes, and an input stream.
Method Summary |
java.lang.String |
getParameter(java.lang.String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. |
java.util.Enumeration |
getParameterNames() Returns an Enumeration of String objects containing the names of the parameters contained in this request. |
java.lang.String[] |
getParameterValues(java.lang.String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. |
java.lang.String |
getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent the request. |
java.lang.String |
getRemoteHost() Returns the fully qualified name of the client that sent the request. |
RequestDispatcher |
getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. |
void |
setAttribute(java.lang.String name, java.lang.Object o) Stores an attribute in this request. |
java.lang.Object |
getAttribute(java.lang.String name) Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. |
java.util.Enumeration |
getAttributeNames() Returns an Enumeration containing the names of the attributes available to this request. |
-
Defines an object to assist a servlet in sending a response to the client.
-
The servlet container creates a ServletResponse object and passes it as an argument to the servlet’s service method.
-
To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream().
-
To send character data, use the PrintWriter object returned by getWriter().
Method Summary |
ServletOutputStream |
getOutputStream() Returns a ServletOutputStream suitable for writing binary data in the response. |
java.io.PrintWriter |
getWriter() Returns a PrintWriter object that can send character text to the client. |
boolean |
isCommitted() Returns a boolean indicating if the response has been committed. |
void |
setContentType(java.lang.String type) Sets the content type of the response being sent to the client. |
-
Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a server log file.
-
There is one context per “web application” per Java Virtual Machine.
Method Summary |
void |
setAttribute(java.lang.String name, java.lang.Object object) Binds an object to a given attribute name in this servlet context. |
java.lang.Object |
getAttribute(java.lang.String name) Returns the servlet container attribute with the given name, or null if there is no attribute by that name. |
java.util.Enumeration |
getAttributeNames() Returns an Enumeration containing the attribute names available within this servlet context. |
java.lang.String |
getInitParameter(java.lang.String name) Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. |
java.util.Enumeration |
getInitParameterNames() Returns the names of the context’s initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters. |
int |
getMajorVersion() Returns the major version of the Java Servlet API that this servlet container supports. |
int |
getMinorVersion() Returns the minor version of the Servlet API that this servlet container supports. |
RequestDispatcher |
getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. |
java.lang.String |
getServerInfo() Returns the name and version of the servlet container on which the servlet is running. |
void |
log(java.lang.String msg) Writes the specified message to a servlet log file, usually an event log. |
void |
log(java.lang.String message, java.lang.Throwable throwable) Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. |
void |
removeAttribute(java.lang.String name) Removes the attribute with the given name from the servlet context. |
A servlet configuration object used by a servlet container used to pass information to a servlet during initialization.
Method Summary |
java.lang.String |
getInitParameter(java.lang.String name) Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. |
java.util.Enumeration |
getInitParameterNames() Returns the names of the servlet’s initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters. |
ServletContext |
getServletContext() Returns a reference to the ServletContext in which the caller is executing. |
java.lang.String |
getServletName() Returns the name of this servlet instance. |
-
Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.
-
The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
-
It has two methods forward and include.
Method Summary |
void |
forward(ServletRequest request,ServletResponse response) Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. |
void |
include(ServletRequest request, ServletResponse response) Includes the content of a resource (servlet, JSP page, HTML file) in the response. |
-
Ensures that servlets handle only one request at a time.
-
This interface has no methods.
-
If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet’s service method.
-
The servlet container can make this guarantee by synchronizing access to a single instance of the servlet.
-
A filter is an object than perform filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.
-
Filters perform filtering in the doFilter method.
-
Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.
-
Filters are configured in the deployment descriptor of a web application.
-
Examples that have been identified for this design are:
1) Authentication Filters
2) Logging and Auditing Filters
3) Image conversion Filters
4) Data compression Filters
5) Encryption Filters
6) Tokenizing Filters
7) Filters that trigger resource access events
8) XSL/T filters
9) Mime-type chain Filter
Method Summary |
void |
destroy() Called by the web container to indicate to a filter that it is being taken out of service. |
void |
doFilter(ServletRequest request, ServletResponse response, FilterChain chain) The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. |
void |
init(FilterConfig filterConfig) Called by the web container to indicate to a filter that it is being placed into service. |
javax.servlet.http package contains following interfaces and classes:
Interfaces
Classes
- extends GenericServlet
- implements java.io.Serializable
- Any class should be subclassed to create an HTTP servlet suitable for a Web site.
- A subclass of HttpServlet must override at least one method, usually one of these:
- doGet, if the servlet supports HTTP GET requests
- doPost, for HTTP POST requests
- doPut, for HTTP PUT requests
- doDelete, for HTTP DELETE requests
- init and destroy, to manage resources that are held for the life of the servlet
- getServletInfo, which the servlet uses to provide information about itself
- There’s almost no reason to override the service method.
- service method handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).
Method Summary |
protected void |
doDelete(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to handle a DELETE request. |
protected void |
doGet(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to handle a GET request. |
protected void |
doHead(HttpServletRequest req,HttpServletResponse resp) receives an HTTP HEAD request from the protected service method and handles the request. |
protected void |
doOptions(HttpServletRequest req,HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to handle a OPTIONS request. |
protected void |
doPost(HttpServletRequest req,HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to handle a POST request. |
protected void |
doPut(HttpServletRequest req,HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to handle a PUT request. |
protected void |
doTrace(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to handle a TRACE request. |
protected long |
getLastModified(HttpServletRequest req) Returns the time the HttpServletRequest object was last modified, in milliseconds since midnight January 1, 1970 GMT. |
protected void |
service(HttpServletRequest req,HttpServletResponse resp) Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. |
void |
service(ServletRequest req, ServletResponse res) Dispatches client requests to the protected service method. |
- extends ServletRequest
- Extends the ServletRequest interface to provide request information for HTTP servlets.
- The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet’s service methods (doGet, doPost, etc).
Method Summary |
java.lang.String |
getHeader(java.lang.String name) Returns the value of the specified request header as a String. |
java.util.Enumeration |
getHeaderNames() Returns an enumeration of all the header names this request contains. |
java.util.Enumeration |
getHeaders(java.lang.String name) Returns all the values of the specified request header as an Enumeration of String objects. |
java.lang.String |
getMethod() Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. |
java.lang.String |
getRemoteUser() Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. |
HttpSession |
getSession() Returns the current session associated with this request, or if the request does not have a session, creates one. |
HttpSession |
getSession(boolean create) Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session. |
java.lang.String |
getContextPath() Returns the portion of the request URI that indicates the context of the request. |
Cookie[] |
getCookies() Returns an array containing all of the Cookie objects the client sent with this request. |
- extends ServletResponse
- Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.
- The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet’s service methods (doGet, doPost, etc).
Method Summary |
void |
addCookie(Cookie cookie) Adds the specified cookie to the response. |
void |
addHeader(java.lang.String name, java.lang.String value) Adds a response header with the given name and value. |
boolean |
containsHeader(java.lang.String name) Returns a boolean indicating whether the named response header has already been set. |
java.lang.String |
encodeRedirectURL(java.lang.String url) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. |
java.lang.String |
encodeURL(java.lang.String url) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. |
void |
sendError(int sc) Sends an error response to the client using the specified status code and clearing the buffer. |
void |
sendError(int sc, java.lang.String msg) Sends an error response to the client using the specified status clearing the buffer. |
void |
sendRedirect(java.lang.String location) Sends a temporary redirect response to the client using the specified redirect location URL. |
void |
setHeader(java.lang.String name,java.lang.String value) Sets a response header with the given name and value. |
void |
setStatus(int sc) Sets the status code for this response. |
- Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
- 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.
- A session usually corresponds to one user, who may visit a site many times.
- The server can maintain a session in many ways such as using cookies or rewriting URLs.
- This interface allows servlets to
- View and manipulate information about a session, such as the session identifier, creation time, and last accessed time
- Bind objects to sessions, allowing user information to persist across multiple user connections
Method Summary |
void |
setAttribute(java.lang.String name, java.lang.Object value) Binds an object to this session, using the name specified. |
java.lang.Object |
getAttribute(java.lang.String name) Returns the object bound with the specified name in this session, or null if no object is bound under the name. |
java.util.Enumeration |
getAttributeNames() Returns an Enumeration of String objects containing the names of all the objects bound to this session. |
long |
getCreationTime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. |
java.lang.String |
getId() Returns a string containing the unique identifier assigned to this session. |
long |
getLastAccessedTime() Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container recieved the request. |
int |
getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. |
void |
invalidate() Invalidates this session then unbinds any objects bound to it. |
void |
removeAttribute(java.lang.String name) Removes the object bound with the specified name from this session. |
void |
setMaxInactiveInterval(int interval) Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. |
- extends java.lang.Object
- implements java.lang.Cloneable
- Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server.
- A cookie’s value can uniquely identify a client, so cookies are commonly used for session management.
- A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
One Constructor of Cookie class as below
Cookie(java.lang.String name, java.lang.String value) Constructs a cookie with a specified name and value.
Method Summary |
java.lang.String |
getName() Returns the name of the cookie. |
java.lang.String |
getValue() Returns the value of the cookie. |
void |
setComment(java.lang.String purpose) Specifies a comment that describes a cookie’s purpose. |
java.lang.String |
getComment() Returns the comment describing the purpose of this cookie, or null if the cookie has no comment. |
int |
getMaxAge() Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. |
void |
setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. |
void |
setValue(java.lang.String newValue) Assigns a new value to a cookie after the cookie is created. |
- Example of Displaying Browser Details by using Servlet
- Example of Storing Customer Transaction thru Servlet in database by getting customer information from user.
- Example of Retrieving Customer Details thru Servlet from database by getting customer Id from user.
- Example of ServletContext using setAttribute and getAttribute
- Example of <context-param> using initParameter() from ServletContext
- Example of <init-param> using initParameter() from ServletConfig
- Example of ServletEvent which will log into server log file when added or removed parameter with context
Recent Comments