Spring MVC-仅在传递请求参数时才在JSP中显示值

时间:2015-10-15 18:59:55

标签: jsp spring-mvc

我想创建一个JSP页面,用户可以从下拉列表中选择一个值,提交它并在同一页面上查看结果。我不知道如何实现这一目标。 这是JSP页面:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Station choosing view</title>
</head>
<body>
    <h1>Select the station</h1>
    <form:form commandName="station" action="archive.htm" method="get" >
        <form:select path="id">
            <form:options items="${stations}" itemValue="id" itemLabel="localisation"></form:options>
        </form:select>
        <p><form:button>Submit</form:button></p>
    </form:form>

    <c:if test="${foundStation.id!=null}">
        <p>Station code is ${foundStation.code}</p>
    </c:if>

</body>
</html>

这是控制器方法的代码:

@RequestMapping(value = "/archive", method = RequestMethod.GET)
public ModelAndView readingHistory(@RequestParam (value = "id", required = false) Long stationId){
    ModelAndView modelAndView = new ModelAndView("archive");
    Iterable<Station> stationList = stationDAO.findAll();
    modelAndView.addObject("stations", stationList);
    modelAndView.addObject("station", new Station());

    if (stationDAO.exists(stationId)){
        modelAndView.addObject("foundStation", stationDAO.findOne(stationId));
    }

    return modelAndView;
}

如果在访问页面时未通过foundStation参数,如何避免打印id的内容?我想我以错误的方式使用<c:if test>。上面的代码在传递id参数时按预期工作。

我得到的错误是:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)

1 个答案:

答案 0 :(得分:1)

  

如果id,我该如何避免打印findStation的内容   访问页面时没有传递参数?

ff。如果NullPointerExceptionfoundStation,代码将抛出null。因此,无法访问id属性。

<c:if test="${foundStation.id!=null}">

将其更改为:

<c:if test="${foundStation != null}">

此外,在从存储库调用方法之前,请确保先对stationId参数执行空检查。这可以防止您发生的错误。

if (stationId != null) {
    if (stationDAO.exists(stationId)){
        modelAndView.addObject("foundStation", stationDAO.findOne(stationId));
    }   
}