下面列出了怎么用javax.servlet.jsp.JspException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public int doStartTag() throws JspException {
// 在标签开始处出发该方法
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
SSOToken token = SSOHelper.getSSOToken(request);
// 如果 token 或者 name 为空
if (token != null && this.getName() != null && !"".equals(this.getName().trim())) {
boolean result = SSOConfig.getInstance().getAuthorization().isPermitted(token, this.getName());
if (result) {
// 权限验证通过
// 返回此则执行标签body中内容,SKIP_BODY则不执行
return BodyTagSupport.EVAL_BODY_INCLUDE;
}
}
return BodyTagSupport.SKIP_BODY;
}
@Override
public int doEndTag() throws JspException {
try {
String value = this.extractValue();
if (null == value) {
return super.doEndTag();
}
IParameterParentTag parentTag = (IParameterParentTag) findAncestorWithClass(this, IParameterParentTag.class);
parentTag.addParameter(this.getName(), value);
} catch (Throwable t) {
_logger.error("Error closing tag", t);
//ApsSystemUtils.logThrowable(t, this, "doEndTag");
throw new JspException("Error closing tag ", t);
}
return super.doEndTag();
}
public void writeAttribute ( final String name, final Object value, final boolean leadingSpace ) throws JspException
{
final StringBuilder sb = new StringBuilder ();
if ( leadingSpace )
{
sb.append ( ' ' );
}
final String strValue = value == null ? "" : value.toString ();
sb.append ( name ).append ( "=\"" );
sb.append ( this.escaper.escape ( strValue ) );
sb.append ( '"' );
write ( sb.toString () );
}
@Test
public void setHtmlEscapeFalse() throws JspException {
tag.setValue("url/path");
tag.setVar("var");
tag.setHtmlEscape(false);
tag.doStartTag();
Param param = new Param();
param.setName("n me");
param.setValue("v&l=e");
tag.addParam(param);
param = new Param();
param.setName("name");
param.setValue("value2");
tag.addParam(param);
tag.doEndTag();
assertEquals("url/path?n%20me=v%26l%3De&name=value2", context.getAttribute("var"));
}
/**
* Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspUtils#executeSimpleTag(org.apache.velocity.context.InternalContextAdapter, org.apache.velocity.runtime.parser.node.Node, javax.servlet.jsp.PageContext, javax.servlet.jsp.tagext.SimpleTag)}.
* @throws IOException If something goes wrong.
* @throws JspException If something goes wrong.
*/
@Test
public void testExecuteSimpleTag() throws JspException, IOException
{
InternalContextAdapter context = createMock(InternalContextAdapter.class);
Node node = createMock(Node.class);
PageContext pageContext = createMock(PageContext.class);
SimpleTag tag = createMock(SimpleTag.class);
ASTBlock block = createMock(ASTBlock.class);
tag.setJspBody(isA(VelocityJspFragment.class));
expect(node.jjtGetChild(1)).andReturn(block);
tag.doTag();
replay(context, node, pageContext, block, tag);
JspUtils.executeSimpleTag(context, node, pageContext, tag);
verify(context, node, pageContext, block, tag);
}
private void setupPageData() throws JspException {
Object d = pageContext.getAttribute(dataSetName);
if (d == null) {
d = pageContext.getRequest().getAttribute(dataSetName);
}
if (d == null) {
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
d = request.getSession(true).getAttribute(dataSetName);
}
if (d != null) {
if (d instanceof List) {
pageData = (List) d;
}
else {
throw new JspException("Dataset named \'" + dataSetName +
"\' is incompatible." +
" Must be an an instance of java.util.List.");
}
}
else {
pageData = Collections.EMPTY_LIST;
}
}
@Test
@SuppressWarnings("serial")
public void themeTag() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
ThemeTag tag = new ThemeTag() {
@Override
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("themetest");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
assertEquals("theme test message", message.toString());
}
protected void writeStartingTd() throws JspException {
ListTagUtil.write(pageContext, "<td");
ListCommand command = ListTagUtil.getCurrentCommand(this, pageContext);
if (styleClass != null ||
(isCurrColumnSorted() && command != ListCommand.COL_HEADER)) {
ListTagUtil.write(pageContext, " class=\"");
if (styleClass != null) {
ListTagUtil.write(pageContext, styleClass);
ListTagUtil.write(pageContext, " ");
}
if (isCurrColumnSorted()) {
ListTagUtil.write(pageContext, "sortedCol");
}
ListTagUtil.write(pageContext, "\"");
}
if (!StringUtils.isBlank(width)) {
ListTagUtil.write(pageContext, " width=\"");
ListTagUtil.write(pageContext, width);
ListTagUtil.write(pageContext, "\"");
}
ListTagUtil.write(pageContext, ">");
}
@Override
public int doStartTag () throws JspException
{
final InputList parent = (InputList)findAncestorWithClass ( this, InputList.class );
if ( parent == null )
{
throw new JspException ( "Missing parent 'inputList' element" );
}
final Object value = parent.getCurrentValue ();
if ( value == null )
{
return Tag.SKIP_BODY;
}
final WriterHelper wh = new WriterHelper ( this.pageContext );
wh.write ( "<input type=\"hidden\"" );
wh.writeAttribute ( "name", parent.getPath () );
wh.writeAttribute ( "value", value );
wh.write ( " />" );
return Tag.SKIP_BODY;
}
@Test
public void messageTagWithCodeAndArguments() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@Override
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments("arg1,arg2");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
assertEquals("Correct message", "test arg1 message arg2", message.toString());
}
private void renderOption(Object value, String label, TagWriter tagWriter) throws JspException {
tagWriter.startTag("option");
writeOptionalAttribute(tagWriter, "id", resolveId());
writeOptionalAttributes(tagWriter);
String renderedValue = getDisplayString(value, getBindStatus().getEditor());
renderedValue = processFieldValue(getSelectTag().getName(), renderedValue, "option");
tagWriter.writeAttribute(VALUE_ATTRIBUTE, renderedValue);
if (isSelected(value)) {
tagWriter.writeAttribute(SELECTED_ATTRIBUTE, SELECTED_ATTRIBUTE);
}
if (isDisabled()) {
tagWriter.writeAttribute(DISABLED_ATTRIBUTE, "disabled");
}
tagWriter.appendValue(label);
tagWriter.endTag();
}
/**
* {@inheritDoc}
*/
@Override
public int doStartTag() throws JspException {
JspWriter out = null;
try {
StringBuffer buf = new StringBuffer();
out = pageContext.getOut();
HtmlTag baseTag = new HiddenInputTag();
if (!StringUtils.isBlank(getId())) {
baseTag.setAttribute("id", getId());
}
baseTag.setAttribute("name", getName());
baseTag.setAttribute("value", StringEscapeUtils.escapeHtml4(getValue()));
buf.append(baseTag.render());
out.print(buf.toString());
return SKIP_BODY;
}
catch (Exception e) {
throw new JspException("Error writing to JSP file:", e);
}
}
@Override
public int doStartTag () throws JspException
{
final Object item = this.item;
final TableExtension extension = getExtension ();
if ( item == null || extension == null )
{
return Tag.SKIP_BODY;
}
this.descriptor = extension.geTableDescriptor ();
this.providers = new LinkedList<> ( extension.getProviders ( this.start, this.end ) );
return pollNext ();
}
@Test
public void messageWithVar() throws JspException {
PageContext pc = createPageContext();
MessageTag tag = new MessageTag();
tag.setPageContext(pc);
tag.setText("text & text");
tag.setVar("testvar");
tag.doStartTag();
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
assertEquals("text & text", pc.getAttribute("testvar"));
tag.release();
// try to reuse
tag.setPageContext(pc);
tag.setCode("test");
tag.setVar("testvar");
tag.doStartTag();
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
assertEquals("Correct message", "test message", pc.getAttribute("testvar"));
}
/**
* {@inheritDoc}
*/
@Override
public int doStartTag() throws JspException {
ListCommand command = ListTagUtil.getCurrentCommand(this, pageContext);
ListTag parent = (ListTag) BodyTagSupport.findAncestorWithClass(this,
ListTag.class);
listName = parent.getUniqueName();
int retval = BodyTagSupport.SKIP_BODY;
setupRhnSet();
if (command.equals(ListCommand.ENUMERATE)) {
parent.addColumn();
retval = BodyTagSupport.EVAL_PAGE;
}
else if (command.equals(ListCommand.COL_HEADER)) {
renderHeader(parent);
retval = BodyTagSupport.EVAL_PAGE;
}
else if (command.equals(ListCommand.RENDER)) {
renderCheckbox();
}
return retval;
}
@Override
public int doEndTag() throws JspException {
Param param = new Param();
param.setName(this.name);
if (this.valueSet) {
param.setValue(this.value);
}
else if (getBodyContent() != null) {
// Get the value from the tag body
param.setValue(getBodyContent().getString().trim());
}
// Find a param aware ancestor
ParamAware paramAwareTag = (ParamAware) findAncestorWithClass(this, ParamAware.class);
if (paramAwareTag == null) {
throw new JspException("The param tag must be a descendant of a tag that supports parameters");
}
paramAwareTag.addParam(param);
return EVAL_PAGE;
}
@Test
public void bindTagWithMappedProperties() throws JspException {
PageContext pc = createPageContext();
IndexedTestBean tb = new IndexedTestBean();
Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult();
errors.rejectValue("map[key1]", "code1", "message1");
errors.rejectValue("map[key1]", "code2", "message2");
pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);
BindTag tag = new BindTag();
tag.setPageContext(pc);
tag.setPath("tb.map[key1]");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
assertTrue("Has status variable", status != null);
assertTrue("Correct expression", "map[key1]".equals(status.getExpression()));
assertTrue("Value is TestBean", status.getValue() instanceof TestBean);
assertTrue("Correct value", "name4".equals(((TestBean) status.getValue()).getName()));
assertTrue("Correct isError", status.isError());
assertTrue("Correct errorCodes", status.getErrorCodes().length == 2);
assertTrue("Correct errorMessages", status.getErrorMessages().length == 2);
assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0]));
assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1]));
assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessages()[0]));
assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1]));
}
public void testEmptyAcl() {
boolean flag = false;
try {
// set test condition
rt.setAcl("");
// we don't expect this to work
tth.assertDoStartTag(-1);
flag = true;
}
catch (JspException e) {
assertFalse(flag);
}
catch (Exception e1) {
fail(e1.toString());
}
}
protected void evalValue() throws JspException {
if (this.getVar() != null) {
this.pageContext.setAttribute(this.getVar(), this.getValue());
} else {
try {
if (this.getEscapeXml()) {
out(this.pageContext, this.getEscapeXml(), this.getValue());
} else {
this.pageContext.getOut().print(this.getValue());
}
} catch (IOException e) {
_logger.error("error in doEndTag", e);
throw new JspException("Error closing tag ", e);
}
}
}
public void testMiscAcl() {
try {
// setup mock objects
String output = "<div class=\"spacewalk-toolbar-h1\">" +
"<div class=\"spacewalk-toolbar\"><a href=\"misc-url\">" +
"<img src=\"/img/foo.gif\" alt=\"ignore me\" title=\"ignore me\" />" +
"ignore me</a></div><h1></h1></div>";
setupMiscTag("h1", "misc-url", "true_test()", "jsp.testMessage",
"jsp.testMessage", "foo.gif");
verifyTag(output);
}
catch (JspException e) {
fail(e.toString());
}
}
@Override
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
WebApplicationContext wac = ApsWebApplicationUtils.getWebApplicationContext(request);
List<PluginSubMenuContainer> containters = new ArrayList<PluginSubMenuContainer>();
ValueStack stack = this.getStack();
try {
String[] beanNames = wac.getBeanNamesForType(PluginSubMenuContainer.class);
for (int i=0; i<beanNames.length; i++) {
PluginSubMenuContainer container = (PluginSubMenuContainer) wac.getBean(beanNames[i]);
containters.add(container);
}
if (containters.size()>0) {
stack.getContext().put(this.getObjectName(), containters);
stack.setValue("#attr['" + this.getObjectName() + "']", containters, false);
return EVAL_BODY_INCLUDE;
}
} catch (Throwable t) {
throw new JspException("Error creating the plugins menu list", t);
}
return super.doStartTag();
}
@Override
public int doEndTag() throws JspException {
Object argument = null;
if (this.valueSet) {
argument = this.value;
}
else if (getBodyContent() != null) {
// Get the value from the tag body
argument = getBodyContent().getString().trim();
}
// Find a param-aware ancestor
ArgumentAware argumentAwareTag = (ArgumentAware) findAncestorWithClass(this, ArgumentAware.class);
if (argumentAwareTag == null) {
throw new JspException("The argument tag must be a descendant of a tag that supports arguments");
}
argumentAwareTag.addArgument(argument);
return EVAL_PAGE;
}
@Test
public void createUrlWithParams() throws JspException {
tag.setValue("url/path");
tag.doStartTag();
Param param = new Param();
param.setName("name");
param.setValue("value");
tag.addParam(param);
param = new Param();
param.setName("n me");
param.setValue("v lue");
tag.addParam(param);
String uri = tag.createUrl();
assertEquals("url/path?name=value&n%20me=v%20lue", uri);
}
@Test
public void bindTagWithMappedProperties() throws JspException {
PageContext pc = createPageContext();
IndexedTestBean tb = new IndexedTestBean();
Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult();
errors.rejectValue("map[key1]", "code1", "message1");
errors.rejectValue("map[key1]", "code2", "message2");
pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);
BindTag tag = new BindTag();
tag.setPageContext(pc);
tag.setPath("tb.map[key1]");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
assertTrue("Has status variable", status != null);
assertTrue("Correct expression", "map[key1]".equals(status.getExpression()));
assertTrue("Value is TestBean", status.getValue() instanceof TestBean);
assertTrue("Correct value", "name4".equals(((TestBean) status.getValue()).getName()));
assertTrue("Correct isError", status.isError());
assertTrue("Correct errorCodes", status.getErrorCodes().length == 2);
assertTrue("Correct errorMessages", status.getErrorMessages().length == 2);
assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0]));
assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1]));
assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessages()[0]));
assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1]));
}
/**
* Close the current tag, allowing to enforce a full closing tag.
* <p>Correctly writes an empty tag if no inner text or nested tags
* have been written.
* @param enforceClosingTag whether a full closing tag should be
* rendered in any case, even in case of a non-block tag
*/
public void endTag(boolean enforceClosingTag) throws JspException {
if (!inTag()) {
throw new IllegalStateException("Cannot write end of tag. No open tag available.");
}
boolean renderClosingTag = true;
if (!currentState().isBlockTag()) {
// Opening tag still needs to be closed...
if (enforceClosingTag) {
this.writer.append(">");
}
else {
this.writer.append("/>");
renderClosingTag = false;
}
}
if (renderClosingTag) {
this.writer.append("</").append(currentState().getTagName()).append(">");
}
this.tagState.pop();
}
@Override
public int doAfterBody() throws JspException {
try {
String s = bodyOut.getString();
System.err.println(s);
if (toBrowser)
bodyOut.writeOut(bodyOut.getEnclosingWriter());
return SKIP_BODY;
} catch (IOException ex) {
throw new JspTagException(ex.toString());
}
}
public int doEndTag() throws JspException {
try{
JspWriter out = pageContext.getOut();
out.print(DESUtil.encryptParamKey(BasicUtil.nvl(value,body,"").toString()));
}catch(Exception e){
e.printStackTrace();
}finally{
release();
}
return EVAL_PAGE;
}
@Test
public void createUrlRemoteContextSingleSlash() throws JspException {
((MockHttpServletRequest) context.getRequest())
.setContextPath("/app-context");
tag.setValue("/url/path");
tag.setContext("/");
tag.doStartTag();
String uri = invokeCreateUrl(tag);
assertEquals("/url/path", uri);
}
@Test
public void createQueryStringNoParams() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
String queryString = tag.createQueryString(params, usedParams, true);
assertEquals("", queryString);
}
@Override
public int doStartTag() throws JspException {
HttpSession session = this.pageContext.getSession();
try {
boolean isAuthorized = false;
UserDetails currentUser = (UserDetails) session.getAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER);
IAuthorizationManager authManager = (IAuthorizationManager) ApsWebApplicationUtils.getBean(SystemConstants.AUTHORIZATION_SERVICE, this.pageContext);
boolean isGroupSetted = StringUtils.isNotEmpty(this.getGroupName());
boolean isPermissionSetted = StringUtils.isNotEmpty(this.getPermission());
boolean isAuthGr = isGroupSetted && (authManager.isAuthOnGroup(currentUser, this.getGroupName()) || authManager.isAuthOnGroup(currentUser, Group.ADMINS_GROUP_NAME));
boolean isAuthPerm = isPermissionSetted && (authManager.isAuthOnPermission(currentUser, this.getPermission()) || authManager.isAuthOnPermission(currentUser, Permission.SUPERUSER));
if (isGroupSetted && !isPermissionSetted) {
isAuthorized = isAuthGr;
} else if (!isGroupSetted && isPermissionSetted) {
isAuthorized = isAuthPerm;
} else if (isGroupSetted && isPermissionSetted && isAuthGr && isAuthPerm) {
isAuthorized = authManager.isAuthOnGroupAndPermission(currentUser, this.getGroupName(), this.getPermission(), true);
}
if (null != this.getVar()) {
this.pageContext.setAttribute(this.getVar(), isAuthorized);
}
if (isAuthorized) {
return EVAL_BODY_INCLUDE;
} else {
return SKIP_BODY;
}
} catch (Throwable t) {
_logger.error("Error during tag initialization", t);
throw new JspException("Error during tag initialization ", t);
}
}