下面列出了怎么用javax.servlet.jsp.PageContext的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void messageWithVarAndScope() throws JspException {
PageContext pc = createPageContext();
MessageTag tag = new MessageTag();
tag.setPageContext(pc);
tag.setText("text & text");
tag.setVar("testvar");
tag.setScope("page");
tag.doStartTag();
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
assertEquals("text & text", pc.getAttribute("testvar"));
tag.release();
tag = new MessageTag();
tag.setPageContext(pc);
tag.setCode("test");
tag.setVar("testvar2");
tag.doStartTag();
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
assertEquals("Correct message", "test message", pc.getAttribute("testvar2"));
tag.release();
}
public static void handleSetPropertyExpression(Object bean,
String prop, String expression, PageContext pageContext,
ProtectedFunctionMapper functionMapper )
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] {
PageContextImpl.proprietaryEvaluate(
expression,
method.getParameterTypes()[0],
pageContext,
functionMapper)
});
} catch (Exception ex) {
Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex);
ExceptionUtils.handleThrowable(thr);
throw new JasperException(ex);
}
}
/**
* Clears the stored {@link TagWriter}.
*/
@Override
public void doFinally() {
super.doFinally();
this.pageContext.removeAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
if (this.previousNestedPath != null) {
// Expose previous nestedPath value.
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME, this.previousNestedPath, PageContext.REQUEST_SCOPE);
}
else {
// Remove exposed nestedPath value.
this.pageContext.removeAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
}
this.tagWriter = null;
this.previousNestedPath = null;
}
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
PageContext pc = createPageContext();
RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
assertEquals("theme test message", rc.getThemeMessage("themetest"));
assertEquals("theme test message", rc.getThemeMessage("themetest", (String[]) null));
assertEquals("theme test message", rc.getThemeMessage("themetest", "default"));
assertEquals("theme test message", rc.getThemeMessage("themetest", (Object[]) null, "default"));
assertEquals("theme test message arg1",
rc.getThemeMessage("themetestArgs", new String[] {"arg1"}));
assertEquals("theme test message arg1",
rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] {"arg1"})));
assertEquals("default", rc.getThemeMessage("themetesta", "default"));
assertEquals("default", rc.getThemeMessage("themetesta", (List) null, "default"));
MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"themetest"});
assertEquals("theme test message", rc.getThemeMessage(resolvable));
}
@Test
public void testDoEndTagSessionScope() throws Exception {
this.context.setAttribute("otherAttribute03", "lostValue03", PageContext.PAGE_SCOPE);
this.context.setAttribute("coolAttribute01", "weirdValue01", PageContext.SESSION_SCOPE);
this.context.setAttribute("testAttribute02", "testValue02", PageContext.SESSION_SCOPE);
this.tag.setScope("session");
final int returnValue = this.tag.doEndTag();
assertEquals("The return value is not correct.", Tag.EVAL_PAGE, returnValue);
this.writer.flush();
final String output = new String(this.output.toByteArray(), UTF8);
assertEquals("The output is not correct.",
"<dl>" +
"<dt><code>coolAttribute01</code></dt><dd><code>weirdValue01</code></dd>" +
"<dt><code>testAttribute02</code></dt><dd><code>testValue02</code></dd>" +
"</dl>", output);
}
public PageContext getPageContext(Servlet servlet,
ServletRequest request,
ServletResponse response,
String errorPageURL,
boolean needsSession,
int bufferSize,
boolean autoflush) {
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedGetPageContext dp =
new PrivilegedGetPageContext(
this, servlet, request, response, errorPageURL,
needsSession, bufferSize, autoflush);
return AccessController.doPrivileged(dp);
} else {
return internalGetPageContext(servlet, request, response,
errorPageURL, needsSession,
bufferSize, autoflush);
}
}
public void setUp() throws Exception {
super.setUp();
setImposteriser(ClassImposteriser.INSTANCE);
RhnBaseTestCase.disableLocalizationServiceLogging();
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
context = mock(PageContext.class);
writer = new RhnMockJspWriter();
ldt = new UnpagedListDisplayTag();
lt = new ListTag();
ldt.setPageContext(context);
ldt.setParent(lt);
lt.setPageList(new DataResult(CSVWriterTest.getTestListOfMaps()));
context().checking(new Expectations() { {
atLeast(1).of(context).getOut();
will(returnValue(writer));
atLeast(1).of(context).getRequest();
will(returnValue(request));
atLeast(1).of(context).setAttribute("current", null);
} });
}
@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());
}
@Test
public void messageTagWithCodeAndArgumentAndNestedArgument() 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");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
tag.setArguments(5);
tag.addArgument(7);
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
assertEquals("Correct message", "test 5 message 7", message.toString());
}
@Test
public void messageTagWithCodeAndStringArgumentWithCustomSeparator() 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,1;arg2,2");
tag.setArgumentSeparator(";");
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,1 message arg2,2", message.toString());
}
@Test
public void testDoEndTagStringVarRequestScope() throws Exception {
this.tag.setLogger("testDoEndTagStringVarRequestScope");
this.tag.setVar("goodbyeCruelWorld");
this.tag.setScope("request");
assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context));
assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag());
assertNull("The default logger should still be null.", TagUtils.getDefaultLogger(this.context));
final Object attribute = this.context.getAttribute("goodbyeCruelWorld", PageContext.REQUEST_SCOPE);
assertNotNull("The attribute should not be null.", attribute);
assertTrue("The attribute should be a Log4jTaglibLogger.", attribute instanceof Log4jTaglibLogger);
final Log4jTaglibLogger logger = (Log4jTaglibLogger)attribute;
assertEquals("The logger name is not correct.", "testDoEndTagStringVarRequestScope", logger.getName());
}
/**
* Renders a dynamic field label
*
* @param pageContext the page context to render to
* @param parentTag the parent tag requesting this rendering
* @param accountingLine the line which owns the field being rendered
* @param accountingLinePropertyPath the path from the form to the accounting line
*/
protected void renderDynamicNameLabel(PageContext pageContext, Tag parentTag, AccountingLineRenderingContext renderingContext) throws JspException {
AccountingLine accountingLine = renderingContext.getAccountingLine();
String accountingLinePropertyPath = renderingContext.getAccountingLinePropertyPath();
DynamicNameLabelRenderer renderer = new DynamicNameLabelRenderer();
if (definition.getDynamicNameLabelGenerator() != null) {
renderer.setFieldName(definition.getDynamicNameLabelGenerator().getDynamicNameLabelFieldName(accountingLine, accountingLinePropertyPath));
renderer.setFieldValue(definition.getDynamicNameLabelGenerator().getDynamicNameLabelValue(accountingLine, accountingLinePropertyPath));
}
else {
if (!StringUtils.isBlank(getField().getPropertyValue())) {
if (getField().isSecure()) {
renderer.setFieldValue(getField().getDisplayMask().maskValue(getField().getPropertyValue()));
}
else {
renderer.setFieldValue(getDynamicNameLabelDisplayedValue(accountingLine));
}
}
renderer.setFieldName(accountingLinePropertyPath + "." + definition.getDynamicLabelProperty());
}
renderer.render(pageContext, parentTag);
renderer.clear();
}
@Test
public void testDoEndTagLoggerVarSessionScope() throws Exception {
this.tag.setLogger(LogManager.getLogger("testDoEndTagLoggerVarSessionScope"));
this.tag.setVar("helloWorld");
this.tag.setScope("session");
assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context));
assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag());
assertNull("The default logger should still be null.", TagUtils.getDefaultLogger(this.context));
final Object attribute = this.context.getAttribute("helloWorld", PageContext.SESSION_SCOPE);
assertNotNull("The attribute should not be null.", attribute);
assertTrue("The attribute should be a Log4jTaglibLogger.", attribute instanceof Log4jTaglibLogger);
final Log4jTaglibLogger logger = (Log4jTaglibLogger)attribute;
assertEquals("The logger name is not correct.", "testDoEndTagLoggerVarSessionScope", logger.getName());
}
@Test
public void testDoEndTagDefaultPageScope() throws Exception {
this.context.setAttribute("testAttribute01", "testValue01", PageContext.PAGE_SCOPE);
this.context.setAttribute("anotherAttribute02", "finalValue02", PageContext.PAGE_SCOPE);
this.context.setAttribute("badAttribute03", "skippedValue03", PageContext.SESSION_SCOPE);
final int returnValue = this.tag.doEndTag();
assertEquals("The return value is not correct.", Tag.EVAL_PAGE, returnValue);
this.writer.flush();
final String output = new String(this.output.toByteArray(), UTF8);
assertEquals("The output is not correct.",
"<dl>" +
"<dt><code>testAttribute01</code></dt><dd><code>testValue01</code></dd>" +
"<dt><code>anotherAttribute02</code></dt><dd><code>finalValue02</code></dd>" +
"</dl>", output);
}
@Test
public void escapeBodyWithHtmlEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {
@Override
protected String readBodyContent() {
return "test & text";
}
@Override
protected void writeBodyContent(String content) {
result.append(content);
}
};
tag.setPageContext(pc);
tag.setHtmlEscape(true);
assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag());
assertEquals(Tag.SKIP_BODY, tag.doAfterBody());
assertEquals("test & text", result.toString());
}
public JspContextWrapper(JspContext jspContext,
ArrayList<String> nestedVars, ArrayList<String> atBeginVars,
ArrayList<String> atEndVars, Map<String,String> aliases) {
this.invokingJspCtxt = (PageContext) jspContext;
if (jspContext instanceof JspContextWrapper) {
rootJspCtxt = ((JspContextWrapper)jspContext).rootJspCtxt;
}
else {
rootJspCtxt = invokingJspCtxt;
}
this.nestedVars = nestedVars;
this.atBeginVars = atBeginVars;
this.atEndVars = atEndVars;
this.pageAttributes = new HashMap<String, Object>(16);
this.aliases = aliases;
if (nestedVars != null) {
this.originalNestedVars = new HashMap<String, Object>(nestedVars.size());
}
syncBeginTagFile();
}
public int doEndTag() throws JspException {
// Rewrite and encode the url.
String result = formatUrl();
// Store or print the output
if (var != null)
pageContext.setAttribute(var, result, PageContext.PAGE_SCOPE);
else {
try {
pageContext.getOut().print(result);
} catch (IOException x) {
throw new JspTagException(x);
}
}
return EVAL_PAGE;
}
/**
* Renders the show/hide button
* @param pageContext the page context to render to
* @param parentTag the tag requesting all this rendering
* @throws JspException thrown under terrible circumstances when the rendering failed and had to be left behind like so much refuse
*/
protected void renderHideDetails(PageContext pageContext, Tag parentTag) throws JspException {
hideStateTag.setPageContext(pageContext);
hideStateTag.setParent(parentTag);
hideStateTag.doStartTag();
hideStateTag.doEndTag();
String toggle = hideDetails ? "show" : "hide";
showHideTag.setPageContext(pageContext);
showHideTag.setParent(parentTag);
showHideTag.setProperty("methodToCall."+toggle+"Details");
showHideTag.setSrc(SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString("kr.externalizable.images.url")+"det-"+toggle+".gif");
showHideTag.setAlt(toggle+" transaction details");
showHideTag.setTitle(toggle+" transaction details");
showHideTag.doStartTag();
showHideTag.doEndTag();
}
public void setUp() throws Exception {
super.setUp();
setImposteriser(ClassImposteriser.INSTANCE);
RhnBaseTestCase.disableLocalizationServiceLogging();
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
context = mock(PageContext.class);
writer = new RhnMockJspWriter();
ldt = new UnpagedListDisplayTag();
lt = new ListTag();
ldt.setPageContext(context);
ldt.setParent(lt);
lt.setPageList(new DataResult(CSVWriterTest.getTestListOfMaps()));
context().checking(new Expectations() { {
atLeast(1).of(context).getOut();
will(returnValue(writer));
atLeast(1).of(context).getRequest();
will(returnValue(request));
atLeast(1).of(context).setAttribute("current", null);
} });
}
@Override
public void doTag() throws JspException {
PageContext pageContext = (PageContext) super.getJspContext();
HttpSession httpSession = pageContext.getSession();
MessageReader messageReader = null;
if (httpSession != null) {
Object temp = httpSession
.getAttribute(Constants.SESSION_LOCALE);
if (temp != null) {
messageReader = new MessageReader(temp.toString());
} else {
messageReader = new MessageReader(null);
}
} else {
messageReader = new MessageReader(null);
}
pageContext.setAttribute(Constants.PAGE_CONTEXT_MESSAGES,
messageReader, PageContext.PAGE_SCOPE);
}
@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());
}
/**
* Method generateTimeTable.
*
* @param startTimeTableHour
*
* @param listaAulas
* @return TimeTable
*/
private TimeTable generateTimeTable(List lessonList, Locale locale, PageContext pageContext, Integer startTimeTableHour) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, startTimeTableHour.intValue());
calendar.set(Calendar.MINUTE, 0);
Integer numberOfDays = new Integer(6);
Integer numberOfHours =
new Integer((endTimeTableHour.intValue() - startTimeTableHour.intValue()) * (60 / slotSizeMinutes.intValue()));
TimeTable timeTable = new TimeTable(numberOfHours, numberOfDays, calendar, slotSizeMinutes, locale, pageContext);
Iterator lessonIterator = lessonList.iterator();
while (lessonIterator.hasNext()) {
InfoShowOccupation infoShowOccupation = (InfoShowOccupation) lessonIterator.next();
timeTable.addLesson(infoShowOccupation);
}
return timeTable;
}
public static List<String> errors ( final PageContext pageContext, final String command, final String path, final boolean local )
{
final BindingResult br = (BindingResult)pageContext.getRequest ().getAttribute ( BindingResult.ATTRIBUTE_NAME );
if ( br == null )
{
return Collections.emptyList ();
}
BindingResult result = br.getChild ( command );
if ( result == null )
{
return Collections.emptyList ();
}
if ( path != null && !path.isEmpty () )
{
result = result.getChild ( path );
if ( result == null )
{
return Collections.emptyList ();
}
}
return ( local ? result.getLocalErrors () : result.getErrors () ).stream ().map ( err -> err.getMessage () ).collect ( Collectors.toList () );
}
@Test
public void bindTagWithToStringAndHtmlEscaping() throws JspException {
PageContext pc = createPageContext();
BindTag tag = new BindTag();
tag.setPageContext(pc);
tag.setPath("tb.doctor");
tag.setHtmlEscape(true);
TestBean tb = new TestBean("somebody", 99);
NestedTestBean ntb = new NestedTestBean("juergen&eva");
tb.setDoctor(ntb);
pc.getRequest().setAttribute("tb", tb);
tag.doStartTag();
BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
assertEquals("doctor", status.getExpression());
assertTrue(status.getValue() instanceof NestedTestBean);
assertTrue(status.getDisplayValue().contains("juergen&eva"));
}
@Test
public void messageTagWithText() 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.setText("test & text é");
tag.setHtmlEscape(true);
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
assertTrue("Correct message", message.toString().startsWith("test & text &"));
}
@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"));
}
/**
* Utility methods
* taken from org.apache.taglibs.standard.tag.common.core.UrlSupport
* @param url The URL
* @param context The context
* @param pageContext The page context
* @return the absolute URL
* @throws JspException If the URL doesn't start with '/'
*/
public static String resolveUrl(
String url, String context, PageContext pageContext)
throws JspException {
// don't touch absolute URLs
if (isAbsoluteUrl(url))
return url;
// normalize relative URLs against a context root
HttpServletRequest request =
(HttpServletRequest) pageContext.getRequest();
if (context == null) {
if (url.startsWith("/"))
return (request.getContextPath() + url);
else
return url;
} else {
if (!context.startsWith("/") || !url.startsWith("/")) {
throw new JspTagException(
"In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\".");
}
if (context.equals("/")) {
// Don't produce string starting with '//', many
// browsers interpret this as host name, not as
// path on same host.
return url;
} else {
return (context + url);
}
}
}
public static void setMethodVariable(PageContext pageContext,
String variable,
MethodExpression expression) {
ExpressionFactory expFactory = getExpressionFactory(pageContext);
ValueExpression exp =
expFactory.createValueExpression(expression, Object.class);
setValueVariable(pageContext, variable, exp);
}
public JspFragmentHelper( int discriminator, JspContext jspContext,
JspTag parentTag )
{
this.discriminator = discriminator;
this.jspContext = jspContext;
if(jspContext instanceof PageContext) {
_jspx_page_context = (PageContext)jspContext;
} else {
_jspx_page_context = null;
}
this.parentTag = parentTag;
}
protected void renderUnbound() throws JspException {
ListTag parent = (ListTag)
BodyTagSupport.findAncestorWithClass(this, ListTag.class);
if (attributeName != null) {
Object bean = parent.getCurrentObject();
String value = ListTagUtil.getBeanValue(bean, attributeName);
pageContext.setAttribute("beanValue", value, PageContext.PAGE_SCOPE);
}
writeStartingTd();
}