0% found this document useful (0 votes)
15 views

C# lectures

Contains C lectures

Uploaded by

Harsh Nara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

C# lectures

Contains C lectures

Uploaded by

Harsh Nara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Lecture-1

on
Advanced
JAVA
UNIT-1

PREPARED BY
URVASHI SANGWAN
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING, VCE,ROHTAK
UNIT 1
Servlet: Servlet introduction, web terminology,
servlet API, servlet Interface, generic servlet,
Http servlet, servlet lifecycle, servlet with IDE
(eclipse, My eclipse, Net beans),servlet request,
servlet collaboration, servlet configuration,
context, attribute in servlet, session technique in
servlet, event and listener, servlet filter, CRUD,
pagination, input output stream, annotation,
single thread model, SSI;
◉ A servlet is a Java programming language class that is
used to extend the capabilities of servers that host
applications accessed by means of a request-response
programming model. Although servlets can respond to
any type of request, they are commonly used to
extend the applications hosted by web servers.
Servlet can be described as follows:

◉ Servlet is a technology which is used to create a web


application.
◉ It is an API that provides many interfaces and classes
including documentation.
◉ Servlet is an interface that must be implemented for
creating any Servlet.
◉ It is also a class that extends the capabilities of the
servers and responds to the incoming requests. It can
respond to any requests.
◉ Java Servlets are:
◉ Technology for generating dynamic Web
pages (like PHP, ASP, ASP.NET, ...)
◉ Protocol and platform-independent server
side components, written in Java, which
extend the standard Web servers.
◉ Java programs that serve HTTP requests
◉ Portability: Write once, serve everywhere
◉ Power: Can take advantage of all Java APIs
◉ Elegance: Simplicity due to abstraction
◉ Efficiency & Endurance: Highly scalable
◉ Safety & Robust: Strong type-checking
Memory management
◉ Integration: Servlets tightly coupled with server
◉ Extensibility & Flexibility:
Servlets designed to be easily extensible, though
currently optimized for HTTP uses.

Flexible invocation of servlet (SSI, servlet-chaining,


filters, etc.)
Servlet Terminology Description

Website: static vs It is a collection of related web pages that may contain text,
dynamic images, audio and video.

HTTP It is the data communication protocol used to establish


communication between client and server.

HTTP Requests It is the request send by the computer to a web server that contains
all sorts 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
server side.

Server: Web vs It is used to manage the network resources and for running the
Application program or software that provides services.

Content Type It is HTTP header that provides the description about what are you
sending to the browser.
◉ The javax.servlet and javax.servlet.http packages represent
interfaces and classes for 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.
◉ Interfaces in javax.servlet package
1) Servlet
2) ServletRequest 8) Filter
3) ServletResponse 9) FilterConfig
10) FilterChain
4) RequestDispatcher 11) ServletRequestListener
5) ServletConfig 12)ServletRequestAttributeListener
13) ServletContextListener
6) ServletContext
14) ServletContextAttributeListener
7) SingleThreadModel
◉ Servlet interface provides common behavior to
all the servlets. Servlet interface defines
methods that all servlets must implement.
◉ Servlet interface needs to be implemented for
creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that
are used to initialize the servlet, to service the
requests, and to destroy the servlet and 2 non-
life cycle methods.
Methods of Servlet interface
Method Description

public void initializes the servlet. It is the life cycle method of servlet and
init(ServletConfig config) invoked by the web container only once.

public void provides response for the incoming request. It is invoked at


service(ServletRequest each request by the web container.
request,ServletResponse
response)

public void destroy() is invoked only once and indicates that servlet is being
destroyed.

public ServletConfig returns the object of ServletConfig.


getServletConfig()

public String returns information about servlet such as writer, copyright,


getServletInfo() version etc.
◉ GenericServlet class implements Servlet, ServletConfig
and Serializable interfaces. It provides the implementation
of all the methods of these interfaces except the service
method.
◉ GenericServlet class can handle any type of request so it is
protocol-independent.

Methods of GenericServlet class


There are many methods in GenericServlet class. They are as
follows:

1) public void init(ServletConfig config) is used to initialize


the servlet.
2) public abstract void service(ServletRequest request,
ServletResponse response) provides service for the
incoming request. It is invoked at each time when user
requests for a servlet.
3) public void destroy() is invoked only once throughout the life
cycle and indicates that servlet is being destroyed.
4) public ServletConfig getServletConfig() returns the object of
ServletConfig.
5) public String getServletInfo() returns information about servlet
such as writer, copyright, version etc.
6) public void init() it is a convenient method for the servlet
programmers, now there is no need to call super.init(config)
7) public ServletContext getServletContext() returns the object
of ServletContext.
8) public String getInitParameter(String name) returns the
parameter value for the given parameter name.
9) public Enumeration getInitParameterNames() returns all the
parameters defined in the web.xml file.
◉ The HttpServlet class extends the GenericServlet class and
implements Serializable interface. It provides http specific
methods such as doGet, doPost, doHead, doTrace etc.

There are many methods in HttpServlet class. They are as follows:

1) public void service(ServletRequest req,ServletResponse


res) dispatches the request to the protected service method by
converting the request and response object into http type.
2) protected void service(HttpServletRequest req,
HttpServletResponse res) receives the request from the service
method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3) protected void doGet(HttpServletRequest req,
HttpServletResponse res) handles the GET request. It is invoked
by the web container.
4) protected void doPost(HttpServletRequest req,
HttpServletResponse res) handles the POST request. It is invoked
by the web container.
5) protected void doHead(HttpServletRequest req,
HttpServletResponse res) handles the HEAD request. It is invoked
by the web container.

6) protected void doOptions(HttpServletRequest req,


HttpServletResponse res) handles the OPTIONS request. It is
invoked by the web container.

7) protected void doPut(HttpServletRequest req,


HttpServletResponse res) handles the PUT request. It is invoked by
the web container.

8) protected void doTrace(HttpServletRequest req,


HttpServletResponse res) handles the TRACE request. It is invoked
by the web container.

9) protected void doDelete(HttpServletRequest req,


HttpServletResponse res) handles the DELETE request. It is invoked
by the web container.
10) protected long getLastModified(HttpServletRequest
req) returns the time when HttpServletRequest was last modified
since midnight January 1, 1970 GMT.
There are given 6 steps to create a servlet example.
These steps are required for all the servers.
The servlet example can be created by three ways:
◉ By implementing Servlet interface,
◉ By inheriting GenericServlet class, (or)
◉ By inheriting HttpServlet class
The mostly used approach is by extending
HttpServlet because it provides http request
specific method such as doGet(), doPost(),
doHead() etc.
The entire life cycle of a Servlet is managed by
the Servlet container which uses
the javax.servlet.Servlet interface to understand
the Servlet object and manage it.
Stages of the Servlet Life Cycle: The Servlet life
cycle mainly goes through four stages,
1. Loading a Servlet.
2. Initializing the Servlet.
3. Request handling
4. Destroying the Servlet.
1. Loading a Servlet: The first stage of the Servlet life
cycle involves loading and initializing the Servlet by
the Servlet container. The Web container or Servlet
Container can load the Servlet at either of the
following two stages :
▪ Initializing the context, on configuring the Servlet
with a zero or positive integer value.
▪ If the Servlet is not preceding the stage, it may delay
the loading process until the Web container
determines that this Servlet is needed to service a
request.
2. Initializing a Servlet: After the Servlet is instantiated
successfully, the Servlet container initializes the
instantiated Servlet object. The container initializes
the Servlet object by invoking
the init(ServletConfig) method which accepts
ServletConfig object reference as a parameter.
3. Handling request: After initialization, the Servlet instance is
ready to serve the client requests. The Servlet container performs
the following operations when the Servlet instance is located to
service a request :
It creates the ServletRequest and ServletResponse objects. In
this case, if this is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects
which are subtypes of
the ServletRequest and ServletResponse objects respectively.
After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by
passing the request and response objects.

The service() method while processing the request may throw


the ServletException or UnavailableException or IOException.
4. Destroying a Servlet: When a Servlet container decides to
destroy the Servlet, it performs the following operations,
It allows all the threads currently running in the service
method of the Servlet instance to complete their jobs and get
released.
After currently running threads have completed their jobs, the
Servlet container calls the destroy() method on the Servlet
instance.

After the destroy() method is executed, the Servlet container


releases all the references of this Servlet instance so that it
becomes eligible for garbage collection.
◉ Eclipse is an open-source ide for developing JavaSE
and JavaEE (J2EE) applications. You can download the
eclipse ide from the eclipse
website http://www.eclipse.org/downloads/.
◉ You need to download the eclipse ide for JavaEE
developers.
◉ Creating servlet example in eclipse ide, saves a lot of
work to be done. It is easy and simple to create a
servlet example. Let's see the steps

1. Create a Dynamic web project


2. create a servlet
3. add servlet-api.jar file
4. Run the servlet
1) Create the dynamic web project:
For creating a dynamic web project click on File Menu -> New -> Project..-
> Web -> dynamic web project -> write your project name e.g. first ->
Finish.

2) Create the servlet in eclipse IDE:


For creating a servlet, explore the project by clicking the + icon ->
explore the Java Resources -> right click on src -> New -> servlet -> write
your servlet name e.g. Hello -> uncheck all the checkboxes except
doGet() -> next -> Finish.

3) add jar file in eclipse IDE:


For adding a jar file, right click on your project -> Build Path -> Configure
Build Path -> click on Libraries tab in Java Build Path -> click on Add
External JARs button -> select the servlet-api.jar file under tomcat/lib ->
ok.

4) Start the server and deploy the project:


For starting the server and deploying the project in one step, Right click on
your project -> Run As -> Run on Server -> choose tomcat server -> next -
> addAll -> finish.
You need to follow the following steps to create the
servlet in the myeclipse IDE. The steps are as
follows:
1. Create a web project
2. create a html file
3. create a servlet
4. start myeclipse tomcat server and deploy project
◉ 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.
◉ Methods of ServletRequest interface
◉ There are many methods defined in the
ServletRequest interface. Some of them are
as follows:
Method Description
public String getParameter(String is used to obtain the value of a parameter by
name) name.
public String[] returns an array of String containing all values of
getParameterValues(String name) given parameter name. It is mainly used to obtain
values of a Multi select list box.
java.util.Enumeration returns an enumeration of all of the request
getParameterNames() parameter names.
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 String getContentType() Returns the Internet Media Type of the request
entity data, or null if not known.

public ServletInputStream Returns an input stream for reading binary data in


getInputStream() throws IOException the request body.

public abstract String getServerName() Returns the host name of the server that received
the request.
public int getServerPort() Returns the port number on which this request was
received.
Example of ServletRequest to display the name of the user

DemoServ.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
index.html public void doGet(HttpServletRequest req,Htt
pServletResponse res)
<form action="welcome" method="ge throws ServletException,IOException
t"> {
Enter your name<input type="text" n res.setContentType("text/html");
ame="name"><br> PrintWriter pw=res.getWriter();
<input type="submit" value="login">
</form> String name=req.getParameter("name");
//will return value
pw.println("Welcome "+name);

pw.close();
}}
◉ RequestDispatcher in Servlet:
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.
Methods of RequestDispatcher interface
◉ public void forward(ServletRequest
request,ServletResponse response)throws
:F
ServletException,java.io.IOException: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)throws ServletException,java.io.IOException:Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.

SendRedirect in servlet:
The sendRedirect() method of HttpServletResponse interface can be used
to redirect response to another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make
another request. So, it can work inside and outside the server
Difference between forward() and sendRedirect() method
There are many differences between the forward() method of
RequestDispatcher and sendRedirect() method of HttpServletResponse
interface. They are given below:
forward() method sendRedirect() method

The forward() method works at server The sendRedirect() method works at


side. client side.
It sends the same request and response It always sends a new request.
objects to another servlet.
It can work within the server only. It can be used within and outside the
server.
Example: Example:
request.getRequestDispacher("servlet2"). response.sendRedirect("servlet2");
forward(request,response);

Syntax of sendRedirect() method:

public void sendRedirect(String URL)throws IOException;

Example of sendRedirect() method:

response.sendRedirect("http://www.javatpoint.com");
◉ 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.
◉ 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.
Methods of ServletConfig interface
1. public String getInitParameter(String
name):Returns the parameter value for the
specified parameter name.
2. public Enumeration
getInitParameterNames():Returns an
enumeration of all the initialization parameter
names.
3. public String getServletName():Returns the
name of the servlet.
4. public ServletContext
getServletContext():Returns an object of
ServletContext.
◉ How to get the object of ServletConfig
getServletConfig() method of Servlet interface
returns the object of ServletConfig.
◉ Syntax of getServletConfig() method
public ServletConfig getServletConfig();
◉ Example of getServletConfig() method
ServletConfig config=getServletConfig();
//Now we can call the methods of ServletConfig inte
rface
Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization


parameter for a servlet.
<web-app>
<servlet>
......

<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>
◉ 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 servlet, 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.
Usage of ServletContext Interface:

There can be a lot of usage of ServletContext object. Some of them are as


follows:
1. The object of ServletContext provides an interface between the
container and servlet.
2. The ServletContext object can be used to get configuration information
from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute
from the web.xml file.
4. The ServletContext object can be used to provide inter-application
communication.
Commonly used methods of ServletContext interface
There is given some commonly used methods of ServletContext
interface.
1. public String getInitParameter(String name):Returns the
parameter value for the specified parameter name.

2. public Enumeration getInitParameterNames():Returns the names


of the context's initialization parameters.

3. public void setAttribute(String name,Object object):sets the


given object in the application scope.

4. public Object getAttribute(String name):Returns the attribute for


the specified name.

5. public Enumeration getInitParameterNames():Returns the names


of the context's initialization parameters as an Enumeration of String
objects.

6. public void removeAttribute(String name):Removes the attribute


with the given name from the servlet context.
How to get the object of ServletContext interface

1. getServletContext() method of ServletConfig interface returns the object


of ServletContext.
2. getServletContext() method of GenericServlet class returns the object of
ServletContext.

Syntax of getServletContext() method

public ServletContext getServletContext()

Example of getServletContext() method

//We can get the ServletContext object from ServletConfig object

ServletContext application=getServletConfig().getServletContext();

//Another convenient way to get the ServletContext object


ServletContext application=getServletContext();
◉ An attribute in servlet is an object that is used to
share information in a web app and among
themselves also. Attribute can be set, get or
removed from one of the following scopes:

◉ request scope
◉ session scope
◉ 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.
Attribute specific methods of ServletRequest,
HttpSession and ServletContext interface:

There are following 4 attribute specific methods. They


are as follows:

1. public void setAttribute(String name,Object


object):sets the given object in the application scope.
2. public Object getAttribute(String name):Returns the
attribute for the specified name.
3. public Enumeration
getInitParameterNames():Returns the names of the
context's initialization parameters as an Enumeration of
String objects.
4. public void removeAttribute(String name):Removes
the attribute with the given name from the servlet
context.
◉ Session simply means a particular interval of time.
◉ Session Tracking is a way to maintain state (data)
of an user. It is also known as session
management in servlet.
◉ Http protocol is a stateless so we need to maintain
state using session tracking techniques. Each time
user requests to the server, server treats the
request as the new request. So we need to
maintain the state of an user to recognize to
particular user.

◉ HTTP is stateless that means each request is


considered as the new request. It is shown in the
figure given below:
Session Tracking used to recognize the particular user.

Session Tracking Techniques:


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

1. Cookies in Servlet :

A cookie is a small piece of information that is persisted between the


multiple client requests.
A cookie has a name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version
number.
How Cookie works:

By default, each request is considered as a new request. In cookies


technique, we add cookie with response from the servlet. So cookie is stored
in the cache of the browser. After that if request is sent by the user, cookie
is added with request by default. Thus, we recognize the user as the old
user.

Types of Cookie:

There are 2 types of cookies in servlets.


1. Non-persistent cookie: It is valid for single session only. It is removed
each time when user closes the browser.
2. 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.
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.

Cookie class:
javax.servlet.http.Cookie class provides the functionality of using cookies. It
provides a lot of useful methods for cookies.
Constructor Description

Cookie() constructs a cookie.


Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class


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) changes the value of the cookie.


2. Hidden Form Field:
In case of Hidden Form Field a hidden (invisible) textfield is used for
maintaining the state of an user.
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.

Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal Jaiswal">


Here, uname is the hidden field name and Vimal Jaiswal is the hidden field
value.

Real application of hidden form field

It is widely used in comment form of a website. In such case, we store page


id or page name in the hidden field so that each page can be uniquely
identified.
Advantage of Hidden Form Field
1. It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.
In this example, we are storing the name of the user in a hidden textfield
and getting that value from another servlet.

3. URL Rewriting:
In 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&??
A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use
getParameter() method to obtain a parameter value.
Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser


independent).
2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information.
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:
bind objects
view and manipulate information about a session, such as
the session identifier, creation time, and last accessed
time.
How to get the HttpSession object ?
The HttpServletRequest interface provides two methods to get the
object of HttpSession:
public HttpSession getSession():Returns the current session
associated with this request, or if the request does not have a
session, creates one.
public 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.

Commonly used methods of HttpSession interface

public String getId():Returns a string containing the unique


identifier value.
public long getCreationTime():Returns the time when this session
was created, measured in milliseconds since midnight January 1,
1970 GMT.
public long getLastAccessedTime():Returns the last time the client
sent a request associated with this session, as the number of
milliseconds since midnight January 1, 1970 GMT.
public void invalidate():Invalidates this session then unbinds any
objects bound to it.
◉ Events are basically occurrence of something.
Changing the state of an object is known as an event.
◉ We can perform some important tasks at the
occurrence of these exceptions, such as counting
total and current logged-in users, creating tables of
the database at time of deploying the project,
creating database connection object etc.
◉ There are many Event classes and Listener interfaces
in the javax.servlet and javax.servlet.http packages.
Event interfaces
Event classes
The event interfaces are as follows:
The event classes are as follows:
1. ServletRequestListener
2. ServletRequestAttributeListener
1. ServletRequestEvent
3. ServletContextListener
2. ServletContextEvent
4. ServletContextAttributeListener
3. ServletRequestAttributeEvent
5. HttpSessionListener
4. ServletContextAttributeEvent
6. HttpSessionAttributeListener
5. HttpSessionEvent
7. HttpSessionBindingListener
6. HttpSessionBindingEvent
8. HttpSessionActivationListener
◉ A filter is an object that is invoked at the preprocessing and
postprocessing of a request.
◉ It is mainly used to perform filtering tasks such as conversion,
logging, compression, encryption and decryption, input
validation etc.
◉ 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.
◉ Note: Unlike Servlet, One filter doesn't have dependency on
another filter.
Usage of Filter
1. recording all incoming requests
2. logs the IP addresses of the computers from which the requests originate
3. conversion
4. data compression
5. encryption and decryption
6. input validation etc.

Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance

Filter API
Like servlet filter have its own API. The javax.servlet package contains the
three interfaces of Filter API.
1. Filter
2. FilterChain
3. FilterConfig

1) Filter interface
For creating any filter, you must implement the Filter interface. Filter
interface provides the life cycle methods for a filter.
Method Description
public void init(FilterConfig config) init() method is invoked only once. It is used to initialize
the filter.
public void doFilter(HttpServletRequest doFilter() method is invoked every time when user request
request,HttpServletResponse response, FilterChain to any resource, to which the filter is mapped.It is used to
chain) perform filtering tasks.

public void destroy() This is invoked only once when filter is taken out of the
service.

2) FilterChain interface

The object of FilterChain is responsible to invoke the next filter or


resource in the chain.This object is passed in the doFilter method of Filter
interface.The FilterChain interface contains only one method:

public void doFilter(HttpServletRequest request, HttpServletResponse


response): it passes the control to the next filter or resource.
◉ 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.
◉ Servlet CRUD example
Create "user905" table in Oracle Database with auto
incrementing id using sequence. There are 5 fields
in it: id, name, password, email and country.
◉ 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.
◉ In this servlet pagination example, we are using
MySQL database to fetch records.
◉ 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.
The getInputStream() method
of ServletRequest interface returns the instance
of ServletInputStream class. So can be get as:

ServletInputStream sin=request.getInputStream();
ServletOutputStream class:

ServletOutputStream class provides a stream to write binary data into the


response. It is an abstract class.
The getOutputStream() method of ServletResponse interface returns the
instance of ServletOutputStream class. It may be get as:

ServletOutputStream out=response.getOutputStream();

Methods of ServletOutputStream class

The ServletOutputStream class provides print() and println() methods that are
overloaded.
1. void print(boolean b){}
2. void print(char c){}
3. void print(int i){}
4. void print(long l){}
5. void print(float f){}
6. void print(double d){}
7. void print(String s){}
8. void println{}
9. void println(boolean b){}
10. void println(char c){}
◉ Annotation represents the metadata. If you use
annotation, deployment descriptor (web.xml file)
is not required. But you should have tomcat7 as it
will not run in the previous versions of tomcat.
@WebServlet annotation is used to map the servlet
with the specified name.
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServ
throws ServletExceptio
let;
n, IOException {
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletReq
uest;
response.setContentType("text/html
import javax.servlet.http.HttpServletRes
");
ponse;
PrintWriter out=response.getWriter(
);
@WebServlet("/Simple")
public class Simple extends HttpServlet {
out.print("<html><body>");
out.print("<h3>Hello Servlet</h3>");
private static final long serialVersionU
ID = 1L;
out.print("</body></html>");
}
protected void doGet(HttpServletReques
}
t request, HttpServletResponse response)
◉ 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.
import 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;

public class MyServlet extends HttpServlet implements SingleThreadModel


{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("welcome");
try
{
Thread.sleep(10000);}
catch(Exception e)
{ e.printStackTrace();}
out.print(" to servlet");
out.close();
}}
ANY QUERY?

You might also like