Spring Boot静态资源
放置静态资源的目录
一般放置在 src/main/resources/static目录中
当然我们也可以自己去创建一个文件夹来存放
这里我创建了st目录来存放静态资源
由于是我们自己创建的所以我们需要告诉SpringBoot
配置yaml让SpringBoot识别自建的静态资源目录
我们需要在application.yaml中配置如下:
#配置静态资源相关事务
spring:
#对静态资源存放目录进行配置
#让资源存放在st目录下
web:
resources:
static-locations:
[ classpath:/st/]
#配置静态资源访问模式,即需要在前加/static/才能访问到我们的静态资源
mvc:
static-path-pattern: /static/**
访问结果如下
当然还是推荐大家使用static作为默认静态资源存放目录
自定义Favicon
将.ico后缀的图标资源放置在静态目录下
如果大家没有这种图片可以使用“格式工厂”这个软件对其他图片进行转换
常用参数注解
1.获取路径变量@PathVariable
源码:
/**
* Annotation which indicates that a method parameter should be bound to a URI template
* variable. Supported for {@link RequestMapping} annotated handler methods.
*
* <p>If the method parameter is {@link java.util.Map Map<String, String>}
* then the map is populated with all path variable names and values.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
* @see RequestMapping
* @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the path variable to bind to.
* @since 4.3.3
*/
@AliasFor("value")
String name() default "";
/**
* Whether the path variable is required.
* <p>Defaults to {@code true}, leading to an exception being thrown if the path
* variable is missing in the incoming request. Switch this to {@code false} if
* you prefer a {@code null} or Java 8 {@code java.util.Optional} in this case.
* e.g. on a {@code ModelAttribute} method which serves for different requests.
* @since 4.3.3
*/
boolean required() default true;
}
源码翻译(解释):
表示方法参数应该使用@PathVariable注释绑定到URL模板
变量支持:@RequestMapping注解处理方法
@RequestMapping("/userId/{id}/username/{username}")
如果使用的是Map<String,String>的形式来获取,那么Map可以获取到所有路径变量的名称和值的键值对
@PathVariable Map<String,String> userObject
@RequestMapping 和 @GetMapping @PostMapping
@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。
ControllerPara.java:
package com.example.day2.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class ControllerPara {
//使用@RequestMapping("/userId/{id}/username/{username}")也是可以的
@GetMapping("/userId/{id}/username/{username}")
public Map<String,Object> getMsg(@PathVariable Integer id,
@PathVariable String username,
@PathVariable Map<String,String> userObject){
Map<String,Object> map = new HashMap<>();
map.put("id",id);
map.put("username",username);
map.put("user",userObject);
return map;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/userId/1/username/zhangsan">/user/{id}+...</a>
</body>
</html>
对应解释
结果展示
2.获取 请求头@RequestHeader
源码
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
/**
* Annotation which indicates that a method parameter should be bound to a web request header.
*
* <p>Supported for annotated handler methods in Spring MVC and Spring WebFlux.
*
* <p>If the method parameter is {@link java.util.Map Map<String, String>},
* {@link org.springframework.util.MultiValueMap MultiValueMap<String, String>},
* or {@link org.springframework.http.HttpHeaders HttpHeaders} then the map is
* populated with all header names and values.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
* @see RequestMapping
* @see RequestParam
* @see CookieValue
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestHeader {
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the request header to bind to.
* @since 4.2
*/
@AliasFor("value")
String name() default "";
/**
* Whether the header is required.
* <p>Defaults to {@code true}, leading to an exception being thrown
* if the header is missing in the request. Switch this to
* {@code false} if you prefer a {@code null} value if the header is
* not present in the request.
* <p>Alternatively, provide a {@link #defaultValue}, which implicitly
* sets this flag to {@code false}.
*/
boolean required() default true;
/**
* The default value to use as a fallback.
* <p>Supplying a default value implicitly sets {@link #required} to
* {@code false}.
*/
String defaultValue() default ValueConstants.DEFAULT_NONE;
}
源码翻译(解释)
表示方法参数应绑定到web请求头的注解。
在SpringMVC和SpringWebFlux中支持带注释的处理程序方法
如果方法参数为Map<String,String>、MultiValueMap<String,String>或HttpHeaders,则映射将填充所有头名称和值
ControllerPara.java
package com.example.day2.controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
public class ControllerPara {
@RequestMapping("/userId/{id}/username/{username}")
public Map<String,Object> getMsg(@RequestHeader("User-Agent") String userAgent,
@RequestHeader Map<String,String> header){
Map<String,Object> map = new HashMap<>();
map.put("User-Agent",userAgent);
map.put("Header",header);
return map;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/userId/1/username/zhangsan">get Header</a>
</body>
</html>
结果展示:
3.获取请求参数@RequestParam
源码
/**
* Annotation which indicates that a method parameter should be bound to a web
* request parameter.
*
* <p>Supported for annotated handler methods in Spring MVC and Spring WebFlux
* as follows:
* <ul>
* <li>In Spring MVC, "request parameters" map to query parameters, form data,
* and parts in multipart requests. This is because the Servlet API combines
* query parameters and form data into a single map called "parameters", and
* that includes automatic parsing of the request body.
* <li>In Spring WebFlux, "request parameters" map to query parameters only.
* To work with all 3, query, form data, and multipart data, you can use data
* binding to a command object annotated with {@link ModelAttribute}.
* </ul>
*
* <p>If the method parameter type is {@link Map} and a request parameter name
* is specified, then the request parameter value is converted to a {@link Map}
* assuming an appropriate conversion strategy is available.
*
* <p>If the method parameter is {@link java.util.Map Map<String, String>} or
* {@link org.springframework.util.MultiValueMap MultiValueMap<String, String>}
* and a parameter name is not specified, then the map parameter is populated
* with all request parameter names and values.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Sam Brannen
* @since 2.5
* @see RequestMapping
* @see RequestHeader
* @see CookieValue
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the request parameter to bind to.
* @since 4.2
*/
@AliasFor("value")
String name() default "";
/**
* Whether the parameter is required.
* <p>Defaults to {@code true}, leading to an exception being thrown
* if the parameter is missing in the request. Switch this to
* {@code false} if you prefer a {@code null} value if the parameter is
* not present in the request.
* <p>Alternatively, provide a {@link #defaultValue}, which implicitly
* sets this flag to {@code false}.
*/
boolean required() default true;
/**
* The default value to use as a fallback when the request parameter is
* not provided or has an empty value.
* <p>Supplying a default value implicitly sets {@link #required} to
* {@code false}.
*/
String defaultValue() default ValueConstants.DEFAULT_NONE;
}
源码翻译(解释)
这个注解指示方法参数要绑定到web请求参数
在SpringMVC中,“请求参数”映射到多部分请求中的查询参数、表单数据和部分。这是因为ServletAPI将查询参数和表单数据组合到一个称为“参数”的映射中,其中包括请求主体的自动解析。
在SpringWebFlux中,“请求参数”仅映射到查询参数。要处理所有3部分数据、查询数据、表单数据和多部分数据,可以使用数据绑定到使用ModelAttribute注释的命令对象。
若方法参数类型是Map<String,String>或MultiValueMap<String,String>且未指定参数名称,则Map参数将填充所有请求参数名称和值。
@RequestParam("age") Integer age,
@RequestParam("habits") List<String> habits,
@RequestParam Map<String, String> details
ControllerPara.java
package com.example.day2.controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class ControllerPara {
@RequestMapping("/userId/{id}/username/{username}")
public Map<String,Object> getMsg(@RequestParam("age") Integer age,
@RequestParam("habits") List<String> habits,
@RequestParam Map<String, String> details){
Map<String,Object> map = new HashMap<>();
map.put("age",age);
map.put("habits",habits);
map.put("details",details);
return map;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/userId/1/username/zhangsan
?age=20&habits=play video game&habits=run">get Details</a>
</body>
</html>
注意
?age=20&habits=play video game&habits=run"
结果展示
4.获取cookie的值@CookieValue
源码
/**
* Annotation to indicate that a method parameter is bound to an HTTP cookie.
*
* <p>The method parameter may be declared as type {@link javax.servlet.http.Cookie}
* or as cookie value type (String, int, etc.).
*
* <p>Note that with spring-webmvc 5.3.x and earlier, the cookie value is URL
* decoded. This will be changed in 6.0 but in the meantime, applications can
* also declare parameters of type {@link javax.servlet.http.Cookie} to access
* the raw value.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
* @see RequestMapping
* @see RequestParam
* @see RequestHeader
* @see org.springframework.web.bind.annotation.RequestMapping
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CookieValue {
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the cookie to bind to.
* @since 4.2
*/
@AliasFor("value")
String name() default "";
/**
* Whether the cookie is required.
* <p>Defaults to {@code true}, leading to an exception being thrown
* if the cookie is missing in the request. Switch this to
* {@code false} if you prefer a {@code null} value if the cookie is
* not present in the request.
* <p>Alternatively, provide a {@link #defaultValue}, which implicitly
* sets this flag to {@code false}.
*/
boolean required() default true;
/**
* The default value to use as a fallback.
* <p>Supplying a default value implicitly sets {@link #required} to
* {@code false}.
*/
String defaultValue() default ValueConstants.DEFAULT_NONE;
}
源码翻译(解释)
指示方法参数绑定到HTTP cookie。
方法参数可以声明为javax类型。servlet。http。Cookie或作为Cookie值类型(字符串、int等)
@CookieValue("cookie") Cookie cookie
ControllerPara.java
package com.example.day2.controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class ControllerPara {
@RequestMapping("/userId/{id}/username/{username}")
public Map<String,Object> getMsg(@CookieValue("cookie") Cookie cookie
){
Map<String,Object> map = new HashMap<>();
map.put("cookie",cookie);
return map;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/userId/1/username/zhangsan
?age=20&habits=play video game&habits=run">get Details</a>
</body>
</html>
结果展示
这里无法获取到cookie的值,是因为我们所有的请求都没有携带cookie
5.获取请求体【post】@RequestBody
表单提交
结合注解@PostMapping来指定提交地址
源码
/**
* Annotation indicating a method parameter should be bound to the body of the web request.
* The body of the request is passed through an {@link HttpMessageConverter} to resolve the
* method argument depending on the content type of the request. Optionally, automatic
* validation can be applied by annotating the argument with {@code @Valid}.
*
* <p>Supported for annotated handler methods.
*
* @author Arjen Poutsma
* @since 3.0
* @see RequestHeader
* @see ResponseBody
* @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {
/**
* Whether body content is required.
* <p>Default is {@code true}, leading to an exception thrown in case
* there is no body content. Switch this to {@code false} if you prefer
* {@code null} to be passed when the body content is {@code null}.
* @since 3.2
*/
boolean required() default true;
}
源码翻译(解释)
指示方法参数的注释应绑定到web请求的主体。请求主体通过HttpMessageConverter传递,以根据请求的内容类型解析方法参数。或者,可以通过使用@Valid注释参数来应用自动验证。
支持带注释的处理程序方法。
@RequestBody String body
ControllerPara.java
package com.example.day2.controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class ControllerPara {
@PostMapping("/save")
public Map<String,Object> postMsg(@RequestBody String body){
Map<String,Object> map = new HashMap();
map.put("body",body);
return map;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/save" method="post">
@RequestBody<br>
username:<input name="username" /><br>
password:<input name="password" type="password" /><br>
<input type="submit" value="submit">
</form>
</body>
</html>
结果展示
6.获取request域属性@RequestAttribute
源码
/**
* Annotation to bind a method parameter to a request attribute.
*
* <p>The main motivation is to provide convenient access to request attributes
* from a controller method with an optional/required check and a cast to the
* target method parameter type.
*
* @author Rossen Stoyanchev
* @since 4.3
* @see RequestMapping
* @see SessionAttribute
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestAttribute {
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the request attribute to bind to.
* <p>The default name is inferred from the method parameter name.
*/
@AliasFor("value")
String name() default "";
/**
* Whether the request attribute is required.
* <p>Defaults to {@code true}, leading to an exception being thrown if
* the attribute is missing. Switch this to {@code false} if you prefer
* a {@code null} or Java 8 {@code java.util.Optional} if the attribute
* doesn't exist.
*/
boolean required() default true;
}
源码翻译(解释)
注释将方法参数绑定到请求属性。
主要目的是通过可选/必需的检查和对目标方法参数类型的转换,方便地从控制器方法访问请求属性。
@RequestAttribute("msg") String msg,
@RequestAttribute("code") Integer code
RequestAttriControlle.java
package com.example.day2.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@Controller
public class RequestAttriController {
@RequestMapping("/test")
public String go(HttpServletRequest request) {
request.setAttribute("msg", "success");
request.setAttribute("code", 200);
return "forward:/success";
}
@ResponseBody
@RequestMapping("/success")
public Map test(@RequestAttribute("msg") String msg,
@RequestAttribute("code") Integer code) {
Map<String, Object> map = new HashMap<>();
map.put("msg", msg);
map.put("code", code);
return map;
}
}