URL RewriterとStrtus 2.0を組み合わせて使用(半分の問題を解決)


tldをstruts 2.0と追加する.tldは一緒に置いてあり、その内容は以下の通りである(に相当し、名前とクラス名が変更されただけである.):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name>r</short-name>
  <uri>/urlrewriter-tags</uri>
 <tag>
    <name>urlrewrite</name>
    <tag-class>com.conkeyn.web.taglib.URLRewriterTag</tag-class>
    <body-content>JSP</body-content>
    <description><![CDATA[This tag is used to create a URL]]></description>
    <attribute>
      <name>action</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[he action generate url for, if not using value]]></description>
    </attribute>
    <attribute>
      <name>anchor</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[The anchor for this URL]]></description>
    </attribute>
    <attribute>
      <name>encode</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[Whether to encode parameters]]></description>
    </attribute>
    <attribute>
      <name>id</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[id for referencing element. For UI and form tags it will be used as HTML id attribute]]></description>
    </attribute>
    <attribute>
      <name>includeContext</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[Whether actual context should be included in url]]></description>
    </attribute>
    <attribute>
      <name>includeParams</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[The includeParams attribute may have the value 'none', 'get' or 'all']]></description>
    </attribute>
    <attribute>
      <name>method</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[The method of action to use]]></description>
    </attribute>
    <attribute>
      <name>namespace</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[The namespace to use]]></description>
    </attribute>
    <attribute>
      <name>portletMode</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[The resulting portlet mode]]></description>
    </attribute>
    <attribute>
      <name>portletUrlType</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[Specifies if this should be a portlet render or action url]]></description>
    </attribute>
    <attribute>
      <name>scheme</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[Set scheme attribute]]></description>
    </attribute>
    <attribute>
      <name>value</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[The target value to use, if not using action]]></description>
    </attribute>
    <attribute>
      <name>windowState</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
      <description><![CDATA[The resulting portlet window state]]></description>
    </attribute>
  </tag>
 
</taglib>

 
コードを追加(元ののクラスをコピーして変更):
package com.conkeyn.web.taglib;

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

import org.apache.struts2.components.Component;
import org.apache.struts2.views.jsp.ComponentTagSupport;

import com.opensymphony.xwork2.util.ValueStack;

/**
 * title:     <s:url>  ,   URL Rewriter    。
 * 
 * @   2008-9-24:  02:16:56
 */
public class URLRewriterTag extends ComponentTagSupport {

	private static final long serialVersionUID = 1722460444125206226L;

	protected String includeParams;
	protected String scheme;
	protected String value;
	protected String action;
	protected String namespace;
	protected String method;
	protected String encode;
	protected String includeContext;
	protected String escapeAmp;
	protected String portletMode;
	protected String windowState;
	protected String portletUrlType;
	protected String anchor;
	protected String forceAddSchemeHostAndPort;

	public Component getBean(ValueStack stack, HttpServletRequest req,
			HttpServletResponse res) {
		return new URLRewriter(stack, req, res);
	}

	protected void populateParams() {
		super.populateParams();
		URLRewriter url = (URLRewriter) component;
		url.setIncludeParams(includeParams);
		url.setScheme(scheme);
		url.setValue(value);
		url.setMethod(method);
		url.setNamespace(namespace);
		url.setAction(action);
		url.setPortletMode(portletMode);
		url.setPortletUrlType(portletUrlType);
		url.setWindowState(windowState);
		url.setAnchor(anchor);
		if (encode != null) {
			url.setEncode(Boolean.valueOf(encode).booleanValue());
		}
		if (includeContext != null) {
			url.setIncludeContext(Boolean.valueOf(includeContext)
					.booleanValue());
		}
		if (escapeAmp != null) {
			url.setEscapeAmp(Boolean.valueOf(escapeAmp).booleanValue());
		}
		if (forceAddSchemeHostAndPort != null) {
			url.setForceAddSchemeHostAndPort(Boolean.valueOf(
					forceAddSchemeHostAndPort).booleanValue());
		}
	}

	public void setEncode(String encode) {
		this.encode = encode;
	}

	public void setIncludeContext(String includeContext) {
		this.includeContext = includeContext;
	}

	public void setEscapeAmp(String escapeAmp) {
		this.escapeAmp = escapeAmp;
	}

	public void setIncludeParams(String name) {
		includeParams = name;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public void setScheme(String scheme) {
		this.scheme = scheme;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public void setPortletMode(String portletMode) {
		this.portletMode = portletMode;
	}

	public void setPortletUrlType(String portletUrlType) {
		this.portletUrlType = portletUrlType;
	}

	public void setWindowState(String windowState) {
		this.windowState = windowState;
	}

	public void setAnchor(String anchor) {
		this.anchor = anchor;
	}

	public void setForceAddSchemeHostAndPort(String forceAddSchemeHostAndPort) {
		this.forceAddSchemeHostAndPort = forceAddSchemeHostAndPort;
	}
}

 
package com.conkeyn.web.taglib;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.net.URL;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.StrutsException;
import org.apache.struts2.components.Component;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.portlet.context.PortletActionContext;
import org.apache.struts2.portlet.util.PortletUrlHelper;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import org.apache.struts2.views.util.UrlHelper;
import org.tuckey.web.filters.urlrewrite.Conf;
import org.tuckey.web.filters.urlrewrite.UrlRewriteWrappedResponse;
import org.tuckey.web.filters.urlrewrite.UrlRewriter;

import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;

@StrutsTag(name = "urlrewrite", tldTagClass = "com.conkeyn.web.taglib.URLRewriter", description = "This tag is used to create a rewrited URL ")
public class URLRewriter extends Component {
	private static final Log LOG = LogFactory.getLog(URLRewriter.class);

	public static final String NONE = "none";
	public static final String GET = "get";
	public static final String ALL = "all";

	private HttpServletRequest req;
	private HttpServletResponse res;

	protected String includeParams;
	protected String scheme;
	protected String value;
	protected String action;
	protected String namespace;
	protected String method;
	protected boolean encode = true;
	protected boolean includeContext = true;
	protected boolean escapeAmp = true;
	protected String portletMode;
	protected String windowState;
	protected String portletUrlType;
	protected String anchor;
	protected boolean forceAddSchemeHostAndPort;
	protected String urlIncludeParams;
	protected ExtraParameterProvider extraParameterProvider;

	public URLRewriter(ValueStack stack, HttpServletRequest req,
			HttpServletResponse res) {
		super(stack);
		this.req = req;
		this.res = res;
	}

	@Inject(StrutsConstants.STRUTS_URL_INCLUDEPARAMS)
	public void setUrlIncludeParams(String urlIncludeParams) {
		this.urlIncludeParams = urlIncludeParams;
	}

	@Inject(required = false)
	public void setExtraParameterProvider(ExtraParameterProvider provider) {
		this.extraParameterProvider = provider;
	}

	public boolean start(Writer writer) {
		boolean result = super.start(writer);

		if (value != null) {
			value = findString(value);
		}
		try {
			String includeParams = (urlIncludeParams != null ? urlIncludeParams
					.toLowerCase() : GET);
			if (this.includeParams != null) {
				includeParams = findString(this.includeParams);
			}
			if (NONE.equalsIgnoreCase(includeParams)) {
				mergeRequestParameters(value, parameters, Collections.EMPTY_MAP);
			} else if (ALL.equalsIgnoreCase(includeParams)) {
				mergeRequestParameters(value, parameters, req.getParameterMap());
				includeGetParameters();
				includeExtraParameters();
			} else if (GET.equalsIgnoreCase(includeParams)
					|| (includeParams == null && value == null && action == null)) {
				includeGetParameters();
				includeExtraParameters();
			} else if (includeParams != null) {
				LOG
						.warn("Unknown value for includeParams parameter to URL tag: "
								+ includeParams);
			}
		} catch (Exception e) {
			LOG.warn("Unable to put request parameters ("
					+ req.getQueryString() + ") into parameter map.", e);
		}
		return result;
	}

	private void includeExtraParameters() {
		if (extraParameterProvider != null) {
			mergeRequestParameters(value, parameters, extraParameterProvider
					.getExtraParameters());
		}
	}

	private void includeGetParameters() {
		if (!(Dispatcher.getInstance().isPortletSupportActive() && PortletActionContext
				.isPortletRequest())) {
			String query = extractQueryString();
			mergeRequestParameters(value, parameters, UrlHelper
					.parseQueryString(query));
		}
	}

	private String extractQueryString() {
		// Parse the query string to make sure that the parameters come from the
		// query, and not some posted data
		String query = req.getQueryString();
		if (query == null) {
			query = (String) req
					.getAttribute("javax.servlet.forward.query_string");
		}
		if (query != null) {
			// Remove possible #foobar suffix
			int idx = query.lastIndexOf('#');

			if (idx != -1) {
				query = query.substring(0, idx);
			}
		}
		return query;
	}

	public boolean end(Writer writer, String body) {
		String scheme = req.getScheme();

		if (this.scheme != null) {
			scheme = this.scheme;
		}

		String result;
		if (value == null && action != null) {
			if (Dispatcher.getInstance().isPortletSupportActive()
					&& PortletActionContext.isPortletRequest()) {
				result = PortletUrlHelper.buildUrl(action, namespace, method,
						parameters, portletUrlType, portletMode, windowState);
			} else {
				result = determineActionURL(action, namespace, method, req,
						res, parameters, scheme, includeContext, encode,
						forceAddSchemeHostAndPort, escapeAmp);
			}
		} else {
			if (Dispatcher.getInstance().isPortletSupportActive()
					&& PortletActionContext.isPortletRequest()) {
				result = PortletUrlHelper.buildResourceUrl(value, parameters);
			} else {
				String _value = value;

				// We don't include the request parameters cause they would have
				// been
				// prioritised before this [in start(Writer) method]
				if (_value != null && _value.indexOf("?") > 0) {
					_value = _value.substring(0, _value.indexOf("?"));
				}
				result = UrlHelper.buildUrl(_value, req, res, parameters,
						scheme, includeContext, encode,
						forceAddSchemeHostAndPort, escapeAmp);
			}
		}
		if (anchor != null && anchor.length() > 0) {
			result += '#' + anchor;
		}
		String id = getId();
		if (id != null) {
			getStack().getContext().put(id, result);
			// add to the request and page scopes as well
			req.setAttribute(id, result);
		} else {
			try {
				result = rewriteURL(result, req, res);
				writer.write(result);
			} catch (IOException e) {
				throw new StrutsException("IOError: " + e.getMessage(), e);
			} catch (Exception e) {
				throw new StrutsException("Error: " + e.getMessage(), e);
			}
		}
		return super.end(writer, body);
	}

	/**
	 *   URL    
	 * 
	 * @param url
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String rewriteURL(String url, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UrlRewriter urlRewriter = null;
		Conf conf = null;
		String DEFAULT_WEB_CONF_PATH = "/WEB-INF/classes/urlrewrite.xml";
		ServletContext context = request.getSession().getServletContext();
		InputStream inputStream = context
				.getResourceAsStream(DEFAULT_WEB_CONF_PATH);
		URL confUrl = null;
		confUrl = context.getResource(DEFAULT_WEB_CONF_PATH);

		String confUrlStr = null;
		if (confUrl != null) {
			confUrlStr = confUrl.toString();
		}
		if (inputStream == null) {
			System.err.println("unable to find urlrewrite conf file at "
					+ DEFAULT_WEB_CONF_PATH);
			// set the writer back to null
			if (urlRewriter != null) {
				System.err.println("unloading existing conf");
				urlRewriter = null;
			}

		} else {
			conf = new Conf(context, inputStream, DEFAULT_WEB_CONF_PATH,
					confUrlStr, false);
			conf.initialise();
		}
		urlRewriter = new UrlRewriter(conf);
		UrlRewriteWrappedResponse urlRewriteWrappedResponse = new UrlRewriteWrappedResponse(
				response, request, urlRewriter);
		//  HTML           
		url = StringEscapeUtils.unescapeHtml(url);
		//   URL Rewriter     
		url = urlRewriteWrappedResponse.encodeURL(url);
		//     HTML   
		url = StringEscapeUtils.escapeHtml(url);
		return url;
	}

	@StrutsTagAttribute(description = "The includeParams attribute may have the value 'none', 'get' or 'all'", defaultValue = "get")
	public void setIncludeParams(String includeParams) {
		this.includeParams = includeParams;
	}

	@StrutsTagAttribute(description = "Set scheme attribute")
	public void setScheme(String scheme) {
		this.scheme = scheme;
	}

	@StrutsTagAttribute(description = "The target value to use, if not using action")
	public void setValue(String value) {
		this.value = value;
	}

	@StrutsTagAttribute(description = "The action to generate the URL for, if not using value")
	public void setAction(String action) {
		this.action = action;
	}

	@StrutsTagAttribute(description = "The namespace to use")
	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}

	@StrutsTagAttribute(description = "The method of action to use")
	public void setMethod(String method) {
		this.method = method;
	}

	@StrutsTagAttribute(description = "Whether to encode parameters", type = "Boolean", defaultValue = "true")
	public void setEncode(boolean encode) {
		this.encode = encode;
	}

	@StrutsTagAttribute(description = "Whether actual context should be included in URL", type = "Boolean", defaultValue = "true")
	public void setIncludeContext(boolean includeContext) {
		this.includeContext = includeContext;
	}

	@StrutsTagAttribute(description = "The resulting portlet mode")
	public void setPortletMode(String portletMode) {
		this.portletMode = portletMode;
	}

	@StrutsTagAttribute(description = "The resulting portlet window state")
	public void setWindowState(String windowState) {
		this.windowState = windowState;
	}

	@StrutsTagAttribute(description = "Specifies if this should be a portlet render or action URL. Default is \"render\". To create an action URL, use \"action\".")
	public void setPortletUrlType(String portletUrlType) {
		this.portletUrlType = portletUrlType;
	}

	@StrutsTagAttribute(description = "The anchor for this URL")
	public void setAnchor(String anchor) {
		this.anchor = anchor;
	}

	@StrutsTagAttribute(description = "Specifies whether to escape ampersand (&) to (&amp;) or not", type = "Boolean", defaultValue = "true")
	public void setEscapeAmp(boolean escapeAmp) {
		this.escapeAmp = escapeAmp;
	}

	@StrutsTagAttribute(description = "Specifies whether to force the addition of scheme, host and port or not", type = "Boolean", defaultValue = "false")
	public void setForceAddSchemeHostAndPort(boolean forceAddSchemeHostAndPort) {
		this.forceAddSchemeHostAndPort = forceAddSchemeHostAndPort;
	}

	
	protected void mergeRequestParameters(String value, Map parameters,
			Map contextParameters) {

		Map mergedParams = new LinkedHashMap(contextParameters);

		// Merge contextParameters (from current request) with parameters
		// specified in value attribute
		// eg. value="someAction.action?id=someId&venue=someVenue"
		// where the parameters specified in value attribute takes priority.

		if (value != null && value.trim().length() > 0
				&& value.indexOf("?") > 0) {
			mergedParams = new LinkedHashMap();

			String queryString = value.substring(value.indexOf("?") + 1);

			mergedParams = UrlHelper.parseQueryString(queryString);
			for (Iterator iterator = contextParameters.entrySet().iterator(); iterator
					.hasNext();) {
				Map.Entry entry = (Map.Entry) iterator.next();
				Object key = entry.getKey();

				if (!mergedParams.containsKey(key)) {
					mergedParams.put(key, entry.getValue());
				}
			}
		}

		// Merge parameters specified in value attribute
		// eg. value="someAction.action?id=someId&venue=someVenue"
		// with parameters specified though param tag
		// eg. <param name="id" value="%{'someId'}" />
		// where parameters specified through param tag takes priority.

		for (Iterator iterator = mergedParams.entrySet().iterator(); iterator
				.hasNext();) {
			Map.Entry entry = (Map.Entry) iterator.next();
			Object key = entry.getKey();

			if (!parameters.containsKey(key)) {
				parameters.put(key, entry.getValue());
			}
		}
	}

	public static interface ExtraParameterProvider {
		public Map getExtraParameters();
	}
}

rewriteURL()の方法はとても俗っぽくて腫れていて、誰がもっと良い方法を考え出すことができます.よろしくお愿いします.
 
以上のコード機能はで使用されています.の問題はまだ解決されていない.解決を待つ....