1. Overview
Describes how to use filter technology to prevent direct access to the site resources through other URL addresses. Run this instance, when the URL address is not the address of the site, the error message will be displayed in the Web page.
2. Technical Highlights
The main application of the Request object's GetHeader () method to get the header source address, if it comes from other websites, the wrong image pops up. The syntax structure of the GetHeader () method is as follows:
Public String GetHeader (String headername)
Parameter description:
Headername: Specifies the name of the response header for the string type.
3. Concrete implementation
(1) Create a filter filter implementation class ImageFilter, in the Dofilter () method to verify the request, the implementation of the picture before the page, to verify that the client request from the site. The main code is as follows:
Public classImageFilterImplementsFilter { Public voidInit (filterconfig config)throwsservletexception {} Public voidDoFilter (servletrequest req, servletresponse Res, filterchain chain)throwsIOException, servletexception {httpservletrequest request= (httpservletrequest) req;//Request ObjectHttpServletResponse response = (httpservletresponse) res;//Response ObjectString Imurl = Request.getheader ("Imurl");//Source address of the link if(Imurl = =NULL|| !imurl.contains (Request.getservername ())) {//determine the source of accessRequest.getrequestdispatcher ("/errorimage.gif"). Forward (Request,//Show Error Pictureresponse); } Else{chain.dofilter (request, response); //Normal Display Picture } } Public voiddestroy () {}}
(2) Configure filter in Web. XML, which is the source of the requests from the request information header, the main code is as follows:
<filter> <filter-name>imageFilter</filter-name> <filter-class> com.mr.filter.imagefilter</filter-class></filter><filter-mapping> < filter-name>imagefilter</filter-name> <url-pattern>/images/*</url-pattern ></filter-mapping>
Servlet Filter--Imitation hotlinking filter