MultiThread/mvc/SpringMVC笔记.md

3.5 KiB
Raw Blame History

SpringMVC笔记

访问控制

请求地址时返回对应的网页文件

  • @RestController用于返回对象格式的内容,在后面会使用ModelAndView可以返回网页文件
  • @Controller用于返回网页文件

环境要求

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- thymeleaf -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- devtools -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.36</version>
    </dependency>

错误页面设置

在这个路径下可以配置错误码要访问的页面,也就是可以自定义页面内容

image-20250122171536808

使用@Controller

返回需要访问的HTML内容页面最后返回的字符串就是页面这个页面位于templates目录下

@RequestMapping("/use")
@Controller
public class UseController {

    // 带参数访问
    @RequestMapping(value = "hello", method = RequestMethod.GET, params = {"name"})
    public String hello() {
        return "hello";
    }

    @GetMapping("jumpPage")
    public String jumpPage() {
        return "jumpPage";
    }

    @GetMapping("index")
    public String quick() {
        return "user";
    }

    // 跳转的页面
    @GetMapping("toJump")
    public String toJump() {
        return "redirect:jumpPage";
    }
}

如果在使用@Controller需要返回JSON内容需要在控制器方法上加上@ResponseBody

@GetMapping("getJson")
@ResponseBody
public List<String> getJson() {
    ArrayList<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");

    return list;
}

使用@RestController

使用方式1

如果使用@RestController那么返回的就是JSON对象但是这时候要想返回网页文件需要使用ModelAndView

@RequestMapping("userRest")
@RestController
public class UseRestController {

    @GetMapping("page/test")
    public ModelAndView test() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("page/test");
        modelAndView.addObject("message", "这是消息内容");
        return modelAndView;
    }
}

我们引入了thymeleaf所以有以下内容<h4 th:text="'消息:'+ ${message}"></h4>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用RestController返回页面信息</title>
</head>
<body>
<h3>使用RestController返回页面信息</h3>
<h4 th:text="'消息:'+ ${message}"></h4>
</body>
</html>

其中modelAndView.addObject("message", "这是消息内容");是可选的

使用方式2

在控制器方法上使用ModelAndView

@GetMapping("page/test2")
public ModelAndView test2(ModelAndView modelAndView) {
    modelAndView.addObject("hello", "你好");
    modelAndView.setViewName("page/test2");
    return modelAndView;
}