Example: Create an IP filtering filter that, when a user makes an access request, is first judged by a filter,
If the user's IP address is restricted, access is forbidden and only legitimate IP can continue to access it. The IP Filtering filter code is as follows:
Ipfilter.java
1 PackageCOM.MHB;2 3 Importjava.io.IOException;4 ImportJava.io.PrintWriter;5 6 ImportJavax.servlet.Filter;7 ImportJavax.servlet.FilterChain;8 ImportJavax.servlet.FilterConfig;9 Importjavax.servlet.ServletException;Ten Importjavax.servlet.ServletRequest; One ImportJavax.servlet.ServletResponse; A - Public classIPFilterImplementsFilter { - the protectedfilterconfig Filterconfig; - protectedString IP; - - Public voidInit (Filterconfig filterconfig)throwsservletexception { + This. filterconfig = Filterconfig;//Set Property Filterconfig - This. IP = This. Filterconfig.getinitparameter ("IP");//set initialization parameter IP + } A //Filtration Method at Public voidDoFilter (servletrequest request, servletresponse response, -Filterchain chain)throwsIOException, servletexception { -String Remoteip = Request.getlocaladdr ();//Get the client IP address - - if(Remoteip.equals (IP)) {//determine if IP is forbidden -Response.setcharacterencoding ("gb2312");//Setting the output content encoding format inPrintWriter out =Response.getwriter (); -Out.println ("<b> Your IP address is forbidden to access!") </b> "); to}Else{ + Chain.dofilter (request, response); - } the } * //Method of Destruction $ Public voiddestroy () {Panax Notoginseng } -}
Web. XML configuration
<filter> <filter-name>IPFilter</filter-name> <filter-class> com.mhb.ipfilter</filter-class> <init-param> <param-name>ip</param-name > <param-value>127.0.0.1</param-value> </init-param> </filter> < filter-mapping> <filter-name>IPFilter</filter-name> <url-pattern>/* </url-pattern> </filter-mapping> <welcome-file-list> <welcome-file >index.jsp</welcome-file> </welcome-file-list></web-app>
Browser display:
Filter design implements IP address restrictions