We repeat the above steps to create an income filter.
In step three of the filter wizard we specify the maximum income:
Here's the implementation of doFilter:
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws
IOException, ServletException {
double income = new
Double(request.getParameter("income"));
double maxIncome =
new
Double(_filterConfig.getInitParameter("maxIncome"));
if (maxIncome < income) {
PrintWriter out =
response.getWriter();
out.println("<html>");
out.println("<head><title>Calculator</title></head>");
out.println("<body>");
out.println(
"sorry,
your income must be <= $50,000/year.");
out.println("</body></html>");
out.close();
return;
}
chain.doFilter(request,
response);
}
Note that this time instead of hard wiring the maximum income into the servlet, it is stored in the filter configuration, which is initialized in the filter's init method:
public void
init(FilterConfig filterConfig)
throws ServletException {
_filterConfig = filterConfig;
}
Let's take a look at the beginning of the web.xml file. This is used by the servlet container to initialize the web application:
<web-app ...>
<description>
Empty web.xml file for Web
Application
</description>
<filter>
<filter-name>AgeFilter</filter-name>
<filter-class>stipcalc.AgeFilter</filter-class>
</filter>
<filter>
<filter-name>IncomeFilter</filter-name>
<filter-class>stipcalc.IncomeFilter</filter-class>
<init-param>
<param-name>maxIncome</param-name>
<param-value>50000</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>AgeFilter</filter-name>
<url-pattern>/calculator</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>IncomeFilter</filter-name>
<url-pattern>/calculator</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>Calculator</servlet-name>
<servlet-class>stipcalc.Calculator</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Calculator</servlet-name>
<url-pattern>/calculator</url-pattern>
</servlet-mapping>
...
</web-app>
Note the filter element for IncomeFilter is where the initial value of maxIncome is stored.
Note also that requests for the /caclulator URL are mapped to the age filter first, then the income filter.
Here's a sample request:
And here's the short circuit response: