首先需要说明的是,SpringMVC向JSP页面传递数据库读取到的值的方法有很多种,这里介绍一种基本的方法。
首先需要说明的是,SpringMVC向JSP页面传递数据库读取到的值的方法有很多种,这里介绍一种基本的方法。
- 控制层(Controller)
在控制层中我们需要注入一个由Service层封装好的Map对象,并将这个Map对象存入ModelAndView中,然后返回给View层(即JSP页面)。
示例:
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user/list")
public ModelAndView userList() {
ModelAndView modelAndView = new ModelAndView("user/list");
Map<String, Object> map = new HashMap<>();
List<User> userList = userService.getUserList();
map.put("userList", userList);
modelAndView.addAllObjects(map);
return modelAndView;
}
}
- 视图层(View)
在JSP页面中,我们需要在<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>标签之后导入相应的JSTL标签库(需要提前将JSTL.jar包放到项目的lib目录下):
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
在JSP页面中,我们可以通过c:forEach标签来对Map中的数据进行遍历,展示在页面上。示例:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>User List:</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
以上就是一个基本的SpringMVC向JSP页面传递数据库读取到的值的方法,可以通过这种方法将读取到的数据传递到JSP页面进行展示。
另外,如果不想使用JSTL标签库,还可以使用EL表达式来实现,示例:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>User List:</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
沃梦达教程
本文标题为:SpringMVC 向jsp页面传递数据库读取到的值方法
基础教程推荐
猜你喜欢
- SpringBoot嵌入式Web容器原理与使用介绍 2023-06-17
- java 解决Eclipse挂掉问题的方法 2024-01-10
- Spring MVC数据绑定方式 2023-06-30
- springboot中request和response的加解密实现代码 2022-12-08
- 详解http请求中的Content-Type 2023-07-31
- 关于@MapperScan包扫描的坑及解决 2023-04-16
- JSP servlet实现文件上传下载和删除 2023-07-30
- SpringBoot 2.5.5整合轻量级的分布式日志标记追踪神器TLog的详细过程 2023-06-17
- jsp hibernate的分页代码第3/3页 2024-01-11
- 用javascript制作qq注册动态页面 2023-12-16
