Servlet Notes1
Servlet Notes1
What is Application
An application program is a computer program designed to carry out a specific task, typically to be used by end-users.
For example, Web browsers, word processors, games, and utilities are all applications. The word "application" is used
because each program has a specific application for the user.
What is Web
The World Wide Web, commonly known as the Web, is an information system enabling documents and other web
resources to be accessed over the Internet.
Documents and downloadable media are made available to the network through web servers and can be accessed by
programs such as web browsers using web applications.
What is Server
A server is a computer program or device that provides a service to another computer program and its user, also
known as the client. In a data center, the physical computer that a server program runs on is also frequently referred
to as a server. That machine might be a dedicated server or it might be used for other purposes.
Server will accept the request, process the request and give back the response to the client.
Servlet Hierarchy
A subclass of HttpServlet must override at least one method, usually one of these:
doGet , if the servlet supports HTTP GET requests. Used in the case of fetching data.
doPost , for HTTP POST requests. Used in the case of inserting data or sending data.
doPut , for HTTP PUT requests. Used in the case of doing update operations.
doDelete , for HTTP DELETE requests. Used when we want to perform delete operation.
NOTE:
If need to perform any database related operations ie., whenever we want to connect to database using hibernate, we
have to create persistence.xml.
but in this case i.e., in servlet there will be no src/main/resources which we were using earlier.
So now persistence.xml should be created in src->java->webapp->WEB-INF->classes->META-INF->Persistence.xml
PrintWriter
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods
found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded
byte streams.
To Get PrintWriter Object we use req.getWriter();
Request Dispatcher
The RequestDispatcher is an interface that comes under package javax.servlet. Using this interface, we get an object
in servlet after receiving the request. Using the RequestDispatcher object we send a request to other resources which
include (servlet, HTML file, or JSP file). A RequestDispatcher object can be used to forward a request to the resource
or to include the resource in a response. The resource can be dynamic or static.
The RequestDispatcher interface provides two methods. They are:
1. public void forward(ServletRequest request,ServletResponse response)
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
2. public void include(ServletRequest request,ServletResponse response)
Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
Cookies
Cookies are the mostly used technology for session tracking.
Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in
its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with
it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie: Cookie cookie = new Cookie(“userID”, “7456”);
res.addCookie(cookie);
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to
disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer
and session tracking fails.
HttpSession
In HttpSession Session Tracking Mechanism, we will create a separate HttpSession object for each and every user at
each and every request we will pick up the request parameters from the request object and we will store them in the
respective HttpSession object for the sale of future reusability.
After keeping the request parameters data in the HttpSession object we have to generate the next form at the client
browser by forwarding the request to the particular static page or by generating a dynamic form.To
get HttpSession object if we getSession() method then container will check whether any HttpSession object existedfor
the respective user or not, if any HttpSession object is existed then container will return the existed HttpSession object
reference. If no object is existed for the respective user, then container will create a new HttpSession object andreturn
its reference.
HttpSession Methods
1. public void invalidate(): To destroy the HttpSession object we will use this method.
2. public void setMaxInactiveInterval(int time): If we want to destroy the HttpSession object after a particularly
ideal time duration then we have to use this method.
3. public void setAttribute(String name, Object value): To set an attribute on to the HttpSession object we have
to use this method.
4. public Object getAttribute(String name): To get a particular attribute value from the HttpSession object we
have to use this method.
5. public void removeAttribute(String name): To remove an attribute from the HttpSession object we have to
use the following method.
Advantages of HttpSession Session Tracking
1. There are no restrictions on the size of the object, any kind of object can be stored in a session.
2. The usage of the session is not dependent on the client’s browser.
3. It is secure and transparent.
Disadvantages of HttpSession Session Tracking
1. We will create a HttpSession object for each and every user, where if we increase the number of users then
automatically the number of HttpSession objects will be created at the server machine, it will reduce the overall
performance of the web application.
2. We are able to identify user-specific HttpSession objects among multiple numbers of HttpSession objects by
carrying Session-Id value from client to server and from server to client.
Url rewriting
When a request is made, additional parameter is appended with the url. In general, added additional parameter will
be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any
special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to
keep track of the parameter as a chain link until the conversation completes and also should make sure that, the
parameter doesn’t clash with other application parameters.
JSP (Java Server Page)
Java Server Pages (JSP) is a technology for developing web pages that support dynamic content which helps
developers insert java code in HTML pages by making use of special JSP tags.
Using JSP, you can collect input from users through web page forms, present records from a database or another
source, and create web pages dynamically.
Advantages of JSP: vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have
plenty of println statements that generate the HTML.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by
using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in
which all template text is converted to println( ) statements and all JSP elements are converted to Java code that
implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the
servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP
response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally, web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were
a static page.
JSP Lifecycle
A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet
life cycle with an additional step which is required to compile a JSP into servlet.
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page
has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform
JSP-specific initialization, override the jspInit().
method: public void jspInit(){ // Initialization code... }
Typically initialization is performed only once and as with the servlet init method, you generally initialize database
connections, open files, and create lookup tables in the jspInit method.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a
browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method
in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... }
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for
that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET,
POST, DELETE etc.
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The
jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to
perform any cleanup, such as releasing database connections or closing open files. The jspDestroy() method has the
following form:
public void jspDestroy() { // Your cleanup code goes here. }
JSP Tags:
1. JSP Comments
Since JSP is built on top of HTML, we can write comments in JSP file like html comments as
<%-- This is HTML Comment --%> These comments are sent to the client and we can look it with view source
option of browsers.
We can put comments in JSP files as: This comment is suitable for developers to provide code level comments
because these are not sent in the client response.
2. JSP Scriptlets
Scriptlet tags are the easiest way to put java code in a JSP page.
A scriptlet tag starts with <% and ends with %>
Any code written inside the scriptlet tags go into the _jspService() method.
3. JSP Expression
Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this
through JSP Expressions.
JSP Expression starts with <%= and ends with %> can be written using JSP Expression as Notice that anything
between is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements
and always ends with semicolon (;) but expression doesn’t end with semicolon.
4. JSP Directives
JSP Directives are used to give special instructions to the container while JSP page is getting translated to servlet
source code. JSP directives starts with For example, in above JSP Example, I am using page directive to to instruct
container JSP translator to import the Date class.
5. JSP Declaration
JSP Declarations are used to declare member methods and variables of servlet class.
JSP Declarations starts with <%! and ends with %>.
For example we can create an int variable in JSP at class level as <%! Int a=10; %>.
JSP supports nine automatically defined variables, which are also called implicit objects.
These variables are:
1. Request:
This is the HttpServletRequest object associated with the request.
2. Response:
This is the HttpServletResponse object associated with the response to the client.
3. Out:
This is the PrintWriter object used to send output to the client.
4. session:
This is the HttpSession object associated with the request.
5. Application:
This is the ServletContext object associated with application context.
6. Config:
This is the ServletConfig object associated with the page.
7. pageContext:
This encapsulates use of server-specific features like higher performance JspWriters.
8. Page:
This is simply a synonym for this, and is used to call the methods defined by the translated servlet
class.
9. Exception:
The Exception object allows the exception data to be accessed by designated JSP.
Servlet Context
An object of ServletContext is created by the web container at time of deploying the project. This object can be used
to get configuration information from web.xml file. There is only one ServletContext object per web application.
If any information is shared to many servlets, it is better to provide it from the web.xml file using the
<context-param> element.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We
provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet.
Thus it removes maintenance problem.
Servlet Config
An object of ServletConfig is created by the web container for each servlet. This object can be used to get
configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier
to manage the web application if any specific content is modified from time to time.
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the
web.xml file