一起学习springboot(四):Springboot集成Html

本篇文章主要介绍springboot集成html,并简单说下四种从后端传数据到页面的方式,这里页面使用的是thymeleaf模板引擎,也是springboot官方推荐的使用方式,学习thymeleaf? https://www.thymeleaf.org/

1、pom.xml中引入thymeleaf

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

2、application.yml配置模板路径

spring:
  thymeleaf:
    prefix: classpath:/templates/

3、controller类

这里说4种传数据到页面得方式:

  1. @ResponseBody直接返回字符串,可以是普通字符串格式也可以是json格式
  2. 通过Model传数据,Model类必须作为函数参数使用来传参,在函数里面通过new出来得对象无法传参
  3. 通过Map传数据,同上,必须作为函数参数来使用
  4. 通过ModelAndView传数据,ModelAndView可以是函数参数,也可以在函数里面new出来,但是函数返回类型必须是ModelAndView
package com.example.springboot_html;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @author XuJD
 * @create 2018-10-29 11:58
 **/
@Controller
public class IndexController {

    @RequestMapping("/index")
    @ResponseBody
    public String index(){
        return "index";
    }

    @RequestMapping("/index1")
    public String index1(Model model,Map<String, Object> map){
        map.put("name","map传参");
        model.addAttribute("name1","Model传参");
        return "index";
    }

    @RequestMapping("/index2")
    public ModelAndView index2(ModelAndView modelAndView){
        //ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("name","ModelAndView传参");
        modelAndView.addObject("name1","ModelAndView传参");
        return modelAndView;
    }

}

4、页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${name}"></h1>
<h1 th:text="${name1}"></h1>
</body>
</html>

源码地址:
github下载
https://github.com/xujiangdong/SpringbootLearn

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值