Tkachuk_Evgen
Tkachuk_Evgen

Reputation: 1354

JSP not throwing NullPointerException

I have controller:

@RequestMapping(method = RequestMethod.GET)
public String getViewRailwayService(@RequestParam long id, Model model) {
    model.addAttribute("railwayService",railwayServiceRepository.findOne(id));
    return "admin/railwayService/view";
}

and jsp page:

...
<title>${railwayService.name}</title>
<c:forEach var="company" items="${railwayService.companies}">
...

It works fine, but I confused, when railwayServiceRepository.findOne(id) return null NullPointerException doesn't throw.

Upvotes: 9

Views: 506

Answers (2)

kryger
kryger

Reputation: 13181

Not sure if a StackOverflow wiki on Expression Language is a trustworthy reference (I've been trying to find it in the official specs, no luck yet), but:

EL relies on the JavaBeans specification when it comes to accessing properties. In JSP, the following expression:

${user.name}

does basically the same as the following in "raw" scriptlet code (the below example is for simplicity, in reality the reflection API is used to obtain the methods and invoke them):

<%
  User user = (User) pageContext.findAttribute("user");
  if (user != null) {
    String name = user.getName();
    if (name != null) {
      out.print(name);
    }
  }
%>

(...) Please note that it thus doesn't print "null" when the value is null nor throws a NullPointerException unlike as when using scriptlets. In other words, EL is null-safe.

Upvotes: 9

Sandeep Patange
Sandeep Patange

Reputation: 459

In model.addAttribute("railwayService",railwayServiceRepository.findOne(id));

whenever value is null, it will not throw NullPointerException, It will just pass value as null to the view.

Upvotes: -4

Related Questions