解答例 - 実習課題1 - 6.フィルタ
(実習課題1)
サンプルのフィルタを実装し、5章実習課題3のサーブレットに適応する事。
解答例
/* * CounterFilter.java TECHSCORE Java Servlet6章 実習課題1 * * Copyright (c) 2004 Four-Dimensional Data, Inc. */ package com.techscore.servlet.chapter6.exercise1; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; public class CounterFilter implements Filter { private ServletContext context = null; public void init(FilterConfig config) throws ServletException { context = config.getServletContext(); context.setAttribute("counter", new Integer(1)); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); Integer counter = (Integer) context.getAttribute("counter"); PrintWriter writer = ((HttpServletResponse) response).getWriter(); writer.print("フィルタのカウンタ:"); writer.println(counter.intValue()); context.setAttribute("counter", new Integer(counter.intValue() + 1)); } public void destroy() { context = null; } }
<?xml version="1.0" encoding="Shift_JIS"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <filter> <filter-name>Counter</filter-name> <filter-class>com.techscore.servlet.chapter6.exercise1.CounterFilter</filter-class> </filter> <filter-mapping> <filter-name>Counter</filter-name> <url-pattern>/servlet5-3</url-pattern> </filter-mapping> </web-app>