【SpringBoot/Thymeleaf/myBatis】如何让SpringBoot Web页面把后台数据带出来

本文例程下载:https://files.cnblogs.com/files/heyang78/myBank_showdataonpage_210906.rar

只要网页出现了,让其中显示数据就不难,因为控制器里可以注入Mapper,而Mapper是访问DB的,取出数据后放到Model里就好。随后页面进行数据解析就OK。

下面是具体步骤:

第一步:在Mapper中准备访问数据的函数:

@Mapper
public interface StudentMapper {
......
    
    @Select("select * from student where rownum<6")
    List<Student> findFive();
......
}

逻辑很简单,就从student表中最多取五条记录就完事。

第二步:在控制器里注入Mapper,然后在函数里使用它。

@Controller
public class ActionController {
    @Autowired
    private StudentMapper studentMapper;
......
    
    @RequestMapping("/list")
    public String showListPage(Model m) {
        List<Student> list=studentMapper.findFive();
        m.addAttribute("list", list);
        
        return "list";
    }
}

这个函数参数里多了一个Model对象m,它相当于request,往里放数据是addAttribute方法,比request的setAttribute方法进步了那么一点点。

第三步:页面显示数据。

    <table......>
......
        <tbody>
            <tr th:each="item:${list}">
                <td th:text="${item.id}">id</td>
                <td th:text="${item.name}">name</td>
            </tr>
        </tbody>
    </table>

这里的标签是themeleaf特有的,也不难理解,也就是从list取出元素名为item,然后item实际和student类是一致的。

最后就是启动程序,在地址栏输入http://localhost:8080/list,之后页面就显示出来了。

到这里就结束了,我又带大家重新体验了一新时代的jsp。

-END-

原文地址:https://www.cnblogs.com/heyang78/p/15233165.html