Presents your JAVA E-NEWSLETTER for June 20, 2002 ------------------------------------------- FILTER ACCESS WITH JAVA SERVLET SPECIFICATION 2.3 If you want to install a servlet with limited access but don't want to alter its source code just to keep it secure, use a servlet filter. Servlet filters, included in version 2.3 of the Java Servlet specification, allow you to intercept the request before, or modify the response after, a servlet has acted. For example, the MenuLabelFilter replaces internationalisation system labels--written out as ${propertyfile.menu.label}--with the user's Locale, if he or she is logged in, or the browser's default Locale, if the user is a guest. There are two parts to a servlet filter: the Java class itself and XML in the web.xml file. A Java class that desires to act as a servlet filter has to implement the javax.servlet.Filter interface, which consists of a self-evident pair of lifecycle methods, init(FilterConfig) and destroy( ), and the action method doFilter(ServletRequest, ServletResponse, FilterChain). The latter is designed to appear similar to a doGet or doPost. Here's an example of the IP blocking servlet filter: import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class IPMonitorFilter implements Filter { private FilterConfig config = null; public void init(FilterConfig config) throws ServletException { this.config = config; } public void destroy( ) { this.config = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if(config == null) { return; } String legalIP = this.config.getInitParameter("LegalIP"); String thisIP = request.getRemoteAddr( ); if(legalIP.equals(thisIP)) { chain.doFilter(request, response); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter( ); out.write("You are not allowed to connect " + "to this URL at the moment. "); } } } The web.xml entry that places the IPMonitorFilter over a servlet, named SecretServlet, looks like this: IPMonitorFilter com.generationjava.tips.IPMonitorFilter LegalIP 192.168.13.15 IPMonitorFilter /secret SecretServlet com.generationjava.tips.SecretServlet SecretServlet /secret In the above example, the XML that handles the filtering looks very similar to the XML that handles the servlet. With this in place, the SecretServlet can only be hit from the local address of 192.168.13.15. This is useful when allowing only an internal user to see the page or, with a different IP address, to give customers access to certain data-feeds. ----------------------------------------