Day4-SpringBoot-Web开发

+静态资源访问

静态资源目录

只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources

访问 : 当前项目根路径/ + 静态资源名

原理分析 :

静态映射/**。请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

改变默认的静态资源路径

spring:
mvc:
static-path-pattern: /res/** # 指定前缀

resources:
static-locations: [classpath:/haha/] # 指定那些路径下的静态资源可以访问到

当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找


webjar

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径


<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>

+欢迎页支持

  • 静态资源路径下 index.html

  • 可以配置静态资源路径

  • 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问

spring:
# mvc:
# static-path-pattern: /res/** 这个会导致welcome page功能失效

resources:
static-locations: [classpath:/haha/]

+ 自定义 Favicon

favicon.ico 放在静态资源目录下即可。 网站logo


请求参数处理

请求映射

rest使用与原理

  • @xxxMapping;

  • Rest风格支持(使用HTTP请求方式动词来表示对资源的操作

  • 以前:**/getUser 获取用户 /deleteUser 删除用户 /editUser 修改用户 /saveUser 保存用户

  • 现在: /user GET-**获取用户 DELETE-**删除用户 PUT-**修改用户 POST-**保存用户

  • 核心Filter;HiddenHttpMethodFilter

  • 用法: 表单method=post,隐藏域 _method=put

  • SpringBoot中手动开启

    @RequestMapping(value = "/user",method = RequestMethod.GET)  //@GetMappping("/user")
public String getUser(){
return "GET-张三";
}

@RequestMapping(value = "/user",method = RequestMethod.POST)
public String saveUser(){
return "POST-张三";
}


@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String putUser(){
return "PUT-张三";
}

@RequestMapping(value = "/user",method = RequestMethod.DELETE)
public String deleteUser(){
return "DELETE-张三";
}


@Bean
@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}


//自定义filter 改变前端隐藏域中 _method
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
methodFilter.setMethodParam("_m");
return methodFilter;
}
<form method="post" action="/user">
<input name="m" hidden value="PUT"> <!-- 这里可以自定义 -->
<input type="submit" value="提交PUT请求">
</form>

Rest原理(表单提交要使用REST的时候)

  • 表单提交会带上_method=PUT

  • 请求过来被HiddenHttpMethodFilter拦截

  • 请求是否正常,并且是POST

  • 获取到_method的值。

  • 兼容以下请求;PUT.DELETE.PATCH

  • 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。

  • 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用**requesWrapper的。**

Rest使用客户端工具,

  • 如PostMan直接发送Put、delete等方式请求,无需Filter
spring:
mvc:
hiddenmethod:
filter:
enabled: true #开启页面表单的Rest功能