Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 829
Tkachuk_Evgen Avatar asked Mar 05 '15 12:03

Tkachuk_Evgen


1 Answers

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.

like image 100
kryger Avatar answered Sep 28 '22 15:09

kryger