SpringMVC 中的常用注解和用法
文章目录
一、SpringMVC 是什么?
Spring Web MVC 是基于 Servlet API 构建的原始 Web 框架,从⼀开始就包含在 Spring 框架中。它的正式名称“Spring Web MVC”来⾃其源模块的名称(Spring-webmvc),但它通常被称为"SpringMVC".总结来说,Spring MVC 是⼀个实现了 MVC 模式的 Web 框架。
二、SpringMVC 中的常用注解和用法
1.@RequestMapping
@RequestMapping 是Spring Web MVC 应用程序中最常被用到的注解之一,它是用来注册接口的路由映射的。(注意,@RequestMapping可以接收post或get请求)。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String sayhello(){
return "hello world";
}
}
我们只需要启动Springboost访问http://localhost:8080/hello网址就可以看到"hello world"。

2.@RequestParam
某些特殊的情况下,前端传递的参数 key 和我们后端接收的 key 可以不⼀致,⽐如前端传递了⼀个usename给后端,而后端是使用username 字段来接收的,这样就会出现参数接收不到的情况,如果出现这种情况,我们就可以使@RequestParam 来重命名前后端的参数值。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String sayhello(String username){
return username;
}
}
我们用postman来模拟前端传参。
当用username发送参数时,返回的结果时空的,也就是后端没有接受到前端传递的参数,原因就是前端的发送的参数usename与后端的接收参数username名字不一致导致的。所以,@RequestParam就登场了。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String sayhello(@RequestParam("usename") String username){
return username;
}
}
不管你前端发过来色的是什么,都可以用@RequestParam重命名参数给后端

这下就不是空了,但是要注意使⽤用@RequestParam 进行参数重命名时, 参数就变成了必传参数,如果我现在啥也不穿就会报错!!

所以我们可以加上@RequestParam(value = “usename”,required = false),这样就可以解决上面不传参数的问题。
默认情况下,请求中参数名相同的多个值,是封装到数组. 如果要封装到集合,要使用@RequestParam 绑定参数关系
@RequestMapping("/v7")
public String v7(@RequestParam() List<String> list){
return list.toString();
}
3.@RequestBody
接收前端发送的JSON对象, 需要使⽤ @RequestBody 注解来接收。
@RestController()
@RequestMapping("/param")
public class ParagramController {
@RequestMapping("/v8")
public String v8(@RequestBody User user){
return user.toString();
}
}
通过发送JSON数据到后端,可以看到后端通过User对象接受了JSON数据

4.@PathVariable
默认传递参数写在URL上,SpringMVC就可以获取到
@RestController()
@RequestMapping("/param"){
@RequestMapping("/v9/{getId}/{gender}")
public String v10(@PathVariable("getId") Integer id,@PathVariable("gender") String gender){
return id+gender;
}
}
直接在URL中加上/23/男就行。

@PathVariable会自动重URL上获取你指定的参数
5.@RequestPart
@RequestPart就是上传文件
@RestController()
@RequestMapping("/param")
public class ParagramController {
@RequestMapping("/v10")
public String v11(@RequestPart("file") MultipartFile file){
String filename = file.getOriginalFilename();
return filename;
}
}
通过postman发送请求

可以看到,我上传了一个名字为:如果打开startup.bat一闪而过,可以在环境变量系统变量那里.txt的file,postman请求后,后端返回了file的名字
结束,求赞!!!
788

被折叠的 条评论
为什么被折叠?



