⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 baseajaxbodytag.java

📁 这是AJAX的一个HTML实现! HTML标签AJAX的实现!
💻 JAVA
字号:
/** * Copyright 2007-2008 Jens Kapitza * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package net.sourceforge.ajaxtags.tags;import static net.sourceforge.ajaxtags.servlets.AjaxActionHelper.trim2Null;import java.io.IOException;import java.io.StringReader;import java.io.StringWriter;import javax.servlet.http.HttpServletRequest;import javax.servlet.jsp.JspException;import javax.servlet.jsp.el.ELException;import javax.servlet.jsp.tagext.BodyContent;import javax.servlet.jsp.tagext.BodyTagSupport;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import net.sourceforge.ajaxtags.helpers.Logger;import org.w3c.dom.Attr;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;/** *  * @author Jens Kapitza * @version $Revision$ $Date: 2007/06/20 20:55:56 $ $Author: jenskapitza $ */abstract class BaseAjaxBodyTag extends BodyTagSupport {    /**     *      */    private static final long serialVersionUID = 1L;    public static final String HEADER_FLAG = "X-Requested-With";    public static final String HEADER_FLAG_VALUE = "XMLHttpRequest";    public BaseAjaxBodyTag() {	super();	release();    }    /**     * detect if the client does a ajax call or not     *      * @return true only if the client send the header with with XMLHttpRequest     */    protected boolean isAjaxRequest() {	HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();	return HEADER_FLAG_VALUE.equalsIgnoreCase(req.getHeader(HEADER_FLAG));    }    protected void out(CharSequence csec) throws JspException {	try {	    pageContext.getOut().append(csec);	} catch (IOException e) {	    throw new JspException(e);	}    }    /**     *      * @return true if the body should be ignored     */    protected boolean skipBody() {	return false;    }    @Override    final public int doStartTag() throws JspException {	initParameters();	return skipBody() ? SKIP_BODY : EVAL_BODY_BUFFERED; // XXX area tag and	// displaytag have	// problems	// with this!    }    @Override    final public void release() {	this.target = null;	this.baseUrl = null;	this.parser = null;	this.preFunction = null;	this.postFunction = null;	this.errorFunction = null;	this.parameters = null;	this.var = null;	this.attachTo = null;	this.source = null;	this.sourceClass = null;	this.eventType = null;	releaseTag();    }    private String source;    private String target;    private String baseUrl;    private String parser;    private String parameters;    private String preFunction;    private String postFunction;    private String errorFunction;    private String var;    private String attachTo;    private String sourceClass;    private String eventType;    final public String getEventType() {	return eventType;    }    final public void setEventType(String eventType) {	this.eventType = trim2Null(eventType);    }    final public String getSourceClass() {	return sourceClass;    }    final public void setSourceClass(String sourceClass) {	this.sourceClass = trim2Null(sourceClass);    }    final public String getSource() {	return source;    }    final public void setSource(String source) {	this.source = trim2Null(source);    }    final public String getVar() {	return var;    }    final public void setVar(String var) {	this.var = trim2Null(var);    }    final public void setAttachTo(String attachTo) {	this.attachTo = trim2Null(attachTo);    }    final public String getAttachTo() {	return attachTo;    }    final protected String getJSVariable() {	StringBuilder script = new StringBuilder();	if (this.var != null) {	    if (this.attachTo != null) {		script.append(this.attachTo).append(".").append(this.var);	    } else {		script.append("var ").append(this.var);	    }	    script.append(" = "); // needed	}	return script.toString();    }    final public String getParameters() {	return parameters;    }    final public void setParameters(String parameters) {	this.parameters = trim2Null(parameters);    }    final public String getErrorFunction() {	return errorFunction;    }    final public void setErrorFunction(String errorFunction) {	this.errorFunction = trim2Null(errorFunction);    }    final public String getPostFunction() {	return postFunction;    }    final public void setPostFunction(String postFunction) {	this.postFunction = trim2Null(postFunction);    }    final public String getPreFunction() {	return preFunction;    }    final public void setPreFunction(String preFunction) {	this.preFunction = trim2Null(preFunction);    }    final public String getParser() {	return parser;    }    final public void setParser(String parser) {	this.parser = trim2Null(parser);    }    final public String getBaseUrl() {	return baseUrl;    }    final public void setBaseUrl(String baseUrl) {	this.baseUrl = trim2Null(baseUrl);    }    /**     * @return Returns the target.     */    final public String getTarget() {	return this.target;    }    /**     * @param target     *            The target to set.     */    final public void setTarget(String target) {	this.target = trim2Null(target);    }    protected void initParameters() throws JspException {    }    /**     * never call release -> ends in loop     */    protected void releaseTag() {    }    /**     * evaluate the given string     *      * @param <T>     * @param obj     * @param clazz     * @return     * @throws ELException     */    @SuppressWarnings("unchecked")    protected <T> T evaluate(String obj, Class<T> clazz) throws ELException {	if (obj == null) {	    return null;	}	return (T) pageContext.getExpressionEvaluator().evaluate(		obj.toString(), clazz, pageContext.getVariableResolver(), null);    }    /**     *      * @return the Optionsbuilder with default options     */    protected OptionsBuilder getOptionsBuilder() {	return getOptionsBuilder(false);    }    protected OptionsBuilder getOptionsBuilder(boolean empty) {	OptionsBuilder builder = OptionsBuilder.getOptionsBuilder();	if (empty) {	    return builder;	}	builder.add("baseUrl", getBaseUrl(), true);	builder.add("parser", getParser(), false);	builder.add("target", getTarget(), true);	builder.add("source", getSource(), true);	builder.add("sourceClass", getSourceClass(), true);	builder.add("eventType", getEventType(), true);	builder.add("parameters", getParameters(), true);	builder.add("preFunction", this.preFunction, false);	builder.add("postFunction", this.postFunction, false);	builder.add("errorFunction", this.errorFunction, false);	// ref for prototype XXX there can be conflics	// change is not save -- double execution?	builder.add("onCreate", this.preFunction, false);	builder.add("onComplete", this.postFunction, false);	builder.add("onFailure", this.errorFunction, false);	return builder;    }    /**     * Helper to define new AJAX updater for onclick attribute.     *      * @param target     *            the target to request     * @param href     *            the url     * @param options     *            the for prototype framework     * @return the javascript code to do ajax update     */    public static final String getOnclickAjax(final String target,	    final String href, final OptionsBuilder opt) {	OptionsBuilder options = opt;	if (options == null) {	    options = OptionsBuilder.getOptionsBuilder(); // use empty here	}	options.add("evalScripts", "true", false);	options.add("requestHeaders", "['" + AjaxAreaTag.TARGET_HEADER		+ "' , ' " + target + "']", false);	StringBuffer onclick = new StringBuffer("new Ajax.Updater('");	onclick.append(target);	onclick.append("', '");	onclick.append(href);	onclick.append("'");	onclick.append(",{");	onclick.append(options.toString());	onclick.append("}");	onclick.append("); return false;");	return onclick.toString();    }    protected String getBody() {	BodyContent bc = this.getBodyContent();	if (bc == null) {	    return null;	}	return bc.getString();    }    protected String ajaxAnchors() {	return ajaxAnchors(getBody(), getTarget());    }    public static Document getDocument(final String html) throws Exception {	if (trim2Null(html) == null) {	    return null;	}	// br -- fixup	String xhtml = trim2Null(html); // .replaceAll("<br(.*?)>", "<br$1/>");	return docBuilder.parse(new InputSource(new StringReader(WARP0 + xhtml		+ WARP1)));    }    private static final String WARP0 = "<x>";    private static final String WARP1 = "</x>";    public static String ajaxAnchors(final String html, final String target) {	try {	    return ajaxAnchors0(html, target);	} catch (Exception e) {	    Logger.error("rewrite links faild < is the content xhtml? >", e);	    Logger.error(html, null);	    Logger.error("params are: [html= " + html + " ],[target= " + target		    + " ]", null);	    return html;	}    }    public static Document rewriteAnchors(Document document, String target) {	return rewriteAnchors(document, target, null);    }    public static Document rewriteAnchors(Document document, String target,	    String className) {	NodeList links = document.getElementsByTagName("a");	for (int i = 0; i < links.getLength(); i++) {	    rewriteLink(links.item(i), target, className);	}	return document;    }    public static void rewriteLink(Node link, String target, String className) {	NamedNodeMap map = link.getAttributes();	Attr href = (Attr) map.getNamedItem("href");	Attr clazz = (Attr) map.getNamedItem("class");	if (className == null || clazz.getValue().contains(className)) {	    Attr onclick = (Attr) map.getNamedItem("onclick");	    if (onclick == null) {		onclick = link.getOwnerDocument().createAttribute("onclick");	    }	    onclick.setValue(getOnclickAjax(target, href.getValue(), null));	    map.setNamedItem(onclick);	    href.setValue("javascript://nop/");	}    }    private static Transformer transformer;    private static DocumentBuilderFactory docFactory = DocumentBuilderFactory	    .newInstance();    private static DocumentBuilder docBuilder;    static {	try {	    transformer = TransformerFactory.newInstance().newTransformer();	    docFactory.setValidating(false);	    docFactory.setIgnoringElementContentWhitespace(true);	    docBuilder = docFactory.newDocumentBuilder();	} catch (Exception e) {	    throw new Error(e);	}    }    public static String toString(Document document) throws Exception {	DOMSource ds = new DOMSource(document);	transformer.setOutputProperty(OutputKeys.METHOD, "html");	StringWriter w = new StringWriter();	transformer.transform(ds, new StreamResult(w));	String xhtml = w.toString();	return xhtml.substring(WARP0.length(), xhtml.length() - WARP1.length());    }    private static String ajaxAnchors0(final String html, final String target)	    throws Exception {	Document document = getDocument(html);	return toString(rewriteAnchors(document, target));    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -