Filters can add additional actions before the request arrives in the JSP or servlet or before the response returns to the client. If you have multiple JSP pages and a servlet that require an identical or similar operation, we can extract the operation into a servlet filter and intercept the interest JSP or servlet via a matching path.
We cite several examples of typical filter applications that readers can generalize by:
• Code Conversion
Garbled problems have plagued many Web application developers because java-based Web applications may run on different Web applications, operating system platforms, or hardware servers, and different environments have their own default encoding types. In the process of data conversion, different default encoding is the originator of garbled problem, so it is often necessary to encode and convert the data when developing JSP. We can create a servlet filter to encode conversions before requesting access to the service program.
• Add a uniform title or footnote
Some pages need to add a uniform header or footnote, and you can add a uniform title and footnote to a Web page by using the servlet filter before the response is returned to the client.
• Safe control
Log on to the system, will generally put the user information object into the session, you can through the servlet filter in the request to enter the JSP or servlet before the user information object, if there is, then the user has logged in, if not, then the user has not logged in, Redirects the request to the login page.
The servlet filters provided in this section are designed to implement security controls, and we will develop this servlet below.
1. Open the wizard that creates the servlet filter.
Start the wizard that creates the servlet filter by double-clicking the filter servlet icon by file->new...->web->, as shown in the following illustration:
Figure 7 Specifying the name of the servlet filter
Figure 8 Specifying a matching path pattern for the filter
|1. Package bookstore.servlet;
3. PublicClass Logincheckfilter
4. Extends HttpServlet implements Filter
7. PublicvoidDofilter (ServletRequestRequest, ServletresponseResponse
8., Filterchain Filterchain)
12.//Type conversions for requests and responses
HttpServletRequest HttpRequest = (httpservletrequest) request;
HttpServletResponse HttpResponse = (httpservletresponse) response;
Boolean isValid = true;
String uristr = Httprequest.getrequesturi (). toUpperCase ();
An. if (uristr. IndexOf("LOGIN.") JSP ") = = 1 &&
Uristr.indexof ("SWITCH. JSP ") = = 1 &&
Httprequest.getsession (). getattribute ("ses_userbean") = = null)
IsValid = false;
Filterchain.dofilter (request, response);
The catch (servletexception SX)
Filterconfig.getservletcontext (). log (Sx.getmessage ());
catch (IOException Iox)
Filterconfig.getservletcontext (). log (Iox.getmessage ());