Springboot将数据库中数据显示在前端,并分页操作查询全部,根据id查询。

楼主本身就是个小白,自己也是墨迹了好久才做出来。具体需求就是使用Springboot(其实ssm框架都一样,只不过连接数据库有一些不同),我下面也不介绍连接数据库了,百度很多方法。我主要将数据库中数据显示在前端,并分页操作查询全部,根据id查询。

经历:1.一开始使用springboot+thymeleaf+PageHapler来做,虽说博客上有很多例子,但是踩坑无数。印象中有thymeleaf依赖包必须加版本号才能导入成功2.0.4.RELEASE这个版本的。同时还需要加入pagehelper依赖包等等,最后由于自身能力有限无法实现,不过大家如果仅仅是练手可以去试试。

下面梳理使用标准显示的步骤
1.需要将数据库job表的全部数据需要在FindAllJobTask.jsp页面上。

在JobTaskMapper中

//查询所有,其实最后因为分页没有用到,不过可以作为显示的一个测试函数
@Select(" select jobname,createtime,endtime,projectname,type from job ")
public  List<JobTask>  selectFindAllJobTask();

//根据id查询一条
//根据任务的id去查询,任务的id并不准备显示在页面上
@Select(" select jobname,createtime,endtime,projectname,type from job where id =#{id}")
public  List<JobTask>  selectFindOneJobTask(String id);

//获得全部商品的条数,为分页做准备
@Select("select count(*) from job")
public int getJobCount();

//获得分页的商品数据
//index和currentCount这两个参数是分页用的,index是起始页号,currentCount是每一页需要显示多少个数据的值。
@Select("select * from job limit #{index},#{currentCount}")
public List<JobTask> findJobForPageBean(@Param("index") int index,@Param("currentCount") int currentCount);

2.在pojo中定义两个类,分别是数据库job表的JobTask类和分页操作的PageBean类

JobTask.java类
(自己加上get和set方法)

public class JobTask implements Serializable {
    /** applet_job.id */
    private Long id;
    /** applet_job.jobName 任务名 */
    private String jobname;
    /** 格式化时间*/
    private String createtime;
    /** 结束时间 */
    private String endtime;
    /**job.projectName 任务名,主线传过来的值 */
    private String projectname;
    /**Type */
    private Integer type;
  
    }

PageBean.java类
(自己加上get和set方法)

public class PageBean<T> {
    //1.每页显示的数据
    private List<T>  joblist=new ArrayList<T>();
    //2.总页数
    private int totalPage;
    //3.当前页
    private  int currentPage;
    //4.总条数
    private int totalCount;
    //5.当前页显示的条数
    private int currentCount;
    }

3.业务逻辑层JobTaskService.java

  • 注意必须加@service否则会报错
@Service
//查询全部分页显示
public class JobTaskService {
    public PageBean findPageBean(int currentPage,int currentCount)  {
        JobTaskMapper jobTaskMapper = ApplicationContextUtil.getInstance().getBean(JobTaskMapper.class);
        //封装一个pagebean
        PageBean pageBean =new PageBean();
        //当前页
        pageBean.setCurrentPage(currentPage);
        //当前页显示的条数
        pageBean.setCurrentCount(currentCount);
        //总条数
        int totalCount=jobTaskMapper .getJobCount();
        pageBean.setTotalCount(totalCount);
        //总页数=Math.ceil(总条数/每页显示的条数)
        int totalPage = (int) Math.ceil(1.0*totalCount/currentCount);
        pageBean.setTotalPage(totalPage);
        //每页显示的数据
        //页数和起始索引的关系
        //第一页则 limit      0 ,       currentCount
        //第二页  limit (第几页-1)*currentCount ,  currentCount
        //第三页  limit currentCount ,currentCount
        //总结  索引index=(当前页数-1)*每页显示的条数
        int index =(currentPage-1)*currentCount;
        List<JobTask> jobList =jobTaskMapper.findJobForPageBean(index,currentCount);
        pageBean.setJoblist(jobList);

        return pageBean;
    }
    
    //根据id查询,也显示在FindAllJobTask.jsp页面上
    public PageBean findOneBean(int currentPage,int currentCount,String id)  {
        JobTaskMapper jobTaskMapper = ApplicationContextUtil.getInstance().getBean(JobTaskMapper.class);
        //封装一个pagebean
        PageBean pageBean =new PageBean();
        //当前页
        pageBean.setCurrentPage(currentPage);
        //当前页显示的条数
        pageBean.setCurrentCount(currentCount);
        //总条数
        int totalCount=jobTaskMapper .getJobCount();
        pageBean.setTotalCount(totalCount);
        //总页数=Math.ceil(总条数/每页显示的条数)
        int totalPage = (int) Math.ceil(1.0*totalCount/currentCount);
        pageBean.setTotalPage(totalPage);
        //每页显示的数据
        //页数和起始索引的关系
        //第一页则 limit      0 ,       currentCount
        //第二页  limit (第几页-1)*currentCount ,  currentCount
        //第三页  limit currentCount ,currentCount
        //总结  索引index=(当前页数-1)*每页显示的条数
        int index =(currentPage-1)*currentCount;
        List<JobTask> jobList =jobTaskMapper .selectFindOneJobTask(id);
        pageBean.setJoblist(jobList);

        return pageBean;
    }
}

4.在controller层中

@RestController
public class JobTaskController{
	//分页并显示
	@RequestMapping(value = "/FindAllJobTask")
	public Object findAllJobTask(HttpServletRequest request, HttpServletResponse response)  {
  		JobTaskService jobTaskService =ApplicationContextUtil.getInstance().getBean(JobTaskService.class);
   		//模拟当前是第一页
  	 	String currentPageStr =request.getParameter("currentPage");
   		if(currentPageStr==null) currentPageStr="1";
   		int currentPage=Integer.parseInt((currentPageStr));
  		 //每页显示15条
 	 	 int currentCount=15;
 	 	 PageBean<JobTask> pageBean =jobTaskService.findPageBean(currentPage,currentCount);
  		 request.setAttribute("pageBean",pageBean);
   		//传入总页面和当前页数
   		return new ModelAndView("FindAllJobTask");
	}	

	//分页显示根据id查询
	@RequestMapping(value = "/FindOneJobTask")
	public Object findOneJobTask(HttpServletRequest request, HttpServletResponse response)  {
   		JobTaskService dbjobTaskService =ApplicationContextUtil.getInstance().getBean(JobTaskService.class);
 		String idd =request.getParameter("id");
  		 //模拟当前是第一页
  		String currentPageStr =request.getParameter("currentPage");
   		if(currentPageStr==null) currentPageStr="1";
   		int currentPage=Integer.parseInt((currentPageStr));
  		 //每页显示15条
   		int currentCount=15;
  		PageBean<JobTask> pageBean =dbjobTaskService .findOneBean(currentPage,currentCount,idd);
  		request.setAttribute("pageBean",pageBean);
  		//传入总页面和当前页数
  		return new ModelAndView("FindAllJobTask");
	}

}

5.FindAllJobTask.jsp页面
记住:根据id查询的部分必须在一个表单里,并且action写的是controller 层的@RequestMapping的value值,本身首先访问的是controller层FindAllJobTask的url ,页面显示的是查询全部的信息,此时点击搜获按钮,提交的是整个表单,会将这个输入的id=id传给controller层的FindOneJobTask处理根据id查询的函数中去。

<form id="Form1" name="Form1" action="FindOneJobTask" method="post" align="center">
请输入id<input type="text" name="id" id="id" align="center">&nbsp;
    <input type="submit" value="搜索" >
%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title>重启任务界面</title>
   script type="text/javascript">
   </script>
</head>
<style>
   ul{
      list-style:none;
   }
   ul li{
      display: inline-block;
   }
</style>
<body>
<form id="Form1" name="Form1" action="FindOneJobTask" method="post" align="center">

    请输入id<input type="text" name="id" id="id" align="center">&nbsp;
    <input type="submit" value="搜索" >

<div class="taskTable" align="center">
   <table  border="1px" >
      <tr>

         <td>任务名</td>
         <td>中文描述</td>
         <td >格式化时间</td>
         <td>结束时间</td>
         <td>任务名</td>
         <td >任务信息</td>
         <td>应用类型</td>
         <td>手机pv类型</td>
         <td>测试状态</td>
      </tr>

      <c:forEach items="${pageBean.joblist}" var="job" varStatus="vs">
         <tr>
            <td>${job.jobname}</td>
            <td>${job.jobnamedesc}</td>
            <td>${job.createtime}</td>
            <td>${job.endtime}</td>
            <td>${job.projectname}</td>
            <td>${job.projectnamedesc}</td>
            <td>${job.aplettype}</td>
            <td>${job.audittype}</td>
            <td>${job.teststatus}</td>
            <td>
               <button id="restart">重启任务</button>
            </td>

         </tr>
      </c:forEach>

   </table>
   <br>
   <br>
   <br>

</div>
</form>
<!--分页 -->
<div align="center" >
   <ul >
      <!-- 上一页 -->
      <!-- 判断当前页是否是第一页 -->
      <c:if test="${pageBean.currentPage==1 }">
         <li class="disabled">
            <a href="javascript:void(0);" aria-label="Previous">
               <span aria-hidden="true">&laquo;</span>
            </a>
         </li>
      </c:if>
      <c:if test="${pageBean.currentPage!=1 }">
         <li>
            <a href="FindAllJobTask?currentPage=${pageBean.currentPage-1}" aria-label="Previous">
               <span aria-hidden="true">&laquo;</span>
            </a>
         </li>
      </c:if>


      <c:forEach begin="1" end="${pageBean.totalPage }" var="page">
         <!-- 判断当前页 -->
         <c:if test="${pageBean.currentPage==page }">
            <li class="active"><a href="javascript:void(0);">${page}</a></li>
         </c:if>
         <c:if test="${pageBean.currentPage!=page }">
            <li><a href="FindAllJobTask?currentPage=${page}">${page}</a></li>
         </c:if>

      </c:forEach>

      <!-- 判断当前页是否是最后一页 -->
      <c:if test="${pageBean.currentPage==pageBean.totalPage }">
         <li class="disabled">
            <a href="javascript:void(0);" aria-label="Next">
               <span aria-hidden="true">&raquo;</span>
            </a>
         </li>
      </c:if>
      <c:if test="${pageBean.currentPage!=pageBean.totalPage }">
         <li>
            <a href="FindAllJobTask?currentPage=${pageBean.currentPage+1}" aria-label="Next">
               <span aria-hidden="true">&raquo;</span>
            </a>
         </li>
      </c:if>

   </ul>
</div>
<!-- 分页结束 -->


</body>
</html>

6.项目最终截图
分页显示job数据库表中的所有数据,注意看url中的FindAllJobTask是controller层@RestMapping中的函数value值
查询分页显示全部job表中的所有数据
根据job的id查询job表中对应的数据并显示在FindAllJobTask.jsp页面中,注意url,这是因为在点击查询的时候表单action写的是controller中FindOneJobTask的函数value,所以可以调用controller中这个函数的功能。
在这里插入图片描述

7.总结
1.可以参考黑马视频就业班基础加强中分页和查询。
2.报错:java传入多个参数时报"Parameter ‘XXX’ not found. Available parameters are [arg1, arg0, param1,…"
参考:https://blog.csdn.net/xuanbabyliu/article/details/84374872。
3.在mapper层写完sql一定要记得在mysql中查询中执行一遍。
其他参考:

  • https://blog.csdn.net/qq_42055933/article/details/92995049
  • https://blog.csdn.net/qq78442761/article/details/88525207 (这个用了thy的模板,很好很全面的例子)
  • https://blog.csdn.net/random0815/article/details/80582922
  • https://blog.csdn.net/qq_27317475/article/details/81168241?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task(使用了pageHepler分页)
  • https://bbs.csdn.net/topics/392207252?list=65523716 表单action的写法
  • 12
    点赞
  • 77
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
以下是使用Spring Boot和MySQL进行分页查询并将结果展示给前端的示例代码: 1. 首先,我们需要在pom.xml添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 2. 接下来,我们需要创建一个实体类,用于映射数据库数据。例如,我们创建一个名为“User”的实体类: ``` @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "email") private String email; // getters and setters } ``` 3. 然后,我们需要创建一个Spring Data JPA的仓库接口,用于访问数据库。例如,我们创建一个名为“UserRepository”的接口: ``` public interface UserRepository extends JpaRepository<User, Long> { Page<User> findAll(Pageable pageable); } ``` 4. 接下来,我们需要创建一个控制器类,用于处理HTTP请求并将结果返回给前端。例如,我们创建一个名为“UserController”的控制器: ``` @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public Page<User> getUsers(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) { return userRepository.findAll(PageRequest.of(page, size)); } } ``` 5. 最后,我们需要在Spring Boot应用程序的配置文件配置MySQL数据库连接信息。例如,我们将以下配置添加到application.properties文件: ``` spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update ``` 现在,我们可以启动Spring Boot应用程序,并访问http://localhost:8080/api/users?page=0&size=10来获取第一页的10个用户数据。页面索引是从0开始的。我们可以使用类似的URL来获取其他页面的数据。这些数据将以JSON格式返回给前端
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值