SpringMVC常用注解

本文详细介绍了SpringBoot中的@RequestMapping注解用于接口路由映射的原理和使用方法,包括GET、POST等HTTP方法的指定,参数的接收,对象的传递,以及@RequestParam参数重命名的处理。同时,还展示了如何处理文件上传的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

URL路由映射
@RequestMapping
该注解用以注册接口的路由映射

路由映射:当用户访问一个url后,将请求对应到某个类的某个方法的过程

用法:该注解可以加在类上也可以加载方法上

@Controller
@ResponseBody
public class StudentController {
    @RequestMapping("/hi")
    public String sayHi(HttpServletRequest request) {
        return "hello world";
}

这样通过访问 http://localhost:8080/hi 在页面上看到一个hello world

@Controller 是spring框架启动时会加载 注册到Bean中
@ResponseBody 用来将JAVA对象转换为json格式的数据,写入response对象的body中。也相当于告诉程序我返回的不是一个页面

如果不加@ResponseBody会发现访问报错,因为他以为你返回了一个页面,结果并没有。
为了简便写法,可以用 @RestController 注解

@RestController
public class StudentController {
    @RequestMapping("/hi")
    public String sayHi(HttpServletRequest request) {
        return "hello world";
}

@RestController的作用就相当于@Controller + @ResponseBody

@RequestMapping默认为get方法

@RequestMapping("/hi") //这样写就是默认的get方法

当然 你可以指定方法
写法:

@RequestMapping(value = "/hi",method = RequestMethod.POST)

还可以使用简便的注解:

  • @PostMapping
  • @GetMapping
  • Put、Delete等都有对应的注解,为方法名加个Mapping

传递单个参数

在servlet中,用过一个方法获取参数

request.getParameter();

在springboot里依然可以用,但是我们有更简便的方法来获取参数
——直接在方法中定义参数,springboot会自动根据参数名找到对应的值,形参名和key值必须相同
例如:

@RestController
public class StudentController {
    @RequestMapping("/hi")
    public String sayHi(String name) {
        return name;
    }
}

http://localhost:8080/hi?name=rich访问
springboot就会自动找到key为name的值,赋值给方法sayHi的形参name

传递对象

同样也可以传递对象
一个Person对象

@Data
public class Person {
 private int id;
 private String name;
 private String password;
}
@RequestMapping("/per")
public Object method_2(Person p){
 System.out.println("对象中的 name:"+p.getName());
 System.out.println("对象中的 password:"+p.getPassword());
 return "/index.html";
}

然后使用
http://localhost:8080/hi?name=rich&&password=123
访问,就可以实现对象 p 的传递,springboot依然会根据key值给Person类的属性赋值,然后传递给method_2方法的形参p

后端参数重命名

当想要对前端传过来的参数重命名时,可以使用该注解:
@RequestParam
具体用法:

@RequestMapping("name")
public Object method_4(@RequestParam("time") String createtime) {
 System.out.println("时间:" + createtime);
 return "/index.html";
}

@RequestParam()中写前端的key,然后再在后面定义形参重新命名为createtime。
但如果前端没有传过来key为time的值时,页面就会报400的错误。但在实际应用中,有些时候的参数非必填项,为了避免报400的错误,可以将@RequestParam的设置改一下

@RequestParam(value = "time", required = false) 

将required改为false,非必要

上传文件

@RequestPart
使用方法:

    @RequestMapping("/param9")
    public String param9(String name, @RequestPart("myfile") MultipartFile file) throws IOException {
        file.transferTo(new File("D://s.png"));
    }

@RequestPart参数写前端传过来的文件的key,传给MultipartFile类的file对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值