The filter accesses in the Java Servlet specification 2.3. (turn)

zhaozj2021-02-16  96

If you want to install a servlet with access restrictions, but at the same time, in order to ensure that its security does not want to change its source code, you should use a servlet filter.

The servlet filter is included in the Java Servlet specification version 2.3. It allows you to take a request before servlet operation, and you can make you modify the request after servlet. For example, if the user has already logged into the system, then MenulaFilter uses the user's configuration to replace the I18N system tag, write format is $ {propertyfile.Menu.label}, if the user is GUEST, use the browser default configuration.

A servlet filter can be divided into two parts: Java class itself and XML in the web.xml file. The Java class to be a servlet shark must implement a javax.servlet.filter interface. This interface is made by a pair of self-descriptive life cycles, DOFILTER (ServletRequest, ServletResonse, Filterchain). The latter design looks similar to doget or dopost.

Below is an IP-managed servlet filter example:

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 imports 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"

"THIS URL AT The Moment.");

}

}

}

WEB.XML entries on servlets on the servlet are called SecretServlet, which can be written as follows:



ipmonitorfilter

com.generationjava.tips.ipmonitorfilter


Legalip

192.168.13.15




ipmonitorfilter

/ secret



SecretServlet

com.generationjava.tips.secretServlet



SecretServlet

/ secret


In the above example, the processing filtered XML looks very similar to the XML of the process servlet. When the setting is complete, the SecretServlet will only be accessed by the local address of 192.168.13.15. This method is especially useful when only one internal user is allowed to access this page or give a different IP address to access certain datasets.

转载请注明原文地址:https://www.9cbs.com/read-11968.html

New Post(0)