Advance Java Notes
Advance Java Notes
Advance Java Notes
Chapter 1
Servlet Introduction
Java Servlets are the Java programs that run on the Java-enabled web
server or application server. They are used to handle the request
obtained from the web server, process the request, produce the
response, and then send a response back to the web server.
Web Terminology
Servlet Terminology Description
Website: static vs It is a collection of related web pages that may contain text, image
dynamic and video.
HTTP Requests It is the request send by the computer to a web server that contains
of potentially interesting information.
Get vs Post It gives the difference between GET and POST request.
Container It is used in java for dynamically generating the web pages on the serv
Server: Web vs It is used to manage the network resources and for running the prog
Application software that provides services.
Content Type It is HTTP header that provides the description about what are you sen
the browser.
Servlet API
Servlets are the Java programs that run on the Java-enabled web server
or application server. They are used to handle the request obtained from
the webserver, process the request, produce the response, then send a
response back to the webserver. In Java, to create web applications we
use Servlets. To create Java Servlets, we need to use Servlet API which
contains all the necessary interfaces and classes. Servlet API has 2
packages namely,
javax.servlet
javax.servlet.http
javax.servlet
javax.servlet.http
Servlet Interface :
javax.servlet.Servlet
The Servlet interface defines methods to initialize a servlet, to receive and
respond to client requests, and to destroy a servlet and its resources. These
are known as life-cycle methods, and are called by the network service in
the following manner:
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.
GenericServlet class
GenericServlet class
implements Servlet, ServletConfig and Serializable interfaces. It provides the
implementation of all the methods of these interfaces except the service
method.
You may create a generic servlet by inheriting the GenericServlet class and
providing the implementation of the service method.
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
HttpServlet class
The HttpServlet class extends the GenericServlet class and implements
Serializable interface. It provides http specific methods such as doGet, doPost,
doHead, doTrace etc.
The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.
The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.
The web container calls the service method each time when request for the
servlet is received. If servlet is not initialized, it follows the first three steps as
described above then calls the service method. If servlet is initialized, it calls
the service method. Notice that servlet is initialized only once. The syntax of
the service method of the Servlet interface is given below:
The web container calls the destroy method before removing the servlet
instance from the service. It gives the servlet an opportunity to clean up any
resource for example memory, thread etc. The syntax of the destroy method
of the Servlet interface is given below:
ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a
servlet such as content type, content length, parameter names and values, header
informations, attributes etc.
Method Description
public int getContentLength() Returns the size of the request entity data,
or -1 if not known.
public String getCharacterEncoding() Returns the character set encoding for the
input of this request.
public abstract String Returns the host name of the server that
getServerName() received the request.
index.html
<form action="welcome" method="get">
Enter your name<input type="text" name="name"><br>
<input type="submit" value="login">
</form>
DemoServ.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.close();
}}
Servelet colaboration interface
RequestDespatcher Interface
The RequestDispatcher interface provides the facility of dispatching the request
to another resource it may be html, servlet or jsp. This interface can also be used
to include the content of another resource also. It is one of the way of servlet
collaboration.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
ServletConfig Interface
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.
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.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
String driver=config.getInitParameter("driver");
out.print("Driver is: "+driver);
out.close();
}
}
ServletContext Interface
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.
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.
Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one
of the following scopes:
1. request scope
2. session scope
3. application scope
The servlet programmer can pass informations from one servlet to another
using attributes. It is just like passing object from one class to another so that
we can reuse the same object again and again.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet1 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
context.setAttribute("company","IBM");
}catch(Exception e){out.println(e);}
}}
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple
client requests.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
In such case, we store the information in the hidden field and get it from
another servlet. This approach is better if we have to submit form in all the
pages and we don't want to depend on the browser.
3)URL Rewriting
n URL rewriting, we append a token or identifier to the URL of the next Servlet
or the next resource. We can send parameter name/value pairs using the
following format:
url?name1=value1&name2=value2&??
4) HttpSession interface
In such case, container creates a session id for each user.The container uses
this id to identify the particular user.An object of HttpSession can be used to
perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
Event and Listener in Servlet
Events are basically occurrence of something. Changing the state of an object
is known as an event.
Event classes
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
Event interfaces
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing
of a request.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
PrintWriter out=resp.getWriter();
out.print("filter is invoked before");
Usage of Filter
o recording all incoming requests
o logs the IP addresses of the computers from which the requests
originate
o conversion
o data compression
o encryption and decryption
Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance
CRUD in Servlet
A CRUD (Create, Read, Update and Delete) application is the most important
application for any project development. In Servlet, we can easily create CRUD
application.
CRUD means Create, Read, Update and Delete. These are the basic
important operations carried out on the Database and in applications. We
will build a simple User registration application using a Servlet, MYSQL,
and JDBC for demonstration. In this example, we will be able to create
users, read users, update users and delete users.
Technology tools:
MySQL(workbench) Database
IDE(Intellij)
Apache Tomcat(I used the Tomcat 9 version)
Pagination in Servlet
To divide large number of records into multiple parts, we use pagination. It
allows user to display a part of records only. Loading all records in a single
page may take time, so it is always recommended to created pagination. In
servlet, we can develop pagination example easily.
Here, we have created "emp" table in "test" database. The emp table has three
fields: id, name and salary. Either create table and insert records manually or
import our sql file.
ServletInputStream class
ServletInputStream class provides stream to read binary data such as image
etc. from the request object. It is an abstract class.
ServletInputStream sin=request.getInputStream();
1. int readLine(byte[] b, int off, int len) it reads the input stream.
ServletOutputStream class
ServletOutputStream class provides a stream to write binary data into the
response. It is an abstract class.
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Simple")
public class Simple extends HttpServlet {
private static final long serialVersionUID = 1L;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<html><body>");
out.print("<h3>Hello Servlet</h3>");
out.print("</body></html>");
}
}
SingleThreadModel interface
The servlet programmer should implement SingleThreadModel interface to
ensure that servlet can handle only one request at a time. It is a marker
interface, means have no methods.
This interface is currently deprecated since Servlet API 2.4 because it doesn't
solves all the thread-safety issues such as static variable and session attributes
can be accessed by multiple threads at the same time even if we have
implemented the SingleThreadModel interface. So it is recommended to use
other means to resolve these thread safety issues such as synchronized block
etc.
port java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
out.print("welcome");
try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}
out.print(" to servlet");
out.close();
}
}
JSP
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to Servlet because it provides more
functionality than servlet such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development.
Advantages of JSP
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the
features of the Servlet in JSP.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic
with presentation logic. In Servlet technology, we mix our business logic with
the presentation logic.
If JSP page is modified, we don't need to recompile and redeploy the project.
The Servlet code needs to be updated and recompiled if we have to change
the look and feel of the application.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.
JSP API
JSP API is a set of classes and interfaces that can be used to make a
JSP page. These classes and interfaces are contained in the javax
servlet.jsp packages.
1. javax.servlet.jsp
javax.servlet.jsp package
The javax.servlet.jsp package has two interfaces and classes.The two interfaces
are as follows:
1. JspPage
2. HttpJspPage
o JspWriter
o PageContext
o JspFactory
o JspEngineInfo
o JspException
o JspError
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
JSP Declaration Tag
The code written inside the jsp declaration tag is placed outside the service()
method of auto generated servlet.
The available implicit objects are out, request, config, session, application etc.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
out :
For writing any data to the buffer, JSP provides an implicit object named out.
It is the object of JspWriter. In case of servlet you need to write:
PrintWriter out=response.getWriter();
Request:
he JSP request is an implicit object of type HttpServletRequest i.e. created for
each jsp request by the web container. It can be used to get request information
such as parameter, header information, remote address, server name, server port,
content type, character encoding etc.
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
Response:
In JSP, response is an implicit object of type HttpServletResponse. The
instance of HttpServletResponse is created by the web container for each jsp
request.
It can be used to add or manipulate response such as redirect response to
another resource, send error etc.
<%
response.sendRedirect("http://www.google.com");
%>
Config:
In JSP, config is an implicit object of type ServletConfig. This object can be
used to get initialization parameter for a particular JSP page. The config object
is created by the web container for each jsp page.
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
Application:
In JSP, application is an implicit object of type ServletContext.
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
Session:
In JSP, session is an implicit object of type HttpSession.The Java developer can
use this object to set,get or remove attribute or to get session information.
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
PageContext:
In JSP, pageContext is an implicit object of type PageContext class.The
pageContext object can be used to set,get or remove attribute from one of
the following scopes:
o page
o request
o session
o application
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
Page:
In JSP, page is an implicit object of type Object class.This object is assigned to the reference
generated servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type.For example:
<% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object directly in jsp.For exampl
<% this.log("message"); %>
Exception:
In JSP, exception is an implicit object of type java.lang.Throwable class. This
object can be used to print the exception. But it can only be used in error
pages.It is better to learn it after page directive.
<%@ page isErrorPage="true" %>
<html>
<body>
</body>
</html>
o page directive
o include directive
o taglib directive
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage