1. 返回数据与返回页面

在写web项目的时候,controller里的返回值一般分为两种,一种是返回页面,也就是ModeAndView,另一种是直接返回数据,比如json格式的数据。

返回一个页面,我们需要用到一些模板引擎,比如熟知的jsp,模板引擎后面会详细讲解。

返回数据一般会选择返回json数据,我们之前的demo项目中使用的@RestController就是一个返回数据的注解。

@RestController是一个组合注解,是由@Controller和@ResponseBody组合而成的。
@Controller:将返回值渲染为页面。
@ResponseBody:将返回值渲染为数据。

2. spring boot支持的模板引擎

spring-boot 支持多种模版引擎包括:

  • FreeMarker
  • Groovy
  • Thymeleaf (Spring 官网使用这个)
  • Velocity
  • JSP (不推荐,jsp在内嵌的servlet容器中运行有一些问题。)

我们在讲前后端分离之前,都会使用Thymeleaf模板引擎,先简单的介绍一下它。

2.1 Thymeleaf模板引擎

Thymeleaf是一个java类库,它是一个xml/xhtml/html5的模板引擎,可以作为mvc的web应用的view层。

Thymeleaf还提供了额外的木块与spring mvc集成,所以使用ssm框架的也可以使用这个模板引擎。

本来想列一下Thymeleaf的用法的,但是感觉有点多,以后哪里用到哪里讲好了。

3. 实战

接下来,我们通过一个项目,来实践一下两种不同的返回结果。

先看一下最终的目录结构:

 
目录结构

3.1 创建项目project_1

  • 选择依赖:web Thymeleaf
 
选择依赖

3.2 新建一个person类,用来封装数据

package com.example.model;

public class Person {

    private String name;
private Integer age; public Person() {
} public Person(String name, Integer age) {
this.name = name;
this.age = age;
} public void setName(String name) {
this.name = name;
} public void setAge(Integer age) {
this.age = age;
} public String getName() {
return name;
} public Integer getAge() {
return age;
}
}

3.3 新建一个ViewController,用来返回一个视图

package com.example.controller;

import com.example.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList;
import java.util.List; @Controller
public class ViewController { @RequestMapping("/view")
public String view(Model model){
Person person = new Person("x", 22); List<Person> list = new ArrayList<>();
list.add(new Person("a", 11));
list.add(new Person("b", 12));
list.add(new Person("c", 13)); model.addAttribute("onePerson", person);
model.addAttribute("manyPerson", list); return "index"; }
}

3.4 创建index.html,用来接收数据

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>test</title> <link href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet"/>
</head> <body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">访问model</h3>
</div>
<div class="panel-body">
<span th:text="${onePerson.name}"></span>
</div>
</div> <div th:if="${not #lists.isEmpty(manyPerson)}">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">列表</h3>
</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" th:each="person:${manyPerson}">
<span th:text="${person.name}"></span>
<span th:text="${person.age}"></span>
</li>
</ul>
</div>
</div>
</div>
</body>
</html>

这里我们使用了Thymeleaf模板引擎来获得后台传来的数据并解析,使用bootstrap框架显示数据。可以看到,Thymeleaf的用法和jsp还是有点像的。可以直接通过${}的形式来获得attribute中的数据。

在 spring boot 中,模板引擎默认是开启缓存的,如果修改了页面内容,刷新页面是得不到修改后的内容的。我们可以在application.yml中关闭模板引擎缓存:

spring:
thymeleaf:
cache: false

如果需要详细的Thymeleaf模板的使用方式教程,可以给我留言,我看情况来决定是否要写一篇。因为我用的也不是很多,大部分情况我都是前后端分离的。

3.5 运行项目,浏览器访问http://localhost:8080/view

 
view

可以看到,我们成功的在前端获取到了数据。方式就是将数据保存在attribute中,然后再前端页面获取。

3.6 修改ViewController中的@Controller为@RestController,重新运行

 
view

我们修改了注解,发现结果变了,直接显示了“index”,是因为@RestController会直接返回数据,而不是渲染页面,所以直接返回了index(这个index,是return语句中的)

3.7 创建DataController,用来直接返回数据

package com.example.controller;

import com.example.model.Person;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.Arrays;
import java.util.List; @RestController // 使用RestController注解
public class DataController { @RequestMapping("/person")
public Person person(){
return new Person("aa", 10);
} @RequestMapping("persons")
public List<Person> persons(){
return Arrays.asList(new Person("bb", 11), new Person("cc", 12));
}
}

3.8 重新运行项目

访问http://localhost:8080/person

 
person

获得了json格式的数据

访问http://localhost:8080/persons

 
persons

列表也可以直接渲染为json。

这里需要注意,如果我们方法的返回值是String(参考上面的index),那么返回的结果就是你return的字符串,如果方法的返回值是一个对象(person)或者一个集合(list,map等),那么得到的结果就是一个json字符串。spring boot默认使用jackson来进行解析。

jackson也是可以修改为gson或者fastjson的,我们下篇再讲。

3.9 修改DataController中的@RestController为@Controller,重新运行

访问http://localhost:8080/person

 
person

访问http://localhost:8080/persons

 
persons

会发现这两个都报错了,因为@Controller注解是渲染视图的,而我们返回的是对象或者集合,不能完成正常的渲染。

4. 小结

本文主要讲解了spring boot 如何渲染视图和数据,讲解了@Controller和@RestController的区别与用法。如果有什么疑问,请及时联系我。


我之前写过一个重新认识java系类(还没写完,会写完的。。),篇幅很长,每一篇文章多的有7、8千字,和多人抱怨说看到一半就不想看了,因为太长了,所以 spring boot 这个系类会尽量的短小精悍,每篇文章只讲一个知识点,这样看着不累~


作者:cleverfan
链接:https://www.jianshu.com/p/b2f2f09987de
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 https://www.jianshu.com/u/8dc5811b228f

springboot_3的更多相关文章

随机推荐

  1. FFmpeg编译:mac下编译iOS平台的FFmpeg库(支持armv7, arm64, i386, x86_64)

    环境:FFmpeg 3.4.6Xcode 10.3macOS 10.14.6iOS SDK 12.4 一.准备工作 1. 下载FFmpeg我这里使用的是3.4.6版本的FFmpeg,可以从FFmpeg ...

  2. php cURL error 60: SSL certificate problem: unable to get local issuer certificate 解决办法

    错误例子如下: php5.6以上的版本会出现这种问题 关于“SSL证书问题:无法获取本地颁发者证书”错误.很明显,这适用于发送CURL请求的系统(并且没有服务器接收请求) 1)从https://cur ...

  3. PL/SQL developer 开发小技能 and ash show command PL/SQL EXECUTE 以及注释

    ##sample  test windows 调试存储过程, 总体指导思想使用pl/sql test windows 调试存储过程,存储过程调试 可以用  run  to next exception ...

  4. 报错:Unable to read additional data from client sessionid 0x36ab52d38c20b20, likely client has closed socket

    报错背景: CDH集群中,将kafka和Flume整合,将kafka的数据发送给Flume消费. 启动kafka的时候正常,但是启动Flume的时候出现了报错现象. 但是我检查了Flume,Flume ...

  5. 编译安装hls协议切片工具 m3u8-segmenter

    操作系统:Ubuntu16.04.4 amd64 安装http://m3u8-segmenter.inodes.org/方式安装m3u8-segmenter报错,于是有了这篇文章 apt instal ...

  6. mysql的驱动类com.mysql.jdbc.Driver过时了,需要用com.mysql.cj.jdbc.Driver代替

    springboot项目整合mybatis,配置文件如下: server: port: 8081 mybatis: config-location: classpath:mybatis/mybatis ...

  7. Java基础教程:多线程基础(6)——信号量(Semaphore)

    Java基础教程:多线程基础(6)——信号量(Semaphore) 信号量 信号量(Semaphore)由一个值和一个指针组成,指针指向等待该信号量的进程.信号量的值表示相应资源的使用情况.信号量S≥ ...

  8. http响应时长分析

    curl -o /dev/null -s -w "time_namelookup:%{time_namelookup}::time_connect:%{time_connect}::time ...

  9. docker pull 提示错误的username or password

    安装完docker后,使用cli docker pull images 时,提示用户名密码错误 解决方法 使用docker ID 不要使用 Email 登陆. https://github.com/d ...

  10. linux系统界面转换

    普通使用的切换: 命令行->图形 startx 或者 ctrl+alt+F7切换到图形界面,虚拟机里面使用Alt+F7返回到图形界面 图形->命令行 Ctrl+Alt+F1--F6 如果想 ...