@RequestMapping注解能够处理的HTTP请求方法有: GET, HEAD, POST, PUT, PATCH, DELETE,OPTIONS, TRACE 。
package org.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/1")
public String test1(){
return "redirect:/home.html";
}
}
能够改变URL;
@GetMapping("/owners/{ownerId}/pets/{petId}")
public String findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
return "主人id:"+ownerId+", 宠物id:"+petId;
}
说明:
当请求数据要绑定到某个简单对象时,可以使用@RequestParam。
需要注意@RequestParam注解参数默认为 required=true ,如果不传该参数就会报错,需要指定为: @RequestParam(required = false)
例如:通过 post 请求,请求数据的键分别为 username 和 password ,指定为queryString,或 Content-Type为表单数据类型, form-data 都可以:
加上这个注解,就可以获取不管是是queryString中的,还是请求头中,键为username的值(value);password同样的道理
@PostMapping("/param1")
public Object param1(@RequestParam String username,@RequestParam String password){
Map<String, String> map = new HashMap<>();
map.put("用户名", username);
map.put("密码", password);
return map;
}
使用 java 对象和使用@RequestParam注解非常类似,只是有点细节不同:
@PostMapping("/pojo1")
public Object pojo1(String username, Integer count){
Map<String, String> map = new HashMap<>();
map.put("用户名", username);
map.put("count", String.valueOf(count));
return map;
}
@RequestParam和POJO对象常用的是POJO对象
@PostMapping("/part")
public Object part(User user, @RequestPart MultipartFile file) throws
IOException {
Map<String, String> map = new HashMap<>();
map.put("用户名", user.getUsername());
map.put("密码", user.getPassword());
map.put("文件名", file.getName()+", "+file.getOriginalFilename());
map.put("文件类型", file.getContentType());
map.put("文件大小", file.getSize()/1024+"KB");
map.put("文件内容(二进制转字符串)", new String(file.getBytes()));
return map;
}
当然,上面的@RequestParam和POJO对象也可以获取文件和@RequestPart用法一样。因此这个注解就不常用,用的都是POJO对象