Strutsフレームワークの改造と結びつけてThreadLocalの使用について述べる(三)


ActionContextクラスを参照:
public class ActionContext {
  private static ThreadLocal entryThread = new ThreadLocal();
  public static void init(ActionMapping mapping,
                            ActionForm form,
                            HttpServletRequest request,
                            HttpServletResponse response) {
	if (entryThread.get() != null)
		destroy();
	Entry entry = new Entry(mapping, form, request, response);
	entryThread.set(entry);
  }  

  public static void destroy() {
    entryThread.set(null);
  }

  public static ActionMapping getMapping() {
    Entry entry = getEntry();
    if (entry == null)
        throw new NullPointerException("ActionContext has not been initialized");
    return entry.mapping;
  }

  public static ActionForm getForm() {
    Entry entry = getEntry();
    if (entry == null)
        throw new NullPointerException("ActionContext has not been initialized");
    return entry.form;
  }

  public static HttpServletRequest getRequest() {
    Entry entry = getEntry();
    if (entry == null)
        throw new NullPointerException("ActionContext has not been initialized");
    return entry.request;
  }

  public static HttpServletResponse getResponse() {
    Entry entry = getEntry();
    if (entry == null)
        throw new NullPointerException("ActionContext has not been initialized");
    return entry.response;
 }

  public static HttpSession getSession() {
      return getRequest().getSession();
  }
  public static ServletContext getContext() {
	return getSession().getServletContext();
  }

  private static Entry getEntry() {
	return (Entry) entryThread.get();
  }

  static class Entry {
    ActionMapping mapping;
    ActionForm form;
    HttpServletRequest request;
    HttpServletResponse response;

    public Entry(ActionMapping mapping,
                 ActionForm form,
                 HttpServletRequest request,
                 HttpServletResponse response) {
        this.mapping = mapping;
        this.form = form;
        this.request = request;
        this.response = response;
    }
  }
}