jsp shows details of objects passed by springmvc modelmap

  • 2021-11-14 06:37:15
  • OfStack

jsp displays objects passed by springmvc modelmap

Recently, I am doing a small website with very basic functions, so I decided to build it with springmvc.

There is a problem. When controller passes values to the front end, such as passing a string with ModelMap, modelmap. addattribute ("msg", "hello"), then on jsp, it can be displayed directly by using ${msg}. Next, if I pass an object, I can still use methods like ${obj. name} to display the individual properties of that object. However, in more cases, the list needs to be displayed, so I passed an List < User > Object, but it is a little stupid when parsing, and I don't know how to traverse it.

After searching for half a day, I know that I can also use jstl tag to deal with the object list 1 passed by servlet before. The specific treatment methods are as follows:

controller.java


@RequestMapping(value = "/getUsers", method = RequestMethod.GET)
public String getUsers(ModelMap model) {
 List<UserEntity> userEntityList = userService.getAllUser();
 for (UserEntity user:userEntityList) {
  System.out.println(Util.toJsonString(user));
 }
 model.addAttribute("userlist", userEntityList);
 return "userList";
}

userList.jsp


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>user list</title>
</head>
<body>
 <h1>hello</h1>
 <br>
 <c:forEach items="${userlist}" var="item" >
  userId:<c:out value="${item.id}"/>
  <br>
  username:<c:out value="${item.username}"/>
  <br>
 </c:forEach>
</body>
</html>

The items specifies the list as an object passed by the back end through the forEach tag, and then it can be traversed directly.

Sentiment: Learn to associate more. Even though springmvc uses many different methods, such as ModelMap to pass objects, it can be handled in a similar way to the previous one shown in jsp.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: