springboot系列八: springboot静态资源访问,Rest风格请求处理, 接收参数相关注解

在这里插入图片描述


⬅️ 上一篇: springboot系列七: Lombok注解,Spring Initializr,yaml语法


🎉 欢迎来到 springboot系列八: springboot静态资源访问,Rest风格请求处理, 接收参数相关注解 🎉

在本篇文章中,我们将探讨如何在 Spring Boot 中处理静态资源访问、实现 Rest 风格的请求处理以及使用接收参数相关的注解。这些功能将帮助您更高效地开发和管理 Spring Boot 应用程序。


🔧 本篇需要用到的项目:


WEB开发-静态资源访问

官方文档

在线文档:

在这里插入图片描述

基本介绍

1.只要静态资源放在类路径下: /static, /public, /resources, /META-INF/resources 可以被直接访问 - 对应文件 WebProperties.java

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { “classpath:/META-INF/resources/”, “classpath:/resources/”, “classpath:/static/”, “classpath:/public/” };

2.常见静态资源: JS, CSS, 图片(.jpg, .png, .gif, .bmp, .svg), 字体文件(Fonts)等

3.访问方式: 默认: 项目根路径 / + 静态资源名, 比如 http://localhost:8080/1.jpg - 设置WebMvcProperties.java
private String staticPathPattern = “/**”;

在这里插入图片描述

快速入门

1.创建SpringBoot项目springbootweb, 这里使用灵活配置方式来创建项目, 参考springboot快速入门

2.创建相关静态资源目录, 并放入测试图片, 没有目录, 自己创建即可, 浏览器访问 http://localhost:8080/4.png , 完成测试.

在这里插入图片描述

注意事项和细节

1.静态资源访问原理: 静态映射是 /** , 也就是对所有请求拦截. 请求进来, 先看Controller能不能处理, 不能处理的请求交给静态资源处理器, 如果静态资源找不到则响应404页面.

在这里插入图片描述

2.改变静态资源访问前缀, 比如我们希望 http://localhost:8080/image/1.png 去请求静态资源.

应用场景: http://localhost:8080/1.png, 静态资源访问前缀和控制器请求路径冲突

在这里插入图片描述

被Controller拦截

在这里插入图片描述

解决方案:
1)创建src/main/resources/application.yml

spring:
  mvc:
    static-path-pattern: /image/**

2)启动, http://localhost:8080/image/1.png 测试

在这里插入图片描述

3.改变默认的静态资源路径, 比如希望在类路径下增加zzwimg目录 作为静态资源路径, 并完成测试.

1)如图所示
在这里插入图片描述

2)配置 application.yml, 增加路径

spring:
  mvc:
    static-path-pattern: /image/** #修改静态资源访问 路径/前缀
  web:
    resources:
      #修改/指定 静态资源的访问路径/位置
      static-locations: [classpath:/zzwimg/] #String[] staticLocations

在这里插入图片描述

3)测试, 浏览器输入 http://localhost:8080/image/6.png(没错, 是image/6.png, 不是image/zzwimg/6.png), 一定要保证工作目录target下 有 6.png, 如果没有, 请rebuild下项目, 再重启项目.

4)如果你配置 static-locations, 原来的访问路径就会被覆盖, 如果需要保留, 再指定一下即可.

  web:
    resources:
      #修改/指定 静态资源的访问路径/位置 String[] staticLocations
      static-locations: ["classpath:/zzwimg/", "classpath:/META-INF/resources/",
                         "classpath:/resources/", "classpath:/static/", "classpath:/public/"]

Rest风格请求处理

基本介绍

1.Rest风格支持 (使用HTTP请求方式来表示对资源的操作)

2.举例说明
请求方式: /monster
GET-获取妖怪
DELETE-删除妖怪
PUT-修改妖怪
POST-保存妖怪

应用实例

1.创建src/main/java/com/zzw/springboot/controller/MonsterController.java

@RestController
public class MonsterController {

    //等价的写法
    //@RequestMapping(value = "/monster", method= RequestMethod.GET)
    @GetMapping("/monster")
    public String getMonster() {
        return "GET-查询妖怪";
    }

    //等价写法
    //@RequestMapping(value = "/monster", method = RequestMethod.POST)
    @PostMapping("/monster")
    public String saveMonster() {
        return "POST-保存妖怪";
    }

    //等价写法
    @RequestMapping(value = "/monster", method = RequestMethod.PUT)
    @PutMapping("/monster")
    public String putMonster() {
        return "PUT-修改妖怪";
    }

    //等价写法
    @RequestMapping(value = "/monster", method = RequestMethod.DELETE)
    @DeleteMapping("/monster")
    public String deleteMonster() {
        return "DELETE-删除妖怪";
    }
}

2.使用Postman完成测试, 请求url: http://localhost:8080/monster

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

注意事项和细节

在SpringMVC中我们学过,SpringMVC系列四: Rest-优雅的url请求风格

1.客户端是Postman 可以直接发送 Put, Delete等方式请求, 可不设置Filter.

2.如果要SpringBoot支持 页面表单的Rest功能, 则需要注意如下细节

1)Rest风格请求核心Filter: HiddenHttpMethodFilter, 表单请求会被HiddenHttpMethodFilter拦截, 获取到表单_method的值, 再判断是PUT/DELETE/PATCH(注意: PATCH方法是新引入的, 是对PUT方法的补充, 用来对已知资源进行局部更新, PATCH和PUT方法的区别)

2)如果要SpringBoot支持 页面表单的Rest功能, 需要在application.yml启用filter功能, 否则无效.

3)修改application.yml, 启用filter功能

spring:
  mvc:
    static-path-pattern: /image/** #修改静态资源访问 路径/前缀
    hiddenmethod:
      filter:
        enabled: true #启动HiddenHttpMethodFilter, 支持rest

4)修改对应的页面, 然后测试.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>rest</title>
</head>
<body>
<h1>测试rest风格的url, 完成get请求</h1>
<form action="/monster" method="get">
  u: <input type="text" name="name"><br/>
  <input type="submit" value="点击提交">
</form>
<h1>测试rest风格的url, 完成post请求</h1>
<form action="/monster" method="post">
  u: <input type="text" name="name"><br/>
  <input type="submit" value="点击提交">
</form>
<h1>测试rest风格的url, 完成put请求</h1>
<form action="/monster" method="post">
    <!--通过隐藏域传递_method参数指定值-->
    <input type="hidden" name="_method" value="PUT">
  u: <input type="text" name="name"><br/>
  <input type="submit" value="点击提交">
</form>
<h1>测试rest风格的url, 完成delete请求</h1>
<form action="/monster" method="post">
    <input type="hidden" name="_method" value="delete">
  u: <input type="text" name="name"><br/>
  <input type="submit" value="点击提交">
</form>
</body>
</html>

思考题

1.为什么这里 return “GET-查询妖怪”,返回的是字符串,而不是转发到对应的资源文件?

1)修改src/main/java/com/zzw/springboot/controller/MonsterController.java

//@RestController
@Controller
public class MonsterController {

    /**
     * 解读
     * 因为@RestController是一个复合注解,含有@ResponseBody注解,所以sprintboot底层(springmvc),
     * 在处理return "xxx"时, 会以 @ResponseBody 注解的方式进行解析处理, 即返回字符串"xxx". 而不会使用
     * 视图解析器来处理. 如果我们把 @RestController 改成 @Controller, 当你访问getMonster()时, 
     * 会使用到视图解析器(如果配置了的话),即如果你有xxx.html, 就会请求转发到xxx.html, 如果没有xxx.html, 就会报404.
     * @return
     */
    @GetMapping("/monster")
    public String getMonster() {
        return "GET-查询妖怪";
    }

    @RequestMapping("/go")
    public String go() {
        //顺序 http://localhost:8088/go
        // => 1.如果没有配置视图解析器, 就看Controller有没有 /hello
        // => 2.如果有, 就请求转发到 /hello, 如果没有 /hello 映射, 就报错
        // => 4.如果配置了视图解析器, 就走视图解析器
        return "hello";
    }
}

2)浏览器请求 http://localhost:8088/go,报 404 错误,因为找不到资源文件 hello.html

解决方案

1.如果没有配置视图解析器, 访问 http://localhost:8088/go, 会请求转发到 /hello
1)修改src/main/java/com/zzw/springboot/controller/HiController.java

@RestController
public class HiController {

    //@RequestMapping("/hi") //模拟一下, 发现默认请求的路径和资源的名字冲突
    @RequestMapping("/hello")
    public String hi(){
        return "hi~";
    }
}

2)测试

在这里插入图片描述

2.如果配置了视图解析器, 访问 http://localhost:8088/go, 就会请求转发到 hello.html
1)新建src/main/resources/public/hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello页面</title>
</head>
<body>
<h2>hello页面</h2>
</body>
</html>

2)application.yml配置视图解析器

spring:
  mvc:
    #尽量用默认的, 因为springboot有个约定优于配置的思想
    #static-path-pattern: /image/** #修改静态资源访问 路径/前缀
    hiddenmethod:
      filter:
        enabled: true #启动HiddenHttpMethodFilter, 支持rest
    view: #修改默认的视图配置
#      prefix: / # No mapping for GET /hello.html
      prefix: / #这里需要注意prefix 需要和当前的static-path-pattern保持一致
      suffix: .html

3)测试

在这里插入图片描述

接收参数相关注解

基本介绍

1.SpringBoot 接收客户端提交数据 / 参数会使用到相关注解.

2.详细学习 @PathVariable, @RequestHeader, @ModelAttribute, @RequestParam, @CookieValue, @RequestBody

应用实例

●需求:
演示各种方式提交数据/参数给服务器, 服务器如何使用注解接收

@PathVariable

1.创建src/main/resources/public/index.html
JavaWeb系列十: web工程路径专题

<h1>跟着老韩学springboot</h1>
基本注解:
<hr/>
<!--
    1. web工程路径知识:
    2. / 会解析成 http://localhost:8080
    3. /monster/100/king => http://localhost:8080/monster/100/king
    4. 如果不带 /, 会以当前路径为基础拼接
/-->
<a href="/monster/100/king">@PathVariable-路径变量 monster/100/king</a><br/><br/>
</body>

2.创建src/main/java/com/zzw/springboot/controller/ParameterController.java
url占位符回顾

@RestController
public class ParameterController {

    /**
     * 1./monster/{id}/{name} 构成完整请求路径
     * 2.{id} {name} 就是占位变量
     * 3.@PathVariable("name"): 这里 name 和 {name} 命名保持一致
     * 4.String name_ 这里自定义, 这里韩老师故意这么写
     * 5.@PathVariable Map<String, String> map 把所有传递的值传入map
     * 6.可以看下@pathVariable源码
     * @return
     */
    @GetMapping("/monster/{id}/{name}")
    public String pathVariable(@PathVariable("id") Integer id,
                               @PathVariable("name") String name,
                               @PathVariable Map<String, String> map) {
        System.out.println("id = " + id + "\nname = " + name + "\nmap = " + map);
        return "success";
    }
}

3.测试 http://localhost:8088/monster/100/king

在这里插入图片描述
在这里插入图片描述

@RequestHeader

需求: 演示@RequestHeader使用.

1.修改src/main/resources/public/index.html

<a href="/requestHeader">@RequestHeader-获取http请求头</a><br/><br/>

2.修改ParameterController.java
JavaWeb系列八: WEB 开发通信协议(HTTP协议)

/**
 * 1. @RequestHeader("Cookie") 获取http请求头的 cookie信息
 * 2. @RequestHeader Map<String, String> header 获取到http请求的所有信息
 */
@GetMapping("/requestHeader")
public String requestHeader(@RequestHeader("Host") String host,
                            @RequestHeader Map<String, String> header) {
    System.out.println("host = " + host + "\nheader = " + header);
    return "success";
}

3.测试

在这里插入图片描述
在这里插入图片描述

@RequestParam

需求: 演示@RequestParam使用.

1.修改src/main/resources/public/index.html

<a href="/hi?name=赵志伟&fruit=apple&fruit=pear&address=上海&id=3">@RequestParam-获取请求参数</a><br/><br/>

2.修改ParameterController.java
SpringMVC系列五: SpringMVC映射请求数据

/**
 * 如果我们希望将所有的请求参数的值都获取到, 可以通过
 * @RequestParam Map<String, String> params
 */
@GetMapping("/hi")
public String hi(@RequestParam(value = "name") String username,
                 @RequestParam(value = "fruit") List<String> fruits,
                 @RequestParam Map<String, String> params) {
    System.out.println("username = " + username + "\nfruits = "
            + fruits + "\nparams = " + params);
    return "success";
}

3.测试

在这里插入图片描述
在这里插入图片描述

@CookieValue

需求: 演示@CookieValue使用.

1.修改src/main/resources/public/index.html

<a href="/cookie">@CookieValue-获取cookie值</a>

2.修改ParameterController.java
JavaWeb系列十一: Web 开发会话技术(Cookie, Session)

/**
 * 因为我们的浏览器目前没有cookie, 我们可以自己设置cookie
 * 如果要测试, 可以先写一个方法, 在浏览器创建对应的cookie
 * 说明:
 * 1. value = "cookie_key" 表示接收名字为 cookie_key的cookie
 * 2. 如果浏览器携带来对应的cookie, 那么后面的参数是String, 则接收到的是对应的value
 * 3. 后面的参数是Cookie, 则接收到的是封装好的对应的cookie
 */
@GetMapping("/cookie")
public String cookie(@CookieValue(value = "cookie_key") String cookie_value,
                     @CookieValue(value = "username") Cookie cookie,
                     HttpServletRequest request) {
    System.out.println("cookie_value = " + cookie_value
            + "\nusername = " + cookie.getName() + "-" + cookie.getValue());
    Cookie[] cookies = request.getCookies();
    
    for (Cookie cookie1 : cookies) {
        System.out.println("cookie1 = " + cookie1.getName() + "-" + cookie1.getValue());
    }
    return "success";
}

3.测试
在这里插入图片描述
在这里插入图片描述

@RequestBody

需求: 演示@RequestBody使用.

1.修改src/main/resources/public/index.html

<h1>测试@RequestBody获取数据: 获取POST请求体</h1>
<form action="/save" method="post">
    名字: <input type="text" name="name"><br/>
    年龄: <input type="text" name="age"><br/>
    <input type="submit" value="提交"/>
</form>

2.修改ParameterController.java
SpringMVC系列十: 中文乱码处理与JSON处理

/**
 * @RequestBody 是整体取出Post请求内容
 */
@PostMapping("/save")
public String postMethod(@RequestBody String content) {
    System.out.println("content = " + content);//content = name=zzw&age=23
    return "sucess";
}

3.测试

在这里插入图片描述

content = name=zzw&age=123

@RequestAttribute

需求: 演示@RequestAttribute使用. 获取request域的属性.

1.修改src/main/resources/public/index.html

<a href="/login">@RequestAttribute-获取request域属性</a>

2.创建RequestController.java
SpringMVC系列十: 中文乱码处理与JSON处理

@Controller
public class RequestController {
    @RequestMapping("/login")
    public String login(HttpServletRequest request) {
        request.setAttribute("user", "赵志伟");//向request域中添加的数据
        return "forward:/ok";//请求转发到 /ok
    }

    @GetMapping("/ok")
    @ResponseBody
    public String ok(@RequestAttribute(value = "user", required = false) String username,
                     HttpServletRequest request) {
        //获取到request域中的数据
        System.out.println("username--" + username);
        System.out.println("通过servlet api 获取 username-" + request.getAttribute("user"));
        return "success"; //返回字符串, 不用视图解析器
    }
}

3.测试…

@SessionAttribute

需求: 演示@SessionAttribute使用. 获取session域的属性.

1.修改src/main/resources/public/index.html

<a href="/login">@SessionAttribute-获取session域属性</a>

2.创建RequestController.java
JavaWeb系列十一: Web 开发会话技术(Cookie, Session)

@Controller
public class RequestController {
    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpSession session) {
        request.setAttribute("user", "赵志伟");//向request域中添加的数据
        session.setAttribute("mobile", "黑莓");//向session域中添加的数据
        return "forward:/ok";//请求转发到 /ok
    }

    @GetMapping("/ok")
    @ResponseBody
    public String ok(@RequestAttribute(value = "user", required = false) String username,
                     HttpServletRequest request,
                     @SessionAttribute(value = "mobile", required = false) String mobile,
                     HttpSession session) {
        //获取到request域中的数据
        System.out.println("username--" + username);
        System.out.println("通过servlet api 获取 username-" + request.getAttribute("user"));

        //获取session域中的数据
        System.out.println("mobile--" + mobile);
        System.out.println("通过HttpSession 获取 mobile-" + session.getAttribute("mobile"));
        return "success"; //返回字符串, 不用视图解析器
    }
}

3.测试…


🔜 下一篇预告: [即将更新,敬请期待]


📚 目录导航 📚

  1. springboot系列一: springboot初步入门
  2. springboot系列二: sprintboot依赖管理
  3. springboot系列三: sprintboot自动配置
  4. springboot系列四: sprintboot容器功能
  5. springboot系列五: springboot底层机制实现 上
  6. springboot系列六: springboot底层机制实现 下
  7. springboot系列七: Lombok注解,Spring Initializr,yaml语法
  8. springboot系列八: springboot静态资源访问,Rest风格请求处理, 接收参数相关注解

💬 读者互动 💬
在学习 Spring Boot 静态资源访问和 Rest 风格请求处理的过程中,您有哪些新的发现或疑问?欢迎在评论区留言,让我们一起讨论吧!😊


相关推荐

  1. SpringBoot缓存关注的使用

    2024-07-09 17:12:08       48 阅读
  2. springboot之Conditional关注

    2024-07-09 17:12:08       24 阅读
  3. springboot请求参数

    2024-07-09 17:12:08       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 17:12:08       51 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 17:12:08       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 17:12:08       44 阅读
  4. Python语言-面向对象

    2024-07-09 17:12:08       55 阅读

热门阅读

  1. Docker

    Docker

    2024-07-09 17:12:08      21 阅读
  2. C++多线程学习笔记

    2024-07-09 17:12:08       24 阅读
  3. 实现基于Spring Cloud的事件驱动微服务

    2024-07-09 17:12:08       23 阅读
  4. js使用websocket,vue使用websocket,copy即用

    2024-07-09 17:12:08       22 阅读
  5. PostgreSQL的扩展(extensions)-常用的扩展-pg_profile

    2024-07-09 17:12:08       26 阅读
  6. Spring Boot整合MongoDB实现事务管理

    2024-07-09 17:12:08       23 阅读
  7. Solana RPC 的工作原理

    2024-07-09 17:12:08       22 阅读