目次へ

解答例 - 実習課題2 - 6.フィルタ

(実習課題2)

実習課題1を改良しなさい。

  • Internet Explorer以外のブラウザからのアクセスに対して、505エラーを返すフィルタを適応する事。

解答例

/*
 * IeFilter.java TECHSCORE Java Servlet6章 実習課題2
 * 
 * Copyright (c) 2004 Four-Dimensional Data, Inc.
 */
package com.techscore.servlet.chapter6.exercise2;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class IeFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest
                && response instanceof HttpServletResponse) {
            String agent = ((HttpServletRequest) request)
                    .getHeader("User-Agent");
            if (agent.indexOf("IE") == -1) {
                ((HttpServletResponse) response)
                        .sendError(HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED);
            }
        }
        chain.doFilter(request, response);
    }

    public void destroy() {

    }

}
<?xml version="1.0" encoding="EUC-JP"?>
<!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>IeFilter</filter-name>
    <filter-class>com.techscore.servlet.chapter6.exercise2.IeFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>IeFilter</filter-name>
    <url-pattern>/servlet5-3</url-pattern>
  </filter-mapping>

</web-app>

↑このページの先頭へ

こちらもチェック!

PR
  • XMLDB.jp