JSP在forEach循环之前获取一个值

时间:2016-03-10 03:15:38

标签: jsp jstl

我确信这是另一个简单的任务,但我正在画一个空白。我不喜欢数组但在进入forEach jstl之前我想显示一个字段。所以这就是我所拥有的:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout) {
    ModelAndView model = new ModelAndView();

    if (error != null) {
        model.addObject("error", "Invalid username and password");
    }
    model.addObject("msg", "This is a message and stuff");
    return model;
}

@RequestMapping(value = { "/welcome/{userName}", "/welcome" }, method = RequestMethod.GET, produces = "application/json")
public User welcome(@PathVariable String userName) {
    User user = new User();
    user.setEmail(userName + "@something.com");
    user.setUsername(userName);
    return user;
}

带有forEach循环的directorlist.jsp文件:

DirectorServlet.jsp (partial)
if(action.equals("list")){
    System.out.println("Inside DirectorServlet, listing");
    List<Director> directors = DirectorUtil.getDirectors();
    request.setAttribute("directors", directors);
    dispatcher="/directorlist.jsp";

    }

2 个答案:

答案 0 :(得分:0)

理想情况下,您可以设置另一个请求属性directorTitle。

 request.setAttribute("directorsTitle", directorsTitle);

并在JSP上访问它,如。

<h1><c:out value="${directorsTitle}"/></h1>

或者如果你想访问列表中的任何项目那么。

<c:out value="${directors[index].title}" />

答案 1 :(得分:0)

您可以使用forEach访问两次,并以这种方式仅获取第一个值:

ddd