開発メモ

開発用のメモです。

リクエストから特定のパラメーターを除外する。(一覧取得時)

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts.action.ActionServlet;

public class SecureStrutsActioServlet extends ActionServlet {

    String excludes = "class,classLoader,type"; // init param で設定

    @Override
    public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // TODO 自動生成されたメソッド・スタブ
        super.process(new SecureHttpServletRequest(request), response);
    }

    protected class SecureHttpServletRequest extends HttpServletRequestWrapper {

        public SecureHttpServletRequest(HttpServletRequest request) {
            super(request);
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            Map<String, String[]> map = super.getParameterMap();
            for (Map.Entry<String, String[]> entry : map.entrySet()) {
                for (String exclude : excludes.split(",")) {
                    if (StringUtils.containsIgnoreCase(entry.getKey(), exclude)) {
                        map.remove(entry.getKey());
                    }
                }
            }
            return map;
        }

        @Override
        public Enumeration<String> getParameterNames() {
            Enumeration<String> enumeration = super.getParameterNames();
            Vector<String> vector = new Vector<String>();
         loop:
            while (enumeration.hasMoreElements()) {
                String target = enumeration.nextElement();
                for (String exclude : excludes.split(",")) {
                    if (StringUtils.containsIgnoreCase(target, exclude)) {
                        continue loop;
                    }
                }
                vector.addElement(target);
            }
            return vector.elements();
        }

        /*
               @Override
               public String[] getParameterValues(String name) {
                   for (String exclude : excludes.split(",")) {
                       if (StringUtils.containsIgnoreCase(name, exclude)) {
                           return null;
                       }
                   }
                   return super.getParameterValues(name);
               }

               @Override
               public String getParameter(String name) {
                   for (String exclude : excludes.split(",")) {
                       if (StringUtils.containsIgnoreCase(name, exclude)) {
                           return null;
                       }
                   }
                   return super.getParameter(name);
               }
       */
    }

}
Twitter: @asahina_alice