Professional Documents
Culture Documents
7 MR Servlet, JSP, JDBC
7 MR Servlet, JSP, JDBC
https://www.javatpoint.com/servlet-tutorial
Before Servlet, CGI (Common Gateway Interface) scripting language was common as a
server-side programming language.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
Servlet is a web component that is deployed on the server to create a dynamic web page.
Advantages of Servlet
Disadvantages of CGI
There are many problems in CGI technology:
If the number of clients increases, it takes more time for sending the response.
For each request, it starts a process, and the web server is limited to start processes.
It uses platform dependent language e.g. C, C++, perl.
Better performance: because it creates a thread for each request, not process.
Portability: because it uses Java language.
Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
Secure: because it uses java language.
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.
public void init(ServletConfig config) throws ServletException
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
public void destroy()
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
Servlet API
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Servlet
ServletRequest
ServletResponse
RequestDispatcher
ServletConfig
ServletContext
SingleThreadModel
Filter
FilterConfig
FilterChain
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)
HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent
HttpUtils (deprecated now)
mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.
DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}}
deployment descriptor is an xml file, from which Web Container gets the information about
the servet to be invoked.
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Servlets - Annotations
https://www.tutorialspoint.com/servlets/servlets-annotations.htm
1
@WebServlet
To declare a servlet.
2
@WebInitParam
3
@WebFilter
4
@WebListener
To declare a WebListener
5
@HandlesTypes
6
@HttpConstraint
This annotation is used within the ServletSecurity annotation to represent the security
constraints to be applied to all HTTP protocol methods for which a corresponding
HttpMethodConstraint element does NOT occur within the ServletSecurity annotation.
7
@HttpMethodConstraint
This annotation is used within the ServletSecurity annotation to represent security constraints
on specific HTTP protocol messages.
8
@MultipartConfig
Annotation that may be specified on a Servlet class, indicating that instances of the Servlet
expect requests that conform to the multipart/form-data MIME type.
9
@ServletSecurity
Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly).
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.
public void service(ServletRequest request,ServletResponse response) provides response for
the incoming request. It is invoked at each request by the web container.
public void destroy() is invoked only once and indicates that servlet is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
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.
<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>
<error-page>
<exception-type>
javax.servlet.ServletException
</exception-type >
<location>/ErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.io.IOException</exception-type >
<location>/ErrorHandler</location>
</error-page>
If you want to have a generic Error Handler for all the exceptions then you should define
following error-page instead of defining separate error-page elements for every exception −
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
allows us to isolate the application/business layer from the persistence layer (usually a
relational database but could be any other persistence mechanism) using an abstract API.
The API hides from the application all the complexity of performing CRUD operations in the
underlying storage mechanism
This permits both layers to evolve separately without knowing anything about each other.
a simple DAO class that will take care of keeping these components neatly decoupled from
each other.
define a basic DAO layer so we can see how it can keep the domain model completely
decoupled from the persistence layer
List<T> getAll();
Dao interface defines an abstract API that performs CRUD operations on objects of type T.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
HTTP is stateless that means each request is considered as the new request.
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
Non-persistent cookie
Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies.
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot be changed after
creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value)
create Cookie
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
SecondServlet.java
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
4) HttpSession interface
bind objects
view and manipulate information about a session, such as the session identifier, creation time,
and last accessed time.
public HttpSession getSession():Returns the current session associated with this request, or if
the request does not have a session, creates one.
HttpSession session=request.getSession();
session.setAttribute("uname",n);
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
SecondServlet.java
To set the attribute in the session scope, we have used the setAttribute() method of
HttpSession interface and to get the attribute, we have used the getAttribute method.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below −
RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp.
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
//servlet2 is the url-pattern of the second servlet
rd.forward(request, response);//method may be include or forward
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
response.sendRedirect("http://www.google.com");
The JSP pages are easier to maintain than Servlet because we can separate designing and
development.
JSP can be easily managed because we can easily separate our business logic with
presentation logic.
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.
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
After that, Servlet page is compiled by the compiler and gets converted into the class file.
Moreover, all the processes that happen in Servlet are performed on JSP later like
initialization, committing response to the browser and destroy.
MVC Architecture in Java with JSP Application Design Example
https://www.guru99.com/jsp-mvc.html
Model Layer
This is the data layer which consists of the business logic of the system.
It consists of all the data of the application
It also represents the state of the application.
It consists of classes which have the connection to the database.
The controller connects with model and fetches the data and sends to the view layer.
The model connects with the database as well and stores the data into a database which is
connected to it.
View Layer
This is a presentation layer.
It consists of HTML, JSP, etc. into it.
It normally presents the UI of the application.
It is used to display the data which is fetched from the controller which in turn fetching data
from model layer classes.
This view layer shows the data on UI of the application.
Controller Layer
It acts as an interface between View and Model.
It intercepts all the requests which are coming from the view layer.
It receives the requests from the view layer and processes the requests and does the necessary
validation for the request.
This requests is further sent to model layer for data processing, and once the request is
processed, it sends back to the controller with required information and displayed accordingly
by the view.
JDBC is a Java API to connect and execute the query with the database.