Web Day21 Web Filter, Application case statistics IP, solve the whole station garbled, coarse granularity permission control, page static

Source: Internet
Author: User



Javaweb three main components
1. All need to be configured in Web. xml

Servlet

Listener (2 perceptual listeners do not need to be configured)

Filter


Filter filters

It executes in front of a set of resources (JSP, servlet,. css,. html, and so on)!

It allows the request to get the target resource, or not to allow the request to reach!

* Filter has the ability to intercept requests!

Login:

Allows it to access Aservlet, Bservlet, Cservlet

-------------------------------

How filters are written

1. Write a class to implement the filter interface

2. Configuring in Web. xml

Filter interface

void Init (Filterconfig)

* Once created, execute immediately; filter will be created when the server is started!

void Destory ()

* Destroy before execution! Destroy when the server shuts down

Voiddofilter (Servletrequest,servletresponse,filterchain)

* Each filter will be executed

Filter is single-case!


Web. XML deployment

<filter>

<filter-name>xxx</filter-name>

<filter-class>cn.itcast.web.filter.AFitler</fitler-class>

</filter>

<fitler-mapping>

<filter-name>xxx</filter-name>

<url-pattern>/*</url-pattern>

<!--In addition to the Url-pattern servlet.

</filter-mapping>

-------------------------------

Filterconfig--> is similar to ServletConfig

* Get initialization parameters: Getinitparameter ()

* Get Filter Name: Getfiltername ()

* Get Appliction:getservletcontext ()


Filterchain

*dofilter (ServletRequest, servletresponse): Release!

Release is equivalent to invoking the service () method of the target servlet!

-------------------------------

-------------------------------

Multi-Filter

Filterchain#dofilter () Method:

Execute the target resource, or execute the next filter! If there is no next filter then the target resource is executed, and if so, then the next filter is executed!

-------------------------------


Four Ways to intercept filters

<dispatcher>REQUEST</dispatcher> Default!

<dispatcher>FORWARD</dispatcher>

<dispatcher>INCLUDE</dispatcher>

<dispatcher>ERROR</dispatcher>

Configure in <filter-mapping>!

-------------------------------

Order of execution for multiple filters

The order in which the <filter-mapping> is configured determines the order in which the filters are executed!

Filter application Case 1. Number of IP Statistics website visits

Code

Lintener

public class Alistener implements Servletcontextlistener {/** * Create map at server startup, save to ServletContext */public    void Contextinitialized (Servletcontextevent SCE) {    //create map    map<string,integer> map = new linkedhashmap< String,integer> ();    Get ServletContext    ServletContext application = Sce.getservletcontext ();    Save the map to application    application.setattribute ("map", map);    public void contextdestroyed (Servletcontextevent sce) {    }}
Filter

/** * Get map from Application * To get the current client's IP * from the request, and save the results to map * @author CXF * */public class Afilter implements Filter {Private filterconfig config;public void Destroy () {}public void DoFilter (ServletRequest request, Servletresponse Respon Se,filterchain chain) throws IOException, servletexception {/* * 1. Get map * 2 in application. Gets the IP address of the current client from request * 3. View m Whether there is an IP corresponding access number in the AP, and if so, save the number of times +1 back to * 4. If this IP does not exist, then this is the first time to access the site, set the number of visits 1 *//* * 1. Get appliction */servletcontext app = Config.getservletcontext (); map<string,integer> map = (map<string, integer>) app.getattribute ("map");/* * 2. Get the IP address of the client */string IP = request.getremoteaddr ();/* * 3. Make a Judgment */if (Map.containskey (IP)) {//This IP exists in the map, stating that it is not the first time to access int cnt = Map.get (IP); map.put (IP, cnt+1);} else {//This IP does not exist in map , the description is the first access to Map.put (IP, 1);} App.setattribute ("map", map),//map back to the app Chain.dofilter (request, response);//Positive Release}/** * This method will be executed when the server is started. And this method only executes once! */public void init (Filterconfig fconfig) throws servletexception {this.config = fConfig;}} 



2. Coarse Granularity Permission Control

public class Adminfilter implements Filter {public void Destroy () {}public void DoFilter (ServletRequest request, Servletre Sponse Response,filterchain chain) throws IOException, servletexception {/* * 1. Get session * 2. Determine if the admin exists in the session field, Release * 3. Determine if there is username in the session field, if present, release, otherwise hit back to login.jsp, and tell it not to blindly stay up to */httpservletrequest req = (httpservletrequest) request; String name = (string) req.getsession (). getattribute ("admin"); if (name! = null) {Chain.dofilter (request, response);} else {Req.setattribute ("msg", "You may be a what, but certainly not an administrator!") "); Req.getrequestdispatcher ("/login.jsp "). Forward (request, response);}} public void init (Filterconfig fconfig) throws servletexception {}}------------------public class Userfilter implements Filter {public void Destroy () {}public void DoFilter (ServletRequest request, servletresponse Response,filterchain chain) Throws IOException, servletexception {/* * 1. Get session * 2. Determine if the session field exists in the admin, if present, release * 3. Determine if there is a username in the session domain, if In, release, otherwise hit back to login.jsp, and tell it not to blind to stay up to */httpservLetrequest req = (httpservletrequest) request; String name = (string) req.getsession (). getattribute ("admin"); if (name! = null) {Chain.dofilter (request, response); return;} Name = (String) req.getsession (). getattribute ("username"), if (name! = null) {Chain.dofilter (request, response);} else { Req.setattribute ("msg", "You're nothing, don't go wandering!") "); Req.getrequestdispatcher ("/login.jsp "). Forward (request, response);}} public void init (Filterconfig fconfig) throws servletexception {}}




3. Solve Post/get Chinese coding problem

Principle: Using decorative mode and Httpservletrequestwrapper packaging class


Filter

public class Encodingfilter implements Filter {public void Destroy () {}public void DoFilter (ServletRequest request, Servle Tresponse Response,filterchain chain) throws IOException, servletexception {// Processing Post request encoding problem request.setcharacterencoding ("Utf-8"); HttpServletRequest req = (httpservletrequest) request;/* * processing GET request encoding problem *///string username = Request.getparameter (" Username ");//username = new String (username.getbytes (" iso-8859-1 ")," UTF-8 ");/* * Swap request * 1. Write a request for the decoration class * 2. When releasing, use our own request */if (Req.getmethod (). Equals ("GET")) {encodingrequest er = new encodingrequest (req); Chain.dofilter (er, response);} else if (Req.getmethod () equals ("POST")) {Chain.dofilter (request, Response);}} public void init (Filterconfig fconfig) throws servletexception {}}

Decorative Packaging class

/** * Decoration Reqeust * @author CXF * */public class Encodingrequest extends Httpservletrequestwrapper {private Httpservletreque St Req;public Encodingrequest (HttpServletRequest request) {super (request); this.req = Request;} public string GetParameter (string name) {String value = Req.getparameter (name);//process encoding problem try {value = new String (VALUE.GETB Ytes ("Iso-8859-1"), "Utf-8");} catch (Unsupportedencodingexception e) {throw new RuntimeException (e);} return value;}}



4. Page static

1. The first step

Write a simple single-table query (slightly)

2. Step two: What is the page static!

First access to the database to get the data, and then save the data to an HTML page (server)

Secondary access, it will not go to the database, but the direct display of HTML

----------------------------------------------------------


1. Target!

A filter is given to save the output of the resource requested by the servlet in HTML and redirect it to an HTML page.

Second access, this HTML already exists, then redirect directly, no need to visit servlet!




Code

Filter

public class Staticfilter implements Filter {private filterconfig config;public void Destroy () {}public void init (Filterco Nfig fconfig) throws servletexception {this.config = Fconfig;} public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {HttpServletRequest req = (httpservletrequest) request; HttpServletResponse res = (httpservletresponse) response;/* * 1. On the first visit, the lookup request for the corresponding HTML page exists if there is a redirect to HTML * 2. If it doesn't exist, release! After the servlet accesses the database, the data output to the client is saved to an HTML file * and then redirected to HTML *//* * One, get the category parameter! * Category has four possibilities: * * null--null.html * * 1--1.html * 2--2.html * * 3--3.html * * HTML page save path, h TMLS Directory * * To determine whether the corresponding HTML file exists, if present, direct redirection! */string category = Request.getparameter ("category"); String htmlpage = category + ". html";//Gets the corresponding file name string Htmlpath = Config.getservletcontext (). Getrealpath ("/htmls");// Get the file's directory of files destfile = new file (Htmlpath, HtmlPage), if (Destfile.exists ()) {//If the file exists//redirected to this file Res.sendredireCT (Req.getcontextpath () + "/htmls/" + htmlpage); return;} /* * Second, if the HTML file does not exist, we want to generate HTML * 1. Release, show.jsp will make a lot of output, we want it to not output to the client, but output to one of our specified HTML file * Complete: * * Swap response, let it's getwriter () and an HTML file binding, Then the output of show.jsp is in the HTML file */staticresponse sr = new Staticresponse (res, Destfile.getabsolutepath ()); Chain.dofilter ( Request, SR);//release, generate HTML file//This page already exists, redirect to HTML file Res.sendredirect (Req.getcontextpath () + "/htmls/" + HtmlPage);}}


Package Response Class

public class Staticresponse extends Httpservletresponsewrapper {private PrintWriter pw;/** * String path:html file path! * @param response * @param path * @throws unsupportedencodingexception  * @throws filenotfoundexception  */public S Taticresponse (httpservletresponse response, String path) throws FileNotFoundException, Unsupportedencodingexception { Super (response);//Create a Stream object along with the HTML file path pw = new PrintWriter (path, "Utf-8");} Public PrintWriter getwriter () {///Returns a PrintWriter object that is bound to HTML//JSP uses it for output so that the data is output to an HTML file. return PW;}}



Web Day21 Web Filter, Application case statistics IP, solve the whole station garbled, coarse granularity permission control, page static

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.