java - JSP 不抛出 NullPointerException

标签 java spring jsp nullpointerexception

我有 Controller :

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

和jsp页面:

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

它工作正常,但我很困惑,当 railwayServiceRepository.findOne(id) 返回 null NullPointerException 没有抛出。

最佳答案

不确定 StackOverflow wiki on Expression Language是一个值得信赖的引用(我一直试图在官方规范中找到它,但运气不好),但是:

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.

关于java - JSP 不抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28877772/

相关文章:

java - 从我的服务器调用另一台服务器的JSP

java - 每次使用 PowerMock 进行测试后模拟行为都会重置

Spring 数据 JPA : class path resource [] cannot be resolved to URL because it does not exist

java - Spring @ControllerAdvice 异常处理程序返回 404 错误而不是 View

java - spring mvc中资源不可用问题

jsp - jsp 的 Aptana 颜色语法

java - 如何停止获取用户输入

java - 获取特定数量的记录在 Hibernate 中不起作用

java - 在单个网络容器中可以运行多少个不同的网络应用程序?

java - 使用 spring CrudRepository 自定义查询