zoukankan      html  css  js  c++  java
  • 【SpringBoot】@Controller和@RestController的区别

    @RestController = @ResponseBody + @Controller

    使用@RestController,return返回的是响应体,例如如果return "success",则会在页面上显示success

    使用@Controller,return返回的是html页面,例如如果return "success",则会跳转到页面success.html

    如果在一个控制器类中,希望某些方法的return实现跳转,某些方法的return可以返回响应体,就可以使用Controller注解,并且在需要返回响应体的方法上加上@ResponseBody的注解

     1 @Controller
     2 public class HelloController {
     3 
     4     @ResponseBody
     5     @RequestMapping("/hello")
     6     public String hello() {
     7         return "hello";
     8     }
     9 
    10     @RequestMapping("/success")
    11     public String success(Map<String,Object> map){
    12         map.put("successful","成功");
    13         return "success";
    14     }
    15 }

    success.html

     1 <!DOCTYPE html>
     2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>success</title>
     6 </head>
     7 <body>
     8     <h1>
     9         成功
    10     </h1>
    11     <div th:text="${successful}"></div>
    12 </body>
    13 </html>

    hello.html

     1 <!DOCTYPE html>
     2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>hello</title>
     6 </head>
     7 <body>
     8 <h1>跳转到hello页面</h1>
     9 </body>
    10 </html>

    从下面的截图可以看出,加了response注解的直接显示响应体,而没有跳转到hello.html

  • 相关阅读:
    线性表——(2)单向链表
    线性表——(1)顺序表
    UVa 1592 数据库
    UVa 12096 集合栈计算机
    Python 协程
    Python 多线程及进程
    Python 日志(Log)
    Python 函数式编程
    Python基础
    DB2 获取前两天的数据
  • 原文地址:https://www.cnblogs.com/xdcat/p/13156642.html
Copyright © 2011-2022 走看看