概述

springboot框架中的 Controller,相当于增强的 servlet:

  1. 接收请求(get、post、ajax)
  2. 获取请求中的参数(url中的参数,post表单参数,ajax参数、上传文件)
  3. 做出响应。(转发页面、重定向页面、返回json)

用 Controller 代替 Servlet,不需要写 Servlet

优点:

更简单的代码,就可以实现更多的功能

创建 controller 类

package top.malaoshi.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//说明该类是Controller
@Controller
public class HelloCtrl {

    //映射路径,也就是说浏览器访问 `http://ip地址:port端口号/context上下文/hello` 时,就能够进入该方法
    @RequestMapping("/hello")
    public String hello(){
        //返回值是字符串时,表示页面名字,转发到hi.html,注意:该页面必须在静态资源目录下
        return "hi.html";
    }
}

创建 hi.html 页面

在静态资源目录下,创建 hi.html 文件,如下图位置:

内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello jsp
</body>
</html>

运行主启动类

测试

访问: http://localhost:8080/hello ,就进入到 HelloCtrlhello() 方法,该方法返回 hi.html 字符串,最终 转发classpath:/static/hi.html

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐