开发者

Why does this JSP scriptlet fail with a NullPointerException?

I can print out开发者_高级运维 pageModel.foo using EL:

${pageModel.foo}

But this scriptlet fails at the line where I check the length() of foo:

java.lang.String foo = (java.lang.String)pageContext.getAttribute("pageModel.foo");
if(foo.length()>10){
    foo = foo.substring(0, 9);
}

It throws a NullPointerException - which doesn't make sense because ${pageModel.foo} works!


There are a couple of problems with the code you posted:

  1. The EL ${pageModel.foo} doesn't load an attribute called "pageModel.foo" - it loads an attribute called "pageModel" and gets it's "foo" property.
  2. pageContext.getAttribute() only loads attributes from the page scope. However, EL can access attributes from many scopes - you should use pageContext.findAttribute() instead.

code:

String foo = "";
PageModel pageModel = (my.package.PageModel)pageContext.findAttribute("pageModel");
if (pageModel != null) {
  foo = pageModel.getFoo();
  if(foo.length()>10){
    foo = foo.substring(0, 9);
  }
}


The answer is already given by Nate, so I won't repeat it.

However, I usually supplement answers with answers which answers what the questioner really needs instead of what the questioner asks. It namely look much like that you're totally unaware of JSTL core tags and functions. You should really prefer it over fiddling with ugly scriptlets.

<c:set var="foo" value="${pageModel.foo}" />
<c:if test="${fn:length(foo) > 10)}">
    <c:set var="foo" value="${fn.substring(foo, 0, 9)}" />
</c:if>
<p>${foo}</p>

or, with the conditional operator ?::

<c:set var="foo" value="${(fn:length(pageModel.foo) > 10) ? fn.substring(pageModel.foo, 0, 9) : pageModel.foo}" />
<p>${foo}</p>

Much better, isn't it?

Keep in mind: whenever you need a scriptlet <% %>, then chances are very big that you're looking for a solution in the wrong direction. Think twice about finding the solution and look in direction of taglibs, EL functions or just servlets/filters.


The attribute is pageModel, not pageModel.foo.

Not that you should be doing that in a scriptlet anyway :(


Try something like:

Map m = (java.util.Map) pageContext.getAttribute("pageModel");
String foo = (String) m.get("foo");
if(foo.length()>10){
    foo = foo.substring(0, 9);
}

I'm not quite sure what kind of object pageModel is but its probably a Map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜