Filters can be used to transform the response from a servlet or a JSP page and can perform many functions as follows
User Authentication- Blocking requests based on user identity.
Logging and auditing-Tracking users and the actions performed.
Image conversion- Scaling, sqeezing etc
Data compression-For making the download easier.
Localization-Targeting the request and response to a particular locale.
A filter is a Java class which implements the javax.servlet.Filter interface . The javax.servlet.Filter interface defines three methods as given below.
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) This method is called each time when a request/response pair is passed.
public void init(FilterConfig filterConfig) init() method is used to initialize the filter and this is invoked only once.
public void destroy() This method is called to indicate that a filter is being taken out of service
Below given example discribes the filter implemetation for user authentication
// To check if the url can be excluded or not
for (int i = 0; i < urlList.size(); i++) {
strURL = urlList.get(i).toString();
if (url.startsWith(strURL)) {
allowedRequest = true;
}
}
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (session == null
|| session.getAttribute("session_uname") == null) {
// Forward the control to login.jsp if authentication fails
request.getRequestDispatcher("/login.jsp").forward(request,
response);
}
}
chain.doFilter(req, res);
}
public void init(FilterConfig config) throws ServletException {
// Read the URLs to be avoided for authentication check (From web.xml)
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
StrUrlList = new ArrayList();
while (token.hasMoreTokens()) {
StrUrlList.add(token.nextToken());
}
}
}
Bookmarks