public
default (no argument) constructorsjava.io.Serializable
java.io.Serializable
interface, can have arguments in their constructors, etc.
This is the very basic difference between JavaBeans and Spring beans.
BeanInfo
interface is provided that explicitly supplies this information.
N
is the name of the property and T
is its type:
public T getN()
public void setN(T arg)
N
is the name of the property and T
is its type:
public T getN(int index);
public void setN(int index, T value);
public T[] getN();
public void setN(T values[]);
T
is the type of the event:
public void addTListener(TListener eventListener)
public void addTListener(TListener eventListener) throws java.util.TooManyListenersException
public void removeTListener(TListener eventListener)
addTListener()
that does not throw an exception can be used to multicast an event, which
means that more than one listener can register for the event notification. The version that throws TooManyListenersException
unicasts the event, which means that the number of listeners can be restricted to one. In either
case, removeTListener()
is used to remove the listener.
Interface | Description |
---|---|
Servlet | Declares the life cycle methods for a Servlet |
ServletConfig | Allows Servlets to get intiialization parameters |
ServletContext | Enables servlets to log events and access information about their environment |
ServletRequest | Used to read data froma Client Request |
Servlet Response | Used to write data to a Client Response |
Class | Description |
---|---|
GenericServlet | Implements the Servlet and the ServletConfig interfaces |
ServletInputStream | Encapsulates an input stream for reading requests from a client |
ServletOutputStream | Encapsulates an output stream for writing response to a Client |
ServletException | Indicates a Servlet error occurred |
UnavailableException | Indicates a Servlet is Unavailable |
javax.servlet.GenericServlet
or an
HTTP servlet that extends javax.servlet.http.HttpServlet
.
getServletConfig
method,
which the
servlet can use to get any startup information, and the getServletInfo
method, which allows the
servlet to
return basic information about itself, such as author, version, and copyright.
Method | Description |
---|---|
void init(ServletConfig sc) throws ServletException | Called when the Servlet is initialized. Initialization parameters for the Servlet can be obtained from the sc. A ServletExce[tion should be thrown if the Servlet cannot be intiialized |
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException | Called to process a request from the Client. The request from the clint can be read from req, the response to the client can be written to res. An exception is generated if if a servlet or IO problem occurs. |
void destroy() | Called when the Servlet is unloaded from the memory |
String getServletInfo() | Returns a String describing the Servlet |
ServletConfig getServletConfig() | Returns a ServletConfig object that contains any initialization parameters |
ServletContext
object is contained within the ServletConfig
object, which
the Web server provides the servlet when the servlet is initialized.
ServletRequest
can provide additional protocol-specific data (for
example, HTTP data
is provided by HttpServletRequest
.
ServletResponse
object and passes it as an argument to the
servlet's service method.
ServletOutputStream
returned by getOutputStream()
.
To send character data, use the PrintWriter
object returned by getWriter()
. To mix
binary and text data, for example, to create a multipart response, use a ServletOutputStream
and manage the character sections manually.
HttpServlet
instead.
GenericServlet
implements the Servlet
and ServletConfig
interfaces.
.
javax.servlet.http
.
Interface | Description |
---|---|
HttpServletRequest | Extends the ServletRequest interface to enable servlets to read data from the HTTP
Request
|
HttpServletResponse | Extends the ServletResponse interface to enable servlets to write data to an HTTP
response
|
HttpSession | 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. |
Class | Description |
---|---|
Cookie | Allows state information to be stored ona Client machine |
HttpServlet | Provides methods to handle HTTP requests and responses. |
ServletRequest
interface to provide request information for HTTP servlets.
HttpServletRequest
object and passes it as an argument to
the servlet's service methods (doGet, doPost, etc).
ServletResponse
interface to provide HTTP-specific functionality in sending a
response. For example, it has methods to access HTTP headers and cookies.
HttpServletResponse
object and passes it as an argument to
the servlet's service methods (doGet, doPost, etc).
HttpSessionBindingListener
. If it does, the servlet notifies the object
that it has
been bound to or unbound from the session. Notifications are sent after the binding methods complete. For
session that are invalidated or expire, notifications are sent after the session has been invalidated or
expired.
HttpSessionActivationListener
interface are notified.
isNew
returns
true. If the client chooses not to join the session, getSession
will return a different session
on each request, and isNew
will always return true.
ServletContext
), so
information stored in one context will not be directly visible in another.
addCookie()
method of the HttpServletResponse
interface. The data for that cookie is then included in the header of the HTTP response that is sent to the
browser. The names and values of cookies are stored on the user's machine.
HttpServlet
class extends GenericServlet
. It is commonly used when
developing servlets that receive and process HTTP requests.
HttpServlet
must override at least one method, usually one of these:
doGet
, if the servlet supports HTTP GET requestsdoPost
, for HTTP POST requestsdoPut
, for HTTP PUT requestsdoDelete
, for HTTP DELETE requestsinit
and destroy
, to manage resources that are held for the life of the
servlet
getServletInfo
, which the servlet uses to provide information about itselfservice
method. service handles standard HTTP
requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed
above).
Likewise, there's almost no reason to override the doOptions
and doTrace
methods.
getSession()
method of HttpServletRequest
. An
HttpSession
object is returned. This object can store a set of bindings that associate names
with objects. The setAttribute()
,
getAttribute()
, getAttributeNames()
, and removeAttribute()
methods of
HttpSession
manage these bindings. Session state is shared by all servlets that are associated
with a client.
Web Server
: A web browser lets a user request a resource. The web server receives the request, finds the resource, and then sends it back to the user. A resource can be anything - HTML page, image, PDF File. If the requested resource is not found, the server replies with a404-Not Found
error code.
A web server can refer to either the physical machine (hardware) or the web server application
(software). Web Client
: Both the human and the browser application (Mozilla, Chrome) being used are referred to as the Web Client. A web browser can communicate with the web server. It can interpret the HTML code that is sent as a part of the server's response and render that web page. Hence a Web Client (browser) lets the user request something from the server and shows the user the result of that request.HTML
: When a server answers a request, the server usually sends some type of content for the browser to display. This content is written in HTML. Two important tags in HTML are:form
and input
HTTP
: Most of the conversations held on the web between clients and servers are held using HTTP Protocol, which allows for simple request-response type conversations. The client sends anHTTP Request
and the Server responds with a HTTP Response
.
HTTP runs on top of TCP/IP. The structure of and HTTP conversation is a simple Request/Response.
HTTP
protocol has several methods, but we mostly use GET
and
POST
methods.
GET
: Gets a resource (HTML page, image, file,..) from the server and sends
it back to the Client. You can also send some data (from the Client to the Server) with
a GET
request, but
this is not recommended. Firstly, because the number of characters that are sent via a
GET
request are limited and secondly all the data sent in a
GET
request is visible in the URL. The "?" separates the path and the
parameters. Together, the entire String is the request that is the URL that is sent with
the request.
POST
: With POST, you can request something and at the same time send form
data to the server. For eg., if the user has completed a long form, you want this data
to be stored into a database. In this case you would use a POST
method. The
data to be sent back to the server is known as the "payload" or the "message body".
<html></html>
that the client then renders as the HTML page that we finally see.
index.html
by default.
PrintWriter.println()
method. The HTML code that is to be returned to the web server is included as a String
type
argument in the println()
method. As you can hope, stuffing properly formatted HTML tags
into
the println()
is not a viable solution. For eg. you will have to manually escape every quote
character (") because Java treats them as end of string character. And HTML happens to use a ton of
quotes
to specify the attribute values and what not.
main()
method. They are under the control of another Java application
known as the Container
.
Servlet
(as opposed to, say, a plain static HTML page) the server hands the
request not to the servlet itself, but to the Container
in which the servlet is deployed.
doGet()
and doPost()
.
Communication Support
: The Container(Tomcat) provides an easy way for your Servlets to talk to your Web Server. You don't have to build a ServerSocket, listen on a port, create Streams, etc. The Container knows the protocol between the Web Server and itself, so that your Servlet does not have to worry about, say, the API between the Apache Web Server and your own web application code.Lifecycle Management:
The Container controls the life and death of you servlets. It takes control of loading the classes, instantiating and initializing the servlets, invoking the servlets methods, and making servlets instances available for garbage collection. With the Container in control, you do not have to worry about the resource management.Multithreading Support:
The Container automatically creates a new Java thread for every servlet request that it receives. When the Servlet's done running the HTTPservice()
method for that Client's request, the thread completes (dies). But you are still responsible for
Thread safety and other synchronization issues. It's just that the work involved in creating and
deleting threads is reduced.
Declarative Security:
XML Deployment Descriptors allow you to configure Security without having to hard-code it into any of your servlets or other classes.JSP Support:
Container also takes care of translating the JSP code into real Java.Step 1:
User clicks on a link that has a URL to a servlet instead of a static web pageStep 2:
The Container "sees" that the request is for a Servlet, so the container creates two objects:HttpServletRequest
and
HttpServletResponse
Step 3:
The Container finds the correct Servlet based on the URL in the request, creates or allocates a thread for that request, and calls the servlet'sservice(HttpServletRequest req, HttpServletResponse resp)
method, passing the request and
response objects as arguments .
Step 4:
Depending on the type of the request, theservice()
methods calls either the doGet()
or
doPost()
methods. For this example, we assume that the request was a HTTP GET method. So the
service()
method calls the servlet's
doGet(HttpServletRequest req, HttpServletResponse resp)
method passing the request and the
response objects as arguments.
Step 5:
ThedoGet()
method generates the dynamic page and stuffs
the page into the
response object. Remember that the Container still has a reference to the Response object.
Step 6:
The thread completes, so the thread either dies or returns to a Container-managed thread pool. The container converts the response object into an HTTP Response, sends it back to the client, and then deletes the request and the response object.Ch2Servlet
) does not have a main()
method. It only has a doGet()
method. In the below example, we are basically overriding the
doGet
method of the HttpServlet
class.
HttpServlet
is an abstract
class that to 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 requestsdoPost
, for HTTP POST requestsdoPut
, for HTTP PUT requestsdoDelete
, for HTTP DELETE requestsinit
and destroy
, to manage resources that are held for the life of the
servlet
getServletInfo
, which the servlet uses to provide information about itselfservice
method. service
handles
standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX
methods listed above). javax.servlet
and javax.servlet.http
. javax.servlet.http
package supplies interfaces that make it easy to build servlets that
support HTTP requests and responses. Two important interfaces in javax.servlet.http
are
HttpServletRequest
and HttpServletResponse
. HttpServlet
class extends GenericServlet
and is used to develop servlets
that handle HTTP requests.
classes/registration/SignUpServlet.class
Deployment Descriptor
to tell the container how to run your Servlets and JSPs.
web.xml
file in your project.
<servlet>
: maps internal name to fully-qualified class name<servlet-mapping>
: maps internal name to public URL name<servlet-class>
tag still contains only the class name and not the complete
path of the the .class file. This is because the Container has a specific place that it will look for all
Servlets for which you have specified a mapping in the DD. web.xml
file. Refer this Oracle link to see
which elements can be defined using your deployment descriptor.
Model
, a JSP
page that will be the View
, and the original Servlet, bereft of any logic or HTML, that will
form
the Controller
part of the puzzle.
-index.jsp
is the file that contains the first page that the user sees when they login into
the http://localhost:8080/BeerV2_war_exploded/
. Changing the name of index.jsp
to some other name causes the app to stop working for some reason.
- The web.xml
is the Deployment Descriptor that we looked at in the previous chapter. br
- When it's time to deploy our app, we will copy a portion of this into wherever our particular
Container wants the pieces to go.
Step 1
: The Client makes a request for the form.html pageStep 2
: The Container retrieves the form.html pageStep 3
: The Container returns the page to the browser where the user answers the question on the form and Clicks SubmitPOST
request to the server. This
request is sent to the SelectBeer.do
file (Line 20). Remember that there is no actual class
named such. It's mapped to an internal Servlet name using the Deployment Descriptors.
POST /BeerRecommender_war_exploded/SelectBeer.do
. In the HTML, the /BeerRecommender_war_exploded/
isn't part of the path in the HTML, it just says:
<form method="POST" action="SelectBeer.do">
But the browser prepends the /BeerRecommender_war_exploded/
on to the request because that's
where the client request is coming from. In other words, the SelectBeer.do
is relative to the
root of the web app /BeerRecommender_war_exploded
Step 4
: The browser sends the request data to the Container. Now the Container has to figure out which is the actual Class to which theSelectBeer.do
maps.
web.xml
file (Deployment Descriptor). The container
searches the DD and finds a <servlet-mapping>
with a <url-pattern>
that matches /SelectBeer.do
where the /
represents the context root of the web
app, and SelectBeer.do
is the logical name of the resource. <servlet-name>
for this <url-pattern>
is
'Ch3 Beer'. But that isn't the name of the actual servlet class file. To a container a servlet is something
that is named in the DD under the <servlet>
tag. The 'name' of the servlet is simply
the name used in the DD so that other parts of the DD can map to it. <servlet>
tags for something with the
<servlet-name>
'Ch3 Beer'. <servlet-class>
in the <servlet>
tag to know
which servlet class is responsible for handling this request. If the servlet has not been initialised, the
class is laoded and the servlet is initialized. service()
method).
Step 5
: The Container finds the correct Servlet and passes the request to the Servlet. This class acts as the Controller, calling the ModelBeerExpert
for the business logic, and the View
result.jsp
for the response.
Step 6
: The Servlet calls the BeerExpert class for help.Step 7
: The BeerExpert class returns an answer that the Servlet class adds to the request object.Step 8
: The Servlet forwards the request to the JSP.Step 9
: The JSP gets the answer from the request object.Step 10
: The JSP generates a page for the Container.Step 11
: The Container returns the page to the User.service()
method, passing the request and response
objects references as arguments.
In this Chapter we look at the Servlet's life in more detail.
initialized
. If the
servlet isn't initialized then it is either being initialized (by running it's constructor or the
init()
method), being destroyed (by running it's destroy()
) method, or it
simply does not exist. init
, service
, and destroy
methods
do?
init()
service()
service()
method to be invoked. This method
looks at the request, determines the HTTP method (GET, POST, etc.) and invokes the matching doGet()
or doPost()
methods respectively. Note that there are other methods in HTTP as well (HEAD, PUT,
etc) and there are corresponding doXXXXX()
methods for almost all of them. Refer the HttpServlet
class below. You should not override the service()
method. Your job is to override the doGet()
or the doPost()
methods, and let the service()
implementation from the HttpServlet
worry about calling the right one.
doPost()
/doGet()
service()
method
invokes the doGet()
or the doPost()
based on the HTTP method (GET, POST, and so on). This is where your code begins.
All the stuff that your app is supposed to be doing goes in here. Always override at least one of these methods.
Whichever ones you override tells the Container what you support. If you do not override doPost()
,
for example, then you are telling the Container that this servlet does not support the HTTP POST request.
destroy()
service()
method again on the Servlet.
ServletContext
to get information from the Container. MyServlet
class. The Container
calls MyServlet
's init()
method. But if I do not
override init
, the one from GenericServlet
runs. Then when a request comes in, the
Container starts or allocates a thread and calls the service()
method, which I do not override. So
the service
method from the HttpServlet
runs. The HttpServlet
service
method then calls my overridden doGet
or doPost
methods. So each time my
doGet
or doPost
runs, it's in a different thread.
thread-per-request vs thread-per-connection
: Per request means when an HTTP request is made, a thread is created or retrieved from a pool to serve it. One thread serves the whole request. Thread per connection would be the same thing except the thread is used for an entire connection, which could be multiple requests and could also have a lot of dead time in between requests. Servlet containers are thread per request. Source on SO.Should I spawn new threads in a JAVA EE Container
: If you're in a full Java EE container, threads may be managed for you in a way that makes it a bad idea to spawn your own. Source on SO. Also there are now Concurrency Utils that enable you to achieve this so that you do not have to do this manually. Source on SO.HttpServlet is in a different package from GenericServlet. How many servlet packages are there?
Everything related to servlets is in eitherjavax.servlet
or
javax.servlet.http
. It's easy to tell the difference because things that have to do with HTTP
are in the javax.servlet.http
package whereas the generic servlet classes and interfaces are in
javax.servlet
.
init()
method. The init()
method is
called just once during the entire life of the servlet. ServletConfig
: This controls the deploy-time values you've configured for the servlet (one per servlet). Things that your servlet might want to access that you do not want to hard code, like maybe a database name.ServletConfig
parameters won't change for as
long as this servlet is deployed and running. To change them, you will have to re-deploy the servlet. This
is also used to access ServletContext
. The parameters are configured in the Deployment
Descriptor. ServletContext
:There is only oneServletContext
per web app, NOT
one per servlet. These are used to access web app parameters that are also configured in the Deployment
Descriptor.
HttpServletRequest
methods are about HTTP things like cookies, headers, and sessions.
HttpServletRequest
interface adds the methods that relate to the HTTP protocol. Same thing with
the HttpServletResponse
as well. HttpServletRequest
). 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). 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 HttpServletResponse object and passes it as an argument to the servlet's
service methods (doGet, doPost, etc). HttpServletRequest
and HttpServletResponse
are interfaces as well.
The implementation of these interfaces is left to the vendor. All you need to know is the methods that you
can call on these objects. The actual class does not matter because you are referring to the request and the
response objects only by the interface type.
doConnect
,
so it is not a part of the HttpServlet
.
GET
and POST
that we studied earlier. The key
difference between the two was
that POST
has a body, whereas in the GET
request all of the parameters are sent in the
header. Remember that GET
is ONLY supposed to be getting things from the server. it should
not make any changes to the server. POST
on the other hand is used to send data to the server for
update.
GET
an idempotent request: making the same GET
request twice will
cause no negative consequences on the server.
POST
, on the other hand, is a non-idempotent request. The data sent to the server could be
used to update some state that cannot be reversed. Think a financial transaction that cannot be reversed.
Intuitive example in book.
Basically, you want to ensure that your app logic can handle scenario where the same request comes in more than
once by mistake.
GET
method in the doGet
method as an non-idempotent method. But you would not want to do so...
color1
. But what if we
wanted two or more parameters from the user. This is how we would do it:
color1=light
,
in
this example the parameters will be sent as color1=light&theSize=heavy
. That is - the POST
request will have both the parameters but separated by an ampersand.
theSize
associated with just a single value
(either light, medium, or heavy). However, some form inputs like checkboxes can have more than one value.
That means a single parameter like theSize
will could have more than one value depending on how
many boxes the user has checked off. userName=&userEmailId=&beer_color_user_likes=light&user-newsletter=on&user-beer-sizes=12&user-beer-sizes=14
getInputStream
and getReader
.
If one is called, then the other can't be called or something like that.
getRemotePort
:
In this case, since it is the server asking, it's the Client that is the
Remote. So getRemotePort
means the Client's remote port. In other words, the
port number on the Client from which the request was sent. Remember, if you are a servlet, remote
means the Client.
getServerPort
:
This method asks "to which port was the request originally sent"
getLocalPort
:
This method asks "on which port did the request ultimately end up".
There is a difference between the above two methods because although the requests are sent to
a single port (where the server is listening), the server turns around and finds a different
local port for each thread so that the app can handle multiple clients at the same time.
setContentType
and getWriter
. After that
you are simply doing I/O to write HTML (or something else) to the stream. But you can also use the
response to set other headers, send errors, and add cookies.
getResourceAsStream
method. Note that there is another method called getResourceAsStream
in the Class
class
as
shown here on Java docs. Both are different from each other. getResourceAsStream
causing a NPE. There
are a lot of linked questions on the page as well that should be helpful. url-pattern
. Without that, we get an error saying invalid url.
setContentType
dosetContentType
before you have called the method that gives you your
output stream (getWriter
or getOutputStream
). That will guarantee you will not run
into conflicts between the content type and the output stream.
ServletOutputStream
and
PrintWriter
:
getWriter()
or you can use the getOutputStream()
setHeader
and addHeader
methods
setHeader
:
Sets a response header with the given name and value. If the header had already
been set, the new value overwrites the previous one. The containsHeader method can be used to test for the
presence of a header before setting its value. addHeader
:
Adds an additional value to the response header. Added value being the the current given name and value.
This method allows response headers to have multiple values. addIntHeader
and setIntHeader
.
response.sendRedirect("/yourRedirectUrl")
/
character. https://www.ws.com/myApp/cool/bar.do
. The request comes in into the servlet mapped to bar.do
,
and the servlet calls sendRedirect()
with a RELATIVE URL that does NOT start with a '/':
sendRedirect("foo/stuff.html")
. The container will then build the full URL relative to the
original request URL:
https://www.ws.com/myApp/cool/foo/stuff.html
. Hence if you don't start with a '/', then the
request path is prepended to the front of foo/stuff.html
sendRequest()
DOES start with a '/' as in
sendRedirect("/foo/stuff.html")
, the container will build the complete URL relative to the WEB
CONTAINER ITSELF, instead of the original URL of the request. So the new URL will be:
https://www.ws.com/foo/stuff.html
. foo is treated as a separate webapp from the
myApp webapp in the previous case. Hence, in this case, the forward slash at the beginning means
"relative to the root of this web container". 302 Found
redirect302
is a common way of performing URL redirection. Along with the
302
status code, the response should include a Location header with a different URI. Such
header will be parsed by the user agent and then perform the redirection:
302 Found
as follows: The 302 (Found) status code indicates that the target
resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the
client ought to continue to use the effective request URI for future requests.
The server SHOULD generate a Location
header field in the response containing a URI reference
for the different URI. The user agent MAY use the Location
field value for automatic
redirection. The server's response payload usually contains a short hypertext note with a hyperlink to the
different URI(s).
Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent
request. If this behavior is undesired, the 307 (Temporary Redirect)
status code can be used
instead. WEB-INF
folder. The problem with this is that, because the files are outside the
WEB-INF
folder, we can directly access them by going to the URL directly. What I mean is, we
could directly type in
http://localhost:8080/BeerRecommender_war_exploded/beer-form.html
in the address bar, and that
would take us to the form. No need to click on anything or to go through actual links. Now this is fine for
the form, but becomes a problem when we navigate to the result.jsp
page directly by typing in
the address. It leads to 500 error because the request object is not populated yet. WEB-INF
folder is a protected resource. It will have to be
accessed by calling /WEB-INF/
from a ServletContext
. Source on
SO. ${pageContext.request.contextPath}
init-param
s in the
ServletConfig
?
<init-param>
element to specify
the name-value pairs. Note that the <init-param></init-param>
should be inside the
servlet
element that you want to initialize with the particular value.
ServletConfig
for the Servlet.
The Container reads the servlet init parameters from the DD and gives them to the ServletConfig
,
and then passes the ServletConfig
to the servlet's init
method.
ServletConfig
they won't be read again until/unless you redeploy
the servlet.
context-param
s
in ServletContext
?
getServletConfig().getInitParameter("emailId");
getServletContext().getInitParameter("adminEmailId"))
GenericServlet
class that is inherited by the HttpServlet
which in turn is inherited by your Servlet class. ServletConfig
is one per servlet, whereas ServletContext
is one per webapp.
i.e. every servlet and JSP deployed as part of a single webapp has access to that same
ServletContext
. But every servlet has it's own ServletConfig
. ServletConfig
classServletConfig
is a servlet configuration object used by a servlet container to pass information to a servlet during
initialization.
Method | Description |
---|---|
String getInitParameter(String name) | Gets the value of the initialization parameter with the given name. |
Enumeration<String> 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. Same as
running this.getServletContext |
String getServletName() | Returns the name of this servlet instance. |
ServletContext
using setAttribute
that is then passed to your web app. Any servlet/jsp can then get that
attribute from the ServletContext
object using getAttribute
. ServletContextListener
. Both
contextInitialized
and contextDestroyed
methods are overridden. I think it is
mainly being used for logging purposes, to kind of try and understand what kind of branch the code is taking
(I guess!). Nothing is being read from the ServletContextEvent
.
HttpSessionListener
interfaceServletContext
,
HttpServletRequest
(ServletRequest
), or HttpSession
request.getParameter()
to extract request parameters (i.e. data sent by posting a html
form). The request.getParameter()
always returns String value and the data comes from client.
The exception to this is ServletContext
and the ServletConfig
init-parameters
which are string parameters that are configured in web.xml and exist on the server.
ServletContext
attribute is an object bound into a context
through the ServletContext.setAttribute()
method and which is available to ALL Servlets (thus JSP) in that context, or to other contexts via the
getContext()
method. By definition a context attribute exists locally in the VM where they were
defined. So, they're unavailable on distributed applications.
HttpSessionBindingListener
interface.
RequestDispatcher
Interface (since you can't add Parameters...) and by the container. Request
attributes are very useful in web apps when you must provide setup information between information providers
and the information presentation layer (a JSP) that is bound to a specific request and need not be available
any longer, which usually happens with sessions without a rigorous control strategy.
ServletContext
,
HttpSession
, and ServletRequest
interfaces. The API methods for these attributes
are the same in every interface:
Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)
Enumeration<String> getAttributeNames(String name)
synchronized (this.getServletContext().getAttribute("UserCount"))
?
RequestDispatcher
RequestDispatcher
's have only two methods:
forward(ServletRequest request, ServletResponse response)
include(ServletRequest request, ServletResponse response)
RequestDispatcher
in two ways: from the request or from the context. Regardless
of where you get it, you ahve to tell it the web component ot which you are forwarding the request.
HttpSession
: We can use an HttpSession
to hold the
conversational state over multiple requests - i.e for the entire session with the user.
SessionID
to each user.
ServletContext
and handles a request identified as being a part of the same session.
Cookie
s to do this.
Cookie
object, stuffs
the SessionID
into the Cookie
object, sets the Cookie as a part of the response.
On subsequent
requests, the Container gets the SessionID
from the Cookie in the request, matches the SessionID
with an existing session, and associates that session with the current request.
HttpSession session = request.getSession()
does the following:
if(the request contains the SessionID object)
find the Session matching that ID
else if (there is no SessionID Cookie OR there is no session matching the current SessionID)
create a new session
HttpSession session = request.getSession()
method returns a session regardless of
whether there is a
pre-existing session or not. You can check if it is a new session by using session.isNew()
method.
HttpSession session = request.getSession(false)
will return null
if there is no
pre-existing session for the Client. You can use it if you have a scenario in which the servlet wants to use
only a previously created session.
JSESSION ID
. This is the same id as the sessionId
.
While testing, if you see your app behaving abnormally (session seems to be behaving weirdly), first clear
the cookies in your browser (Ctrl + Shift + Del) and then retry. If that does not work, go into your app and
by inspecting elements, manually delete the cookies.
doGet
method was
activated only when the user clicked a button on the index page to get the form. The point is that, line 4
of the below code will always contain a valid session.
session.invalidate
. Remember that this will
not set the session
to null
as explained
here in SO. So we get the session again, as on Line 8. This time the Container does not find any
existing sessions and the session
variable is in fact null. When we run the code, now, the
if (session == null)
block is executed.
encodeURL
method
getSession
, and the Container does not have the SessionID
associated with the Client's request, the Container knows that it must attempt to set up a new session with
the Client. At this point the Container does not know whether the Cookies will work or not. Hence for the
first response back to the Client, the Container tries both, Cookies and URL Rewriting.
HttpSession
methodsinvalidate()
on the Session objectsession.setMaxInactiveInterval(20*60)
setMaxInactiveInterval()
on every session that is created.
invalidate()
: Invalidates this session then unbinds any objects bound to it.
Like we discussed earlier, calling this method will not set the session object to null
.
JSESSION
cookie works. But you can tell a cookie to stay alive even
AFTER the browser shuts down. These types of cookies are known as Persistent Cookies.
ServletConfig
, ServletContext
,
and HttpSession
objects in this case.
HttpSession
objects (and their attributes) move from one VM to another.
ServletContext
per VM. There is one ServletConfig
per
Servlet, per VM. But there is only one HttpSession
object for a given
SessionId
per web app, regardless of how many VM's the app is distributed across.
HttpSessionActivationListener
HttpSessionAttributeListener
HttpSessionAttributeListener
service()
method.
<%@ page import = "java.util.List" %>
.
Notice that there is no semicolon at the end of the import statement.
<%@ page import = "java.util.List,java.util.Map"%>
. Note that packages are separated by
comma and the quotes go around the entire list of packages.
<% %>
: Between these tags goes the java code that you want to write in
the JSP page. <% out.println(Counter.getCount()); %>
.
<%@ %>
: used for writing import statements, among other things, in the
JSP. No semi-colon at the end.
<%= >
: it automatically prints out whatever you put between the tags.
This is meant as a replacement for out.println
in JSP. So, instead of writing, say,
<% out.println(Counter.getCount()); %>
, we would just write
<%= Counter.getCount() %>
. Note that the expression does not need a semicolon at
the end either. A n expression cannot use a method that does not have a return type, i.e has
void
as return type because then there won't be anything to print.
out
in the above example is passed implicitly to your
JSP page, just in case you want to pass it to some other object that does not have direct access to the
output stream for the response.
_jspService
method that takes as
argument the HttpServletRequest request
object. Hence you wan write your JSP assuming that it
is going to be a part of a servlet. This is also an example of "implicit" object. Something that we see in
the next paragraph.
<%! int count = 0;%>
.
<%! %>
tag is added to the class outside the service method. That means
that you can declare, both, static variables (what?) and methods.
API | Implicit Object |
---|---|
JspWriter | out |
HttpServletRequest | request |
HttpServletResponse | response |
HttpSession | session |
ServletContext | application |
ServletConfig | config |
Throwable | exception |
PageContext | pageContext |
Object | page |
pageContext
encapsulates the other implicit objects. This way if you give some other helper
object a reference to the PageContext, the helper can use that reference to get all the OTHER implicit
object
and attributes from all the scopes.
JSP Element | Usage | What is it used for | Usage Example |
---|---|---|---|
Scriptlet | <% ;%> |
Used to write Java Code | <% out.println(Counter.getCount()); %> |
Directive | <%@ %> |
Used for writing import statements | <%@ page import = "java.util.List" %> |
Expression | <%= %> |
Printing out stuff | <%= Counter.getCount() %> |
Declaration | <%! ;%> |
Declaring methods and instance variables in the JSP | <%! int count = 0;%> |
ExpressionLanguages | ${ } |
Invokes Java Code | ${applicationScope.mail} |
Actions | <jsp: /> , <c: /> |
They are 2 types: standarad and other |
|
Scope | In a Servlet | In a JSP (using implicit objects) |
---|---|---|
Application/Context | getServletContext.setAttribute("foo", barObject) |
application.setAttribute("foo", barObject) |
Request | request.setAttribute("foo", barObject) |
request.setAttribute("foo", barObject) |
Session | request.getSession().setAttribute("foo", barObject) |
session.setAttribute("foo", barObject) |
Page | Does not apply |
pageContext.setAttribute("foo", barObject) |
//Your comment
: in a scriptlet or a declaration. However, outside of this the string
"//" would just be parsed like normal HTML comment and you would see your comment printed on the
page
<!-- HTML Comment -->
: Use this if you want the comments to stay as a part of the
HTML response to the Client
<%-- JSP Comment --%>
: Comments will be hidden. They are stripped off when the JSP
is converted into Java.
<scripting-invalid> true </scripting-invalid>
to disable scripting
elements for ALL JSPs. There is a specific format for this. Refer text.
Context
can be found here on the Tomcat docs. Good read. Go
through the Host section under Containers as well. That is relevant too. http://localhost:8080/commerce/resourceName
. <Context docBase="C:/apps/commerce" reloadable="true"/>
. The only required attribute
is docBase, which specifies the location of the application. The reloadable attribute is optional, but if it is present and its value is set to true, Tomcat will monitor the
application for any addition, deletion, or update of a Java class file and other resources. When such a change is detected, Tomcat will reload the application. Setting
reloadable to true is recommended during development but not in production. When you add a context file to the specified directory, Tomcat will automatically load the
application. When you delete it, Tomcat will unload the application. http://google.com/index.html
. The first part of the URLs is http, which identifies the protocol. Not all
URLs use HTTP. For instance, these two URLs are valid even though they are not HTTP-based URLs: mailto:joe@example.com
,
ftp://marketing@ftp.example.org
. protocol://[host.]domain[:port][/context][/resource][?query string]
or
protocol://IP address[:port][/context][/resource][?query string]
. The parts in square brackets are optional. ping google.com
. For an IPv6 address, you need to
wrap it inside a square bracket as explained here. Note that you need to have IPv6 working on your OS, and every device in the
path to the destination (including proxy servers if you use one). http://localhost:8080
.
localhost
is a reserved name typically used to refer to the local computer, i.e. the same computer the web browser is running on. /
character, the browser will fetch that resource
from the top root of the server, without reference to the context given by the current document. This is the most common use case for an absolute URL within an HTML document.
The browser will use the same protocol and the same domain name as the one used to load the document hosting that URL. Look at examples here on MDN. /
. Servlet
, an interface that all servlet classes must implement either directly or indirectly. Servlet
interface defines a contract between a servlet and the servlet container. The contract boils down to the promise by the servlet container to load
the servlet class into memory and call specific methods on the servlet instance. There can only be one instance for each servlet type in an application. service
method, passing an instance of ServletRequest
and an instance of
ServletResponse
. The ServletRequest
encapsulates the current HTTP request so that servlet developers do not have to parse and manipulate raw HTTP
data. The ServletResponse
represents the HTTP response for the current user and makes it easy to send response back to the user. ServletContext
. This object encapsulates the environment details of the context
(application). There is only one ServletContext
for each context. For each servlet instance, there is also a ServletConfig
that encapsulates the
servlet configuration.
Servlet
interfaceinit
method. service
method are handled. destroy
method, then garbage collected and finalized. Servlet
interface defines the following 5 methods here on the Oracle
site: void init(ServletConfig config) throws ServletException
: The servlet container invokes this method the first time the servlet is requested. This method is not
called at subsequent requests. You use this method to write initialization code. When invoking this method, the servlet container passes a ServletConfig
.
Normally, you will assign the ServletConfig
to a class level variable so that this object can be used from other points in the servlet class. void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
: The servlet container invokes this method each time the
servlet is requested. You write the code that the servlet is supposed to do here. The first time the servlet is requested, the servlet container calls the init
method and the service
method. For subsequent requests, only service
is invoked. void destroy()
: The servlet container invokes this method when the servlet is about to be destroyed. This occurs when the application is unloaded or when the
servlet container is being shut down. Normally, you write clean-up code in this method String getServletInfo()
: This method returns the description of the servlet. You can return any string that might be useful or even null. ServletConfig getServletConfig()
: This method returns the ServletConfig passed by the servlet container to the init method. However, in order for
getServletConfig
to return a non-null value, you must have assigned the ServletConfig
passed to the init
method to a class level
variable.
classes
: Your servlet classes and other Java classes must reside here. The directories under classes reflect the class package. In Figure 1.2 there is one class deployed, app01a.MyServlet.lib
: Deploy jar files required by your servlet application here. The Servlet API jar file does not need to be deployed here because the servlet container already has a copy of it. In this application, the lib directory is empty. An empty lib directory may be deleted.servletRequest.getContextPath()
, it is the value of this "Application Context" that will be returned. @WebServlet(name = "WelcomeServlet", urlPatterns = {"/welcome"})
annotation instead of writing this
configuration in the web.xml
file. You would access this link by doing http://localhost:8080/app01a/welcome.
ServletRequest
and passes it to the servlet's service
method. The
ServletRequest
encapsulates information about the request. getParameter(String name)
is the most frequently used method in ServletRequest. A common use of this method is to return the value of an HTML form field.
getParameter
can also be used to get the value of a query string. For example, if a servlet is invoked using this URI
http://domain/context/servletName?id=123, you can retrieve the value of id from inside your servlet using this statement:
String id = request.getParameter("id");
. Note that getParameter
returns null if the parameter does not exist.
service
method, the servlet container creates a ServletResponse
and pass it as the second argument to the service
method. The ServletResponse
hides the complexity of sending response to the browser. ServletResponse
is the getWriter
method, which returns a java.io.PrintWriter
that can send text to the
client. There is also another method that you can use to send output to the browser: getOutputStream
. However, this method is for sending binary data. setContentType
method, passing "text/html" as an argument. This is
how you tell the browser that the content type is HTML. Most browsers by default render a response as HTML in the absence of a content type.
ServletConfig
to the servlet's init
method when the servlet container initializes the servlet. The
ServletConfig
encapsulates configuration information that you can pass to a servlet through @WebServlet
or the deployment descriptor. Every piece of
information so passed is called an initial parameter. An initial parameter has two components: key and value. getInitParameter
method on the ServletConfig
passed by the servlet
container to the servlet's init
method.
@WebServlet
since the deployment descriptor is a text file and you can edit it without recompiling the servlet class. The deployment
descriptor also allows you to override values specified in a servlet annotation.
ServletContext
represents the servlet application. There is only one context per web application. In a distributed environment where an application is
deployed simultaneously to multiple containers, there is one ServletContext
object per Java Virtual Machine. In this situation, the context cannot be used as a
location to share global information (because the information won't be truly global). Use an external resource like a database instead. ServletContext
is there so that you can share information that can be accessed from all resources in the application and to enable dynamic registration of
web objects. The former is done by storing objects in an internal Map
within the ServletContext
. Objects stored in ServletContext
are
called attributes.
Servlet
interface caused us to implement all the 5 methods defined on the interface even if we did not have
the need for all of them. In its place, we can extend the GenericServlet
which provides default implementations of the methods except the service
method. 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
. It also assigns the ServletConfig
in the
init
method to a class level variable so that it can be retrieved by calling getServletConfig
.
HttpServlet
class extends the GenericServlet
class. The HttpServletRequest
interface extends ServletRequest
and
HttpServletResponse
extends ServletResponse
.HttpServlet
overrides the service
method in GenericServlet
and
adds another service
method with the following signature:
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
. HttpServlet
that you do not find in GenericServlet
: service
method, you will override doGet
, doPost
, or both of them. In rare cases, you will also override any of these
methods: doHead
, doPut
, doTrace
, doOptions
, doDelete
. HttpServletRequest
and HttpServletResponse
, instead of ServletRequest
and ServletResponse
. HttpServletRequest
represents the servlet request in the HTTP environment. It extends the ServletRequest
interface and adds several methods. Some
methods added are as follows: String getContextPath()
: Returns the portion of the request URI that indicates the context of the request. Cookie[] getCookies()
: Returns an array containing all the Cookie
objects the client sent with this request. This method returns null if no
cookies were sent. String getHeader(String name)
: Returns the value of the specified request header as a String. If the request did not include a header of the specified name,
this method returns null. If there are multiple headers with the same name, this method returns the first header in the request. The header name is case-insensitive. You can
use this method with any request header. String getMethod()
: Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. String getQueryString()
: Returns the query string that is contained in the request URL after the path. This method returns null if the URL does not have a
query string. For instance, if this is the URL: http://localhost:8080/ServletsTutorial/QueryStringExample?firstName=Java&lastName=InterviewPoint, then the value
returned by this method will be firstName=Java&lastName=InterviewPoint. 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 there is no current session and
create is true, returns a new session. If create is false and the request has no valid HttpSession
, this method returns null.
ServletResponse
interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and
cookies. Here are some of the methods defined in it: void addCookie(Cookie cookie)
: Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie. void addHeader(String name, String value)
: Adds a response header with the given name and value. This method allows response headers to have multiple values.
void sendRedirect(String location)
: Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer. The
buffer will be replaced with the data set by this method. Calling this method sets the status code to SC_FOUND 302 (Found). This method can accept relative URLs; the servlet
container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container
interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root. If
the location is relative with two leading '/' the container interprets it as a network-path reference.
ServletRequest.getParameter
that takes an input
field name never returns null. <select multiple>
) sends a string array and has to be handled by ServletRequest.getParameterValues()
. ServletRequest.getParameter(fieldName)
returns null. Note that by "nothing" we
mean that there will be no parameter in the HttpServletRequest
that will correspond to the name attribute of the checkbox. Hence, doing
ServletRequest.getParameter(fieldName)
returns null.
- Radio Buttons: Radio buttons send the value of the selected button to the server. If
none of the buttons is selected, nothing is sent to the server and ServletRequest.getParameter(fieldName)
returns null. Similar to the above case, by "nothing is
sent to the server", we mean that there will be no parameter in the HttpServletRequest
that will correspond to the name attribute of the radio button.
ServletRequest.getParameterValues()
to
retrieve them. ServletRequest.getParameter()
will only return the last value.