March 24th, 2008
452 CHAPTER 11 ADVANCED FILTERING TECHNIQUES the two systems. Figure 11-11 shows the result when the FindProd.jsp page receives a request without the required request parameter. This filter intercepts the request, examines where it s from, and generates the required DEPT parameter for the JSP resource so that it can function properly. It determines the department of the incoming client by examining its subnet portion of the IP address corresponding to the client (assume you have the subnet IP to department-mapping information). Therefore, this adapter translates an incoming IP address to a required DEPT parameter and allows two incompatible systems to work together. You can easily imagine many more complex examples from the real world that may require significantly more adaptation code; however, the general structure and technique for creating such adapter filters remains the same. Figure 11-11. When a request does not contain the necessary department, the resulting web page does not display correctly. The reason the message does not contain a department name is because of the missing DEPT parameter when the URL is accessed. You ll fix this by creating a filter that will adapt any incoming requests by detecting the department information and providing the missing parameter. Wrapping an Incoming Request with the LegacyAdapterFilter
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.
Posted in Jsp | No Comments »
March 23rd, 2008
CHAPTER 11 ADVANCED FILTERING TECHNIQUES 451 Filter 3: A Filter for Adapting to Legacy Resources The next filter you will examine addresses a common problem in the real world that occurs when two independent systems refer to each other through hyperlinks. Over time, the requirement and access changes because of independent evolution. Imagine that because of the size of the independent projects, or because of political situations, you can t change the links to either one of the systems. To keep them working, you ll create a filter that adapts one system to another, without modifying a single line of code in either system. Figure 11-10 shows the action of just such an adapter filter within a typical system. Figure 11-10. Filters can modify requests so that two systems that were not built to work together can be integrated. In this example, a JSP page represents the legacy resource. A centralized administrative server that is accessed by multiple departments in a company services this JSP page. This legacy system requires the originating department information to be supplied in the form of a DEPT parameter in order to work properly. Unfortunately, because of political situations in this hypothetical company, the links coming into this server don t and won t contain the originating department information (the DEPT parameter). Therefore, you ll design a filter to adapt
We recommend high quality webhost to host and run your jsp application: christian web host services.
Posted in Jsp | No Comments »
March 22nd, 2008
450 CHAPTER 11 ADVANCED FILTERING TECHNIQUES Make sure that you ve configured the starthour and stophour variables to make the current time outside of the allowable range, and create a games directory off the filters2 web-application directory that contains an appropriate index.html file. Start Tomcat and try to access the following URL through a browser: http://localhost:8080/filters2/games/index.html You should see an access denied message as shown in Figure 11-8. Figure 11-8. When a request is made outside allowable hours, the filter blocks the request. This is the custom-generated response straight from the filter. Now, modify the element in web.xml to include the current time within the range. Reload the web application by using Tomcat s management tool, or restart Tomcat, and try to access the same URL. Figure 11-9 shows the page you should now see. Figure 11-9. When a request is made within allowable hours, the filter passes the request down the chain.
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.
Posted in Jsp | No Comments »
March 21st, 2008
CHAPTER 11 ADVANCED FILTERING TECHNIQUES 449 the same time. Following the filter life cycle, however, there s a natural place to set the value of your initialization parameters. After an instance of a filter has been created, and before the very first doFilter() is called, the container calls the init() method to set the FilterConfig object for the filter. This is a natural point at which to perform any initialization required, and it s conceptually equivalent to the init() method of a servlet. In this case, you ll take advantage of it by setting your instance variables with values from the filter definition. Listing 11-10 shows the init() method for the StopGamesFilter. The container always calls init() in a single thread when it sets up the filter instance. In the init() method, the filterConfig.getInitParameter()method reads the web.xml file for initialization parameters. The init() method in Listing 11-10 replaces the init() method in Listing 11-9. Listing 11-10. init() (To Be Added to StopGamesFilter.java) public void init(FilterConfig arg0) throws ServletException { String tpString; filterConfig = arg0; if ((tpString = filterConfig.getInitParameter(”starthour”)) != null) starthour = Integer.parseInt(tpString, 10); if ((tpString = filterConfig.getInitParameter(”stophour”)) != null) stophour = Integer.parseInt(tpString, 10); } Installing and Configuring the StopGamesFilter To install and configure the filter, first make sure all other and elements are removed or commented out of the web.xml file. Then add the following entries Stop Games Filter com.apress.projsp.StopGamesFilter
starthour
8
stophour
9 Stop Games Filter /games/*
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.
Posted in Jsp | No Comments »
March 20th, 2008
448 CHAPTER 11 ADVANCED FILTERING TECHNIQUES out.println(”
“); out.println(”
Sorry, game playing is not ” + “allowed at this time!
“); out.println(”“); out.flush(); filterConfig.getServletContext() .log(”Access to game page denied”); return; } filterConfig.getServletContext() .log(”Access to game page granted”); chain.doFilter(request, response); filterConfig.getServletContext() .log(”Getting out of StopGamesFilter”); } public void init(FilterConfig arg0) throws ServletException { this.filterConfig = arg0; } public void destroy() {} } The class has two instance variables to hold the default hours of operation, which allows game playing all the time. These parameters are used if the filter is configured without initial parameters, or if the access to the initial parameters failed. It s always a good idea to set some usable default value for the filter. In the doFilter()method, the class obtains the current hour, which depends on a 24-hour clock to make things simple. The class also assumes that the start and stop hours don t cross the 12 a.m. boundary to keep the logic simple. Next, the class makes a log entry to show the various values, which is useful for auditing or debugging purposes. If the incoming request arrives outside of the allowed time range, doFilter() simply generates the content of the response. The generated content lets the user know that access to the game resource page is disallowed. If the request arrives within the allowed hours, the filter lets the request through to access the game resource by passing the request and response to chain.doFilter(). Thread-Safety Considerations One question that you may have is, Where do I access the initialization parameters? The answer is, generally not in the doFilter() method. This goes back to our discussion in the previous chapter about thread-safe programming. The starthour and stophour variables are instance-scoped variables. Modifying the value of instance-scoped variables in doFilter() requires careful synchronization, because doFilter() will be accessed in multiple threads at
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.
Posted in Jsp | No Comments »
March 18th, 2008
CHAPTER 11 ADVANCED FILTERING TECHNIQUES 447 No Figure 11-7. When a request is made outside the allowable hours, the filter denies access to the requested resource. Listing 11-9 shows the code for StopGamesFilter. The filter is designed to allow you to make the range of allowable hours a configurable parameter, to make the filter flexible enough for use in different environments. It also gives you a chance to see how to access and work with initial parameters in filters. Listing 11-9. StopGamesFilter.java package com.apress.projsp; import java.io.*; import javax.servlet.*; import java.util.Calendar; public final class StopGamesFilter implements Filter { private FilterConfig filterConfig = null; private int starthour = 0; private int stophour = 24; // default is to allow all the time public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Calendar myCal = Calendar.getInstance(); int curhour = myCal.get(Calendar.HOUR_OF_DAY); filterConfig.getServletContext().log( “in StopGamesFilter cur:” + curhour + “, start: ” + starthour + “, end: ” + stophour); if ((curhour >= stophour) || (curhour < starthour)) { PrintWriter out = response.getWriter();
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.
Posted in Jsp | No Comments »
March 17th, 2008
446 CHAPTER 11 ADVANCED FILTERING TECHNIQUES Next, you ll try a servlet resource instead. Open http://localhost:8080/filters2/servlet/ findprod (note that findprodis lowercase). Figure 11-6 shows that the output is once again intercepted and the auditing information is appended. Figure 11-6. Filters can act upon any web resource including static HTML pages, JSP pages, and, as shown here, servlets. If you re creating filters that must work across many types of resources, you must test against each type of resource. This is necessary because each type of resource is passed through a different resource processor, each of which potentially has different assumptions and behavior from the others (servlets are passed to Catalina, JSP pages are passed to Jasper first, and so on). Filter 2: An Authorization Filter A filter can generate its own output and deprive the downstream filters and resource processor of a chance to see the request altogether. Obviously, there s very little application for a filter that does this all the time, but a filter that does this based on some dynamic criterion can be useful. One example is a filter that blocks resource access based on the time of day. You ll create such a filter in this section. Generating Your Own Response The filter you re going to create falls into the authorization filter application domain. More specifically, it allows or disallows an incoming request to reach its destined resource processor depending on the time of day. The application is intended to stop users from accessing game- playing resources during certain hours. Figure 11-7 illustrates the filter action. If a request arrives during the allotted time window, the user is allowed through to the resource processor to play games. If a request arrives outside of the allotted time window, the filter generates a response of its own, depriving the downstream resource processor of a chance to see the request. This effectively blocks the use of the game resources.
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.
Posted in Jsp | No Comments »
February 26th, 2008
CHAPTER 11 ADVANCED FILTERING TECHNIQUES 445 When close() is called for the first time, the class transforms the output in the in- memory stream. After the transformation, the class stores the results so the filter can retrieve them later. Multiple calls to close() don t cause a problem in this case. The processStream() method calls the replaceContent() method to transform the in-memory stream and write the transformed output to the wrapped output stream. The replaceContent() method is abstract. Subclasses of this class will provide an implementation for the method. The intention is for subclasses to transform the input byte array and return the transformed array. As you saw in Listing 11-4, VisAuditOutStream.java, that subclass transforms the inBytes byte array by adding additional data to the stream. This is the end of the code analysis for the ReplaceContentOutputStream abstract class. You ll rely on this class for two subsequent filters that transform their outgoing response s content. Configuring and Testing the Filter To deploy the filter, add the filter definition and filter mapping in Listing 11-8 to the web.xml file. Listing 11-8. and< filter-mapping> Elements for web.xml VisAudit Filter com.apress.projsp.VisAuditFilter VisAudit Filter /* This mapping will apply the filter to every resource served by the application. Start by loading the JSP page FindProd.jsp, as shown in Figure 11-5, using the appropriate test URL for the application you created. Figure 11-5. The VisAuditFilter can be used to filter JSP pages. It appends an audit message to the end of the response.
In case you need quality webspace to host and run your web applications, try our personal web hosting services.
Posted in Jsp | No Comments »
February 25th, 2008
444 CHAPTER 11 ADVANCED FILTERING TECHNIQUES extends ServletOutputStream { byte[] result; private ByteArrayOutputStream baStream; private boolean closed = false; public ReplaceContentOutputStream() { baStream = new ByteArrayOutputStream(); } public void write(int i) throws java.io.IOException { baStream.write(i); } public void close() throws java.io.IOException { if (!closed) { processStream(); closed = true; } } public abstract byte[] replaceContent(byte[] inBytes) throws java.io.IOException; public void processStream() throws java.io.IOException { result = replaceContent(baStream.toByteArray()); } public byte[] getResult() { return result; } } This abstract class extends another abstract class, called ServletOutputStream, which is the base class of the OutputStreamreturned by getOutputStream()on a response. ServletOutputStream requires the write(int) method to be implemented by its subclass. It implements all the other write() variants based on this method. The ReplaceContentOutputStreamrequires the replaceContent() method to be implemented by all its subclasses. Note the use of the flag variable closed: Initially false, this variable is used to ensure that the wrapped stream is closed only once, regardless of how many times the close() method may be called. The constructor creates the memory-based ByteArrayOutputStream for the downstream processors. Next, the class implements the required write(int)method, which writes to the in- memory byte array stream called baStream. This ensures that all writes on this stream write to baStream (essentially a buffer).
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.
Posted in Jsp | No Comments »
February 24th, 2008
CHAPTER 11 ADVANCED FILTERING TECHNIQUES 443 filterConfig.getServletContext().log( “Getting out of VisAuditFilter”); } public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } public void destroy() {} } Code in the doFilter() method, prior to the chain.doFilter() call, is executed on the inbound request. The code retrieves the client s IP address and the host name. This information will be passed down to the custom stream. After a little logging, the class creates a new customized wrapped response, passing in the actual response as well as the IP address and host name. Then the class calls chain.doFilter(), passing the wrapped response downstream to other filters and the resource processor. Some resource processor and downstream filter combinations don t close the output stream properly, so after chain.doFilter() returns, the code forces a close on the PrintWriter. You ll see shortly that the implementation of the ReplaceContentOutputStream class is guarded against multiple closes, so this is safe even if the stream was closed previously. The rest of these methods implement the filter interface and are standard implementations that you saw within the samples of Chapter 10. The ReplaceContentOutputStream Class The custom stream, VisAuditOutStream, depends on the ReplaceContentOutputStream class (Listing 11-7) to do a lot of its magic. This class wraps an OutputStream and does the following: Supplies its own byte array based stream for the write() method, called by downstream filters and the resource processor. Handles the close() method by calling a child s replaceContent() method to transform the byte array stream. Provides the transformed content through the getResult() method. This method is called by the filter when the filter writes the response. This class can be used for any filter that transforms or replaces the response content. Listing 11-7. ReplaceContentOutputStream.java package com.apress.projsp; import java.io.*; import javax.servlet.*; public abstract class ReplaceContentOutputStream
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.
Posted in Jsp | No Comments »