struts 2 alertプロンプト付きredirectResult

3264 ワード

使用方法:
1、result-typeの登録

<result-types>
    <result-type name="redirect-message" class="RedirectMessageResult" />
</result-types>

2、Actionにresult-typeを指定する

<action name="loginAction" class="LoginAction">
    <result name="success" type="redirect-message">index.action</result>
</action>

StrutsResultSupportコードは次のとおりです.

public class RedirectMessageResult extends StrutsResultSupport {

	private static final long serialVersionUID = -5046390384916067270L;

	private static Logger log = Logger.getLogger(RedirectMessageResult.class);

	protected boolean prependServletContext = true;

	public RedirectMessageResult() {
		super();
	}

	public RedirectMessageResult(String location) {
		super(location);
	}

	public void setPrependServletContext(boolean prependServletContext) {
		this.prependServletContext = prependServletContext;
	}

	private static boolean isPathUrl(String url) {
		return (url.indexOf(':') == -1);
	}

	protected void doExecute(String finalLocation, ActionInvocation invocation)
			throws Exception {
		ActionContext ctx = invocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ctx
				.get(ServletActionContext.HTTP_RESPONSE);

		if (isPathUrl(finalLocation)) {
			if (!finalLocation.startsWith("/")) {
				String namespace = invocation.getProxy().getNamespace();
				if ((namespace != null) && (namespace.length() > 0)
						&& (!"/".equals(namespace))) {
					finalLocation = namespace + "/" + finalLocation;
				} else {
					finalLocation = "/" + finalLocation;
				}
			}
			if (prependServletContext && (request.getContextPath() != null)
					&& (request.getContextPath().length() > 0)) {
				finalLocation = request.getContextPath() + finalLocation;
			}
			finalLocation = response.encodeRedirectURL(finalLocation);
		}

		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");

		PrintWriter out = response.getWriter();
		StringBuffer buffer = new StringBuffer();
		String message = ((CoreAction) invocation.getAction()).getMessage();
		buffer.append("<script type=\"text/javascript\">");
		buffer.append("alert('" + message + "');");
		buffer.append("location='" + finalLocation + "';");
		buffer.append("</script>");
		String s = buffer.toString();
		if (log.isDebugEnabled()) {
			log.debug(s);
		}
		out.println(s);
		out.flush();
		out.close();

	}
}