下面列出了怎么用javax.servlet.jsp.tagext.BodyContent的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Perform a RequestDispatcher.include() operation, with optional flushing
* of the response beforehand.
*
* @param request The servlet request we are processing
* @param response The servlet response we are processing
* @param relativePath The relative path of the resource to be included
* @param out The Writer to whom we are currently writing
* @param flush Should we flush before the include is processed?
*
* @exception IOException if thrown by the included servlet
* @exception ServletException if thrown by the included servlet
*/
public static void include(ServletRequest request,
ServletResponse response,
String relativePath,
JspWriter out,
boolean flush)
throws IOException, ServletException {
if (flush && !(out instanceof BodyContent))
out.flush();
// FIXME - It is tempting to use request.getRequestDispatcher() to
// resolve a relative path directly, but Catalina currently does not
// take into account whether the caller is inside a RequestDispatcher
// include or not. Whether Catalina *should* take that into account
// is a spec issue currently under review. In the mean time,
// replicate Jasper's previous behavior
String resourcePath = getContextRelativePath(request, relativePath);
RequestDispatcher rd = request.getRequestDispatcher(resourcePath);
rd.include(request,
new ServletResponseWrapperInclude(response, out));
}
@Override
public int doEndTag() throws JspException {
// Reset optional attribute value
declaringPlugin = null;
extension = null;
// Emit body content
try {
BodyContent currentBodyContent = getBodyContent();
if (currentBodyContent != null) {
if (!navigationDataList.isEmpty()) {
currentBodyContent.writeOut(getPreviousOut());
}
currentBodyContent.clearBody();
}
} catch (IOException e) {
logger.error("Error in ShowNavigationTag.doEndTag: " + e.getMessage(), e);
}
return EVAL_PAGE;
}
/**
* Sets attribute for the pagecontext.
*/
@Override
public int doAfterBody() throws JspException {
BodyContent currentBodyContent = getBodyContent();
if (currentBodyContent != null) {
try {
currentBodyContent.getEnclosingWriter().write(currentBodyContent.getString());
} catch (IOException e) {
logger.error("Error writing body content", e);
}
currentBodyContent.clearBody();
}
Map<String, Object> result = getNextRecord();
if (result != null) {
setResultInPageContext(result);
return EVAL_BODY_BUFFERED;
} else {
return SKIP_BODY;
}
}
/**
* Fill in this method to process the body content of the tag.
* You only need to do this if the tag's BodyContent property
* is set to "JSP" or "tagdependent."
* If the tag's bodyContent is set to "empty," then this method
* will not be called.
*/
private void writeTagBodyContent(JspWriter out, BodyContent bodyContent) throws IOException {
//
// TODO: insert code to write html before writing the body content.
// e.g.:
//
out.println("<p>");
out.println("Sum of " + x + " and " + y + " is " + (x+y));
out.println("<br/>");
//
// write the body content (after processing by the JSP engine) on the output Writer
//
bodyContent.writeOut(out);
out.println("<br/>");
out.println("END of sum");
out.println("</p>");
// clear the body content for the next time through.
bodyContent.clearBody();
}
/**
* This method is called after the JSP engine processes the body content of the tag.
* @return EVAL_BODY_AGAIN if the JSP engine should evaluate the tag body again, otherwise return SKIP_BODY.
* This method is automatically generated. Do not modify this method.
* Instead, modify the methods that this method calls.
*/
public int doAfterBody() throws JspException {
try {
//
// This code is generated for tags whose bodyContent is "JSP"
//
BodyContent bodyContent = getBodyContent();
JspWriter out = bodyContent.getEnclosingWriter();
writeTagBodyContent(out, bodyContent);
} catch (Exception ex) {
handleBodyContentException(ex);
}
if (theBodyShouldBeEvaluatedAgain()) {
return EVAL_BODY_AGAIN;
} else {
return SKIP_BODY;
}
}
/**
* Perform a RequestDispatcher.include() operation, with optional flushing
* of the response beforehand.
*
* @param request The servlet request we are processing
* @param response The servlet response we are processing
* @param relativePath The relative path of the resource to be included
* @param out The Writer to whom we are currently writing
* @param flush Should we flush before the include is processed?
*
* @exception IOException if thrown by the included servlet
* @exception ServletException if thrown by the included servlet
*/
public static void include(ServletRequest request,
ServletResponse response,
String relativePath,
JspWriter out,
boolean flush)
throws IOException, ServletException {
if (flush && !(out instanceof BodyContent))
out.flush();
// FIXME - It is tempting to use request.getRequestDispatcher() to
// resolve a relative path directly, but Catalina currently does not
// take into account whether the caller is inside a RequestDispatcher
// include or not. Whether Catalina *should* take that into account
// is a spec issue currently under review. In the mean time,
// replicate Jasper's previous behavior
String resourcePath = getContextRelativePath(request, relativePath);
RequestDispatcher rd = request.getRequestDispatcher(resourcePath);
rd.include(request,
new ServletResponseWrapperInclude(response, out));
}
@Override
public int doEndTag() throws JspException {
BodyContent body = this.getBodyContent();
String value = body.getString();
URLTag parentTag = null;
try {
Tag tag = this;
do {
tag = tag.getParent();
} while (!(tag instanceof URLTag));
parentTag = (URLTag) tag;
} catch (RuntimeException e) {
throw new JspException("Error nesting parameter in url tag.", e);
}
parentTag.addParameter(this.getName(), value);
return EVAL_PAGE;
}
/**
* Perform a RequestDispatcher.include() operation, with optional flushing
* of the response beforehand.
*
* @param request The servlet request we are processing
* @param response The servlet response we are processing
* @param relativePath The relative path of the resource to be included
* @param out The Writer to whom we are currently writing
* @param flush Should we flush before the include is processed?
*
* @exception IOException if thrown by the included servlet
* @exception ServletException if thrown by the included servlet
*/
public static void include(ServletRequest request,
ServletResponse response,
String relativePath,
JspWriter out,
boolean flush)
throws IOException, ServletException {
if (flush && !(out instanceof BodyContent))
out.flush();
// FIXME - It is tempting to use request.getRequestDispatcher() to
// resolve a relative path directly, but Catalina currently does not
// take into account whether the caller is inside a RequestDispatcher
// include or not. Whether Catalina *should* take that into account
// is a spec issue currently under review. In the mean time,
// replicate Jasper's previous behavior
String resourcePath = getContextRelativePath(request, relativePath);
RequestDispatcher rd = request.getRequestDispatcher(resourcePath);
rd.include(request,
new ServletResponseWrapperInclude(response, out));
}
/**
* Perform a RequestDispatcher.include() operation, with optional flushing
* of the response beforehand.
*
* @param request The servlet request we are processing
* @param response The servlet response we are processing
* @param relativePath The relative path of the resource to be included
* @param out The Writer to whom we are currently writing
* @param flush Should we flush before the include is processed?
*
* @exception IOException if thrown by the included servlet
* @exception ServletException if thrown by the included servlet
*/
public static void include(ServletRequest request,
ServletResponse response,
String relativePath,
JspWriter out,
boolean flush)
throws IOException, ServletException {
if (flush && !(out instanceof BodyContent))
out.flush();
// FIXME - It is tempting to use request.getRequestDispatcher() to
// resolve a relative path directly, but Catalina currently does not
// take into account whether the caller is inside a RequestDispatcher
// include or not. Whether Catalina *should* take that into account
// is a spec issue currently under review. In the mean time,
// replicate Jasper's previous behavior
String resourcePath = getContextRelativePath(request, relativePath);
RequestDispatcher rd = request.getRequestDispatcher(resourcePath);
rd.include(request,
new ServletResponseWrapperInclude(response, out));
}
@Override
public int doEndTag() throws JspException {
BodyContent bodyContent = getBodyContent();
String content = bodyContent.getString();
XmlCompressor compressor = new XmlCompressor();
compressor.setEnabled(enabled);
compressor.setRemoveComments(removeComments);
compressor.setRemoveIntertagSpaces(removeIntertagSpaces);
try {
bodyContent.clear();
bodyContent.append(compressor.compress(content));
bodyContent.writeOut(pageContext.getOut());
} catch (Exception e) {
throw new JspException("Failed to compress xml",e);
}
return super.doEndTag();
}
/**
* Actions after some body has been evaluated.
*/
@Override
public int doAfterBody() throws JspTagException {
// put out the evaluated body
BodyContent body = getBodyContent();
JspWriter out = body.getEnclosingWriter();
try {
out.print( body.getString() );
} catch(IOException ioe) {
throw new NavigatorRuntimeException("Error in IfTag.", ioe);
}
parentChooser.setFoundMatchingWhen();
return SKIP_BODY;
}
/**
* Actions after some body has been evaluated.
*/
@Override
public int doAfterBody() throws JspTagException {
// retrieve parent tag which accepts the result of this operation
ValueAcceptingTagIF acceptingTag = (ValueAcceptingTagIF)
findAncestorWithClass(this, ValueAcceptingTagIF.class);
// get body content which should contain the string we want to set.
BodyContent body = getBodyContent();
String content = body.getString();
// construct new collection which consists of one String entry
// kick it over to the nearest accepting tag
acceptingTag.accept( Collections.singleton(content) );
// reset body contents
body.clearBody();
return SKIP_BODY;
}
/**
* Actions after some body has been evaluated.
*/
@Override
public int doAfterBody() throws JspTagException {
ElementTag elementTag = (ElementTag)
findAncestorWithClass(this, ElementTag.class);
if (elementTag != null) {
// get body content
BodyContent body = getBodyContent();
if (body != null) {
String content = body.getString();
// add this attribute to parent element tag
elementTag.addAttribute(attrName, content);
body.clearBody();
} else {
log.warn("AttributeTag: body content is null!");
}
} else {
log.warn("AttributeTag: no parent element tag found!");
}
// only evaluate body once
return SKIP_BODY;
}
/**
* Actions after some body has been evaluated.
*/
@Override
public int doAfterBody() throws JspTagException {
// put out the evaluated body
BodyContent body = getBodyContent();
JspWriter out = null;
try {
out = body.getEnclosingWriter();
out.print(body.getString());
body.clearBody();
} catch(IOException ioe) {
throw new NavigatorRuntimeException("Error in AssociationTypeLoopTag.", ioe);
}
// test if we have to repeat the body
if (index < assocStore.length) {
// set to next value in list
setVariableValues(assocStore[index]);
index++;
return EVAL_BODY_AGAIN;
} else {
return SKIP_BODY;
}
}
public static JspWriter startBufferedBody(PageContext pageContext, BodyTag tag)
throws JspException {
BodyContent out = pageContext.pushBody();
tag.setBodyContent(out);
tag.doInitBody();
return out;
}
/**
* The user customised the output of the error messages - flush the
* buffered content into the main {@link javax.servlet.jsp.JspWriter}.
*/
protected void flushBufferedBodyContent(BodyContent bodyContent) throws JspException {
try {
bodyContent.writeOut(bodyContent.getEnclosingWriter());
}
catch (IOException ex) {
throw new JspException("Unable to write buffered body content.", ex);
}
}
@Before
public void setup() throws JspException {
pageContext = createNiceMock(PageContext.class);
bodyContent = createNiceMock(BodyContent.class);
request = createNiceMock(ServletRequest.class);
tag = new RegisterInitializationScriptTag();
tag.setPageContext(pageContext);
}
/**
* The user customised the output of the error messages - flush the
* buffered content into the main {@link javax.servlet.jsp.JspWriter}.
*/
protected void flushBufferedBodyContent(BodyContent bodyContent) throws JspException {
try {
bodyContent.writeOut(bodyContent.getEnclosingWriter());
}
catch (IOException ex) {
throw new JspException("Unable to write buffered body content.", ex);
}
}
/**
* {@inheritDoc}
*/
public int doEndTag() throws JspException {
// Make sure there is something in the body for this tag
// to process
BodyContent bc = getBodyContent();
if (bc == null) {
return SKIP_BODY;
}
// Make sure tags are set and valid.
initTags();
String body = bc.getString();
String search = "(" + text + ")"; //add grouping so we can get correct case out
try {
Pattern pattern = Pattern.compile(search,
Pattern.CASE_INSENSITIVE |
Pattern.UNICODE_CASE);
Matcher matcher = pattern.matcher(body);
body = matcher.replaceAll(startTag + "$1" + endTag);
}
catch (PatternSyntaxException e) {
log.warn("highlighting disabled. Invalid pattern [" + search +
"]." + e.getMessage());
}
try {
pageContext.getOut().println(body);
}
catch (IOException ioe) {
throw new JspException("IO error writing to JSP file:", ioe);
}
return EVAL_PAGE;
}
/**
* The user customised the output of the error messages - flush the
* buffered content into the main {@link javax.servlet.jsp.JspWriter}.
*/
protected void flushBufferedBodyContent(BodyContent bodyContent) throws JspException {
try {
bodyContent.writeOut(bodyContent.getEnclosingWriter());
}
catch (IOException ex) {
throw new JspException("Unable to write buffered body content.", ex);
}
}
/**
* Executes a {@link Tag}.
*
* @param context The directive context.
* @param node The main node of the directive.
* @param pageContext The page context.
* @param tag The tag to execute.
* @throws JspException If something goes wrong.
*/
public static void executeTag(InternalContextAdapter context, Node node,
PageContext pageContext, Tag tag) throws JspException
{
int result = tag.doStartTag();
if (tag instanceof BodyTag)
{
BodyTag bodyTag = (BodyTag) tag;
BodyContent bodyContent = new VelocityBodyContent(
pageContext.getOut(), (ASTBlock) node.jjtGetChild(1),
context);
switch (result)
{
case BodyTag.EVAL_BODY_BUFFERED:
bodyTag.setBodyContent(bodyContent);
bodyTag.doInitBody();
case BodyTag.EVAL_BODY_INCLUDE:
bodyContent.getString();
default:
break;
}
while (bodyTag.doAfterBody() == BodyTag.EVAL_BODY_AGAIN) {
bodyContent.getString();
}
}
tag.doEndTag();
}
/**
* The user customised the output of the error messages - flush the
* buffered content into the main {@link javax.servlet.jsp.JspWriter}.
*/
protected void flushBufferedBodyContent(BodyContent bodyContent) throws JspException {
try {
bodyContent.writeOut(bodyContent.getEnclosingWriter());
}
catch (IOException e) {
throw new JspException("Unable to write buffered body content.", e);
}
}
@Override
public int doEndTag() {
if (isOverrided()) {
return EVAL_PAGE;
}
BodyContent b = getBodyContent();
String newName = BLOCK + name;
pageContext.getRequest().setAttribute(newName, b.getString());
return EVAL_PAGE;
}
/**
* {@inheritDoc}
*/
public int doEndTag() throws JspException {
// Make sure there is something in the body for this tag
// to process
BodyContent bc = getBodyContent();
if (bc == null) {
return SKIP_BODY;
}
// Make sure tags are set and valid.
initTags();
String body = bc.getString();
String search = "(" + text + ")"; //add grouping so we can get correct case out
try {
Pattern pattern = Pattern.compile(search,
Pattern.CASE_INSENSITIVE |
Pattern.UNICODE_CASE);
Matcher matcher = pattern.matcher(body);
body = matcher.replaceAll(startTag + "$1" + endTag);
}
catch (PatternSyntaxException e) {
log.warn("highlighting disabled. Invalid pattern [" + search +
"]." + e.getMessage());
}
try {
pageContext.getOut().println(body);
}
catch (IOException ioe) {
throw new JspException("IO error writing to JSP file:", ioe);
}
return EVAL_PAGE;
}
@Override
public int doEndTag() throws JspException {
if(!isCondition())
return EVAL_PAGE;
if(hasChildPageOverride(name))
return EVAL_PAGE;
BodyContent content = getBodyContent();
OverrideBody override = new OverrideBody(name, content);
this.pageContext.getRequest().setAttribute(getOverrideName(name), override);
return EVAL_PAGE;
}
@Override
public int doEndTag() throws JspException {
BodyContent bodyContent = getBodyContent();
String content = bodyContent.getString();
try {
if(enabled) {
//call YUICompressor
YuiCssCompressor compressor = new YuiCssCompressor();
compressor.setLineBreak(yuiCssLineBreak);
String result = compressor.compress(content);
bodyContent.clear();
bodyContent.append(result);
bodyContent.writeOut(pageContext.getOut());
} else {
bodyContent.clear();
bodyContent.append(content);
bodyContent.writeOut(pageContext.getOut());
}
} catch (Exception e) {
throw new JspException("Failed to compress css",e);
}
return super.doEndTag();
}
@Override
public BodyContent pushBody() {
JspWriter previous = out;
writerStack.push(out);
out = new FakeBodyContent(previous);
return (BodyContent) out;
}
@Override
public int doEndTag() throws JspException {
BodyContent bc = getBodyContent();
if (bc != null) {
try {
NormalizeWhitespaceWriter nww = new NormalizeWhitespaceWriter(getBodyContent().getEnclosingWriter());
bc.writeOut(nww);
// make sure orphaned whitespace is flushed
nww.done();
} catch (IOException e) {
throw new JspException(e);
}
}
return EVAL_PAGE;
}
/**
* Print the body content to the enclosing writer.
* Return SKIP_BODY by default.
*/
@Override
public int doAfterBody() throws JspTagException {
// put out the evaluated body
try {
BodyContent body = getBodyContent();
body.getEnclosingWriter().print( body.getString() );
} catch (IOException ioe) {
throw new NavigatorRuntimeException("Error in QueryExecutingTag.", ioe);
}
// Skip the body by default.
return SKIP_BODY;
}
/**
* Actions after some body has been evaluated.
*/
@Override
public int doAfterBody() throws JspTagException {
BodyContent body = getBodyContent();
StringBuilder complElem = new StringBuilder(100);
complElem.append("<").append(elemName);
// put in attribute-value pairs
Iterator it = attrnames.iterator();
String key, val;
while (it.hasNext()) {
key = (String) it.next();
val = (String) attrs.get(key);
complElem.append(" ").append(key).append("='").append(val).append("'");
}
complElem.append(">");
// append body content
complElem.append( body.getString() );
complElem.append("</").append(elemName).append(">");
// write it out
try {
JspWriter out = body.getEnclosingWriter();
out.print( complElem.toString() );
body.clearBody();
} catch (IOException ioe) {
throw new NavigatorRuntimeException("Error in ElementTag. JspWriter not there.", ioe);
}
// only evaluate body once
return SKIP_BODY;
}