You are on page 1of 49

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.

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


1. public ServletContext getServletContext()
Example of getServletContext() method
1. //We can get the ServletContext object from ServletConfig object
2. ServletContext application=getServletConfig().getServletContext();
3.
4. //Another convenient way to get the ServletContext object
5. ServletContext application=getServletContext();
Syntax to provide the initialization parameter in Context scope
The context-param element, subelement of web-app, is used to define the initialization parameter in the application scope. The
param-name and param-value are the sub-elements of the context-param. The param-name element defines parameter name and
and param-value defines its value.

<web-app>
......

<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
......
</web-app>

Example of ServletContext to get the initialization parameter


In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter.
Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the
web.xml file, all the servlet classes will get the changed value. So we don't need to modify the servlet. So it is better to have the
common information for most of the servlets in the web.xml file by context-param element. Let's see the simple example:

DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

//creating ServletContext object


ServletContext context=getServletContext();

//Getting the value of the initialization parameter and printing it


String driverName=context.getInitParameter("dname");
pw.println("driver name is="+driverName);

pw.close();

}}
web.xml
<web-app>

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>

</web-app>

Example of ServletContext to get all the initialization parameters


In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used
the getInitParameterNames() method in the servlet class.
DemoServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();

ServletContext context=getServletContext();
Enumeration<String> e=context.getInitParameterNames();

String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br> "+context.getInitParameter(str));
}
}}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
11. </context-param>
12.
13. <servlet-mapping>
14. <servlet-name>sonoojaiswal</servlet-name>
15. <url-pattern>/context</url-pattern>
16. </servlet-mapping>
17.
18. </web-app>

Example of ServletContext to get all the initialization parameters


In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the
getInitParameterNames() method in the servlet class.

DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();

ServletContext context=getServletContext();
Enumeration<String> e=context.getInitParameterNames();

String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br> "+context.getInitParameter(str));
}
}}
web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>

<context-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>

Inter-servlet communication using Request Dispatcher


Request Dispatcher:An object of the javax.servlet.RequestDispatcher interface that allows inter-servlet communication.
Object is used to include ot forward the content of another servlet.
To get RequestDispatcher Object:

//for relative path


ServletContext.getRequestDispatcher(String resource)
//for context path
ServletRequest.getRequestDispatcher(String resource)

RequestDispatcher interface provides two methods:


public void forward(ServletRequest req,ServletResponse res)throws ServletException,java.io.IOException:
Forwards a request from a servlet to another resource on the server.
public void include(ServletRequest req,ServletResponse res)throws ServletException,java.io.IOException:
Includes the content of a resource in the response.
Examples:
RequestDispatcher rd;
rd = request.getRequestDispatcher("abc.jsp?user=ank");
rd.include(request, response);

Or

RequestDispatcher dispatcher =
req.getRequestDispatcher("/index.html");
dispatcher.forward(req, res);

Inter-servlet communication using Send Redirect


Send Redirect can be used to communicate between two servlet present in different servers, the output will be same as request dispatcher forward
example but the url of the page will be changed to redirected page
Example:

response.sendRedirect
("http://localhost:8080/Test/ServletTwo");

Inter-servlet communication example


In this example, we are validating the password entered by the user. If password is correct, it will forward the request to the HomeServlet, otherwise
will forward request to login page with an error message: Either username or password is wrong.
In this example, we have created following files:

• index.html file: for getting input from the user.


• Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet.
• HomeServlet.java file: a servlet class for displaying the Home Page.
• web.xml file: a deployment descriptor file that contains the information about the servlet.

index.html
<form action="servlet1" method="post"\>
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"><br/>
<input type="submit" value="login"/>
</form>

login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Login extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
String pass=request.getParameter("userPass");

if(pass.equals("servlet"){
RequestDispatcher dispatcher=request.getRequestDispatcher("servlet2");
dispatcher.forward(request, response);
}
else{
out.print("Either UserName or Password is Wrong!");
RequestDispatcher dispatcher=request.getRequestDispatcher("/index.html");
dispatcher.include(request, response);

}
}

HomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HomeServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String name=request.getParameter("userName");
out.print("HomePage "+name);
}

web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>HomeServlet</servlet-name>
<servlet-class>HomeServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping\>
<servlet-name>HomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Event and Listener in Servlet


1. Event and Listener in Servlet
2. Event classes
3. Event interfaces

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 classes
The event classes are as follows:

1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent

Event interfaces
The event interfaces are as follows:
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener

Servlet – Event and Listener


The term “event” refers to the occurrence of something. An event occurs when the state of an object changes. When
these exceptions occur, we can conduct certain crucial actions, such as collecting total and current logged-in users,
establishing database tables when deploying the project, building database connection objects, and so on. The
javax.servlet and javax.servlet.http packages contain numerous Event classes and Listener interfaces.
The primary function of a Listener in a GUI application is to concentrate an event from a specific GUI component,
handle it using Listener functions, and provide the response to the GUI application. The following technique is referred
to as Event Handling or Event Delegation Model in GUI applications.
Event Categories
Servlet events are divided into two categories: high-level and low-level.
1. Servlet context-level (application-level) event: This event concerns resources or states held at the
appliance servlet context object’s extent.
2. Session-level event: It involves resources or states associated with a sequence of requests from a single
user session; in other words, it is associated with the HTTP session object.
There are two types of events on each of those two levels:
1. Changes in the life cycle
2. Changes in attributes
For each of the four-event categories, we can define one or more event listener classes. Multiple event categories can
be monitored by a single listener class. Implementing an interface or interfaces from the javax.servlet package or
javax.servlet.http package is a common way to make an occasion class.
Event Listener Interfaces

istener Interface Description

Listener that will be alerted if an asynchronous action started on a ServletRequest


javax.servlet.AsyncListener to which the listener was attached has completed, timed out, or failed.

javax.servlet.ServletContextListener Interface for receiving ServletContext lifecycle change notification events.

javax.servlet.ServletContextAttributeListener Interface for receiving ServletContext attribute changes notification events.

Interface for receiving notifications about requests entering and exiting a web
javax.servlet.ServletRequestListener application’s scope.
istener Interface Description

javax.servlet.ServletRequestAttributeListener Interface for receiving ServletRequest attribute changes notification events.

javax.servlet.http.HttpSessionListener Interface for receiving HttpSession lifecycle changes notification events.

When an object is tied to or freed from a session, it is alerted by


javax.servlet.http.HttpSessionBindingListener javax.servlet.http.HttpSessionBindingListener.

javax.servlet.http.HttpSessionAttributeListener Interface for receiving HttpSession attribute change notification events.

javax.servlet.http.HttpSessionActivationListener Objects that are connected to a javax.servlet.http.HttpSessionActivationListener

Steps for Using Listeners


If we want to utilize listener listeners in our web apps, we must follow the steps below:
Step 1: Get the Listener class ready.
Take one user-defined class, which must be a Listener interface implementation class. For instance, consider the
public class Listener is implemented by MyListener{……}
Step 2: In the web.xml file, configure the Listener class.
The following XML tags must be used in the web.xml file to configure the Listener class:
<web-app>
……

<listener>
<listener-class>Name of the Listener class</listener-class>
</listener>

……

</web-app>
Except for HttpSessionBindingListener and HttpSessionActivationListener, all Listeners require the aforementioned
listener configuration.
Methods for Event Listeners and Related Classes
1) Methods for ServletContextListeners and the ServletContextEvent Class
The following methods are defined by ServletContextListener:

Methods Description

void contextInitialized(ServletContextEvent This function is used to inform the listener that the servlet context has been formed
sce) and that the application is now ready to handle requests.

void contextDestroyed(ServletContextEvent
sce) This function is used to alert the listener that the program is about to be terminated.

When a web application is deployed on the server, the ServletContextEvent is informed. It includes the technique
shown below, which your listener might call:
ServletContext getServletContext(): This method retrieves the servlet context object that was created or is going to be
deleted, from which you may get any information you want.
2) Methods for ServletContextAttributeListener and the ServletContextAttributeEvent Class
ServletContextAttributeListener specifies the following methods:
When a web application is deployed on the server, the ServletContextEvent is informed. It includes the technique
shown below, which your listener might call:
ServletContext getServletContext(): This method retrieves the servlet context object that was created or is going to be
deleted, from which you may get any information you want.
2) Methods for ServletContextAttributeListener and the ServletContextAttributeEvent Class
ServletContextAttributeListener specifies the following methods:

Methods Description

It’s used to inform the listener that the servlet context has been updated
void attributeAdded(ServletContextAttributeEvent scae): with an attribute.

void attributeRemoved(ServletContextAttributeEvent It’s used to inform the listener that an attribute from the servlet context has
scae): been deleted.

void attributeReplaced(ServletContextAttributeEvent It’s used to inform the listener when an attribute in the servlet context has
scae) been replaced.

The event class ServletContextAttributeEvent is used to notify about changes to the attributes of a web application’s
servlet context. It includes the techniques listed below, which your listener can use:
1. String getName() returns the name of the attribute that was added, deleted, or replaced as a
2. string.
3. Object getValue() is a method for retrieving the value of an attribute that has been added, deleted, or replaced.
This method returns the previous value, not the new value, in the event of a replaced attribute.
3) Methods for HttpSessionListeners and the HttpSessionEvent Class
HttpSessionListener specifies the following methods

Methods Description

void sessionCreated(HttpSessionEvent hse) It’s used to inform the listener that a session has been established.

void sessionDestroyed(HttpSessionEvent hse): It’s used to let the listener know that a session has been terminated.

When the session object is modified, HttpSessionEvent is informed. It includes the technique shown below, which your
listener might call:
HttpSession getSession(): This function is used to obtain the generated or deleted session object.
4) Methods for HttpSessionAttributeListener and the HttpSessionBindingEvent Class
HttpSessionAttributeListener specifies the following methods:
Methods Description Methods Description

It informs the It informs the


listener that a listener that a
new attribute new attribute
void has been void has been
attributeAdded(HttpSessionBindingEvent introduced to attributeAdded(HttpSessionBindingEvent introduced to
hsbe) the session. hsbe) the session.

It’s used to It’s used to


inform the inform the
listener when a listener when a
void session void session
attributeRemoved(HttpSessionBindingEvent attribute has attributeRemoved(HttpSessionBindingEvent attribute has
hsbe) been deleted. hsbe) been deleted.

It’s used to It’s used to


inform the inform the
listener when listener when
void an attribute in void an attribute in
attributeReplaced(HttpSessionBindingEvent the session has attributeReplaced(HttpSessionBindingEvent the session has
hsbe) been replaced. hsbe) been replaced.
When an object implements HttpSessionBindingListener When an object implements HttpSessionBindingListener
is bound or freed from a session, is bound or freed from a session,
HttpSessionBindingEvent is delivered to that object, or to HttpSessionBindingEvent is delivered to that object, or to
a HttpSessionAttributeListener that has been set in the a HttpSessionAttributeListener that has been set in the
deployment descriptor when any attribute is bound, deployment descriptor when any attribute is bound,
unbound, or replaced in a session. It includes the unbound, or replaced in a session. It includes the
techniques listed below, which your listener can use: techniques listed below, which your listener can use:

AppContextAttributeListener.java
• Java

package com.geeksforgeeks.listener;

import javax.servlet.ServletContextAttributeEvent;

import javax.servlet.ServletContextAttributeListener;

import javax.servlet.annotation.WebListener;
@WebListener

public class AppContextAttributeListener

implements ServletContextAttributeListener {

public void

attributeAdded(ServletContextAttributeEvent

servletContextAttributeEvent)

System.out.println(

"ServletContext attribute added::{"

+ servletContextAttributeEvent.getName() + ","

+ servletContextAttributeEvent.getValue()

+ "}");

public void
attributeReplaced(ServletContextAttributeEvent

servletContextAttributeEvent)

System.out.println(

"ServletContext attribute replaced::{"

+ servletContextAttributeEvent.getName() + ","

+ servletContextAttributeEvent.getValue()

+ "}");

public void

attributeRemoved(ServletContextAttributeEvent

servletContextAttributeEvent)

System.out.println(
"ServletContext attribute removed::{"

+ servletContextAttributeEvent.getName() + ","

+ servletContextAttributeEvent.getValue()

+ "}");

AppContextListener.java
• Java

package com.geeksforgeeks.listener;

import com.geeksforgeeks.db.*;

import javax.servlet.ServletContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import javax.servlet.annotation.WebListener;

@WebListener

public class AppContextListener

implements ServletContextListener {

public void contextInitialized(

ServletContextEvent servletContextEvent)

ServletContext ctx

= servletContextEvent.getServletContext();

String url = ctx.getInitParameter("DBURL");

String u = ctx.getInitParameter("DBUSER");
String p = ctx.getInitParameter("DBPWD");

// create database connection

// from init parameters

// and set it to context

DatabaseManager dbManager

= new DatabaseManager(url, u, p);

ctx.setAttribute("DBManager", dbManager);

System.out.println(

"Database connection initialized for Application.");

public void contextDestroyed(

ServletContextEvent servletContextEvent)

{
ServletContext ctx

= servletContextEvent.getServletContext();

DatabaseManager dbManager

= (DatabaseManager)ctx.getAttribute(

"DBManager");

dbManager.closeConnection();

System.out.println(

"Database connection closed for Application.");

MyServletRequestListener.java
• Java

package com.geeksforgeeks.listener;
import javax.servlet.ServletRequest;

import javax.servlet.ServletRequestEvent;

import javax.servlet.ServletRequestListener;

import javax.servlet.annotation.WebListener;

@WebListener

public class MyServletRequestListener

implements ServletRequestListener {

public void requestDestroyed(

ServletRequestEvent servletRequestEvent)

ServletRequest servletRequest

= servletRequestEvent.getServletRequest();
System.out.println(

"ServletRequest destroyed. Remote IP="

+ servletRequest.getRemoteAddr());

public void requestInitialized(

ServletRequestEvent servletRequestEvent)

ServletRequest servletRequest

= servletRequestEvent.getServletRequest();

System.out.println(

"ServletRequest initialized. Remote IP="

+ servletRequest.getRemoteAddr());

}
MySessionListener.java
• Java

package com.geeksforgeeks.listener;

import javax.servlet.annotation.WebListener;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

@WebListener

public class MySessionListener

implements HttpSessionListener {

public void

sessionCreated(HttpSessionEvent sessionEvent)
{

System.out.println(

"Session Created:: ID="

+ sessionEvent.getSession().getId());

public void

sessionDestroyed(HttpSessionEvent sessionEvent)

System.out.println(

"Session Destroyed:: ID="

+ sessionEvent.getSession().getId());

MyServlet.java
• Java

package com.geeksforgeeks.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
@WebServlet("/MyServlet")

public class MyServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

ServletContext ctx = request.getServletContext();

ctx.setAttribute("User", "GeeksForGeeks");

String user = (String)ctx.getAttribute("User");

ctx.removeAttribute("User");

HttpSession session = request.getSession();


session.invalidate();

PrintWriter out = response.getWriter();

out.write("Hi " + user);

Output:
When we deploy our application and access MyServlet, the server log file will include the following logs.
In the browser, we’ll see something like this.
Servlet Filter
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.

So maintenance cost will be less.

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
o 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 to any
request,HttpServletResponse response, FilterChain chain) resource, to which the filter is mapped.It is used to 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:

1. public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the control to the next filter or resource.

How to define Filter


We can define filter same as servlet. Let's see the elements of filter and filter-mapping.

<web-app>

<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
</filter>
<filter-mapping>
<filter-name>...</filter-name>
<url-pattern>...</url-pattern>
</filter-mapping>

</web-app>

For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an advantage over servlet-name element
i.e. it can be applied on servlet, JSP or HTML.

Simple Example of Filter


In this example, we are simply displaying information that filter is invoked automatically after the post processing of the request.

index.html
<a href="servlet1">click here</a>
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{


public void init(FilterConfig arg0) throws ServletException {}

public void doFilter(ServletRequest req, ServletResponse resp,


FilterChain chain) throws IOException, ServletException {

PrintWriter out=resp.getWriter();
out.print("filter is invoked before");

chain.doFilter(req, resp);//sends request to next resource

out.print("filter is invoked after");


}
public void destroy() {}
}
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
1.
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("<br>welcome to servlet<br>");

}
web.xml

For defining the filter, filter element of web-app must be defined just like servlet.

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>

</web-app>

You might also like