Spring Boot下的Spring MVC和之前的Spring MVC使用完全一样
@Controller
即为Spring MVC的注解,处理http请求
@RestController
- Spring4后新增注解
- 是@Controller和@ResponseBody的组合注解
- 用于返回字符串或者json数据
例:实体类User
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
业务控制UserController类
import com.springboot.module.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping("/getUser")
public Object getUser(){
User user = new User();
user.setId(123);
user.setName("马克");
return user;
}
}
运行结果
注意:使用该注解后,该类中的所有方法都不能返回页面了,如果需要返回页面,则需使用@Controller注解
@GetMapping
RequestMapping和Get请求方法的组合,只支持Get请求
以下两个方法等价
import com.springboot.module.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping(value = "/getUser",method = RequestMethod.GET)
public Object getUser(){
User user = new User();
user.setId(123);
user.setName("马克");
return user;
}
@GetMapping("/getUser1")
public Object getUser1(){
User user = new User();
user.setId(1234);
user.setName("马克1");
return user;
}
}
@PostMapping
和上述注解一样,只不过是只支持Post请求。
@PutMapping
RequestMapping和Put请求方法的组合,使用的较少,可用于修改操作。
@DeleteMapping
RequestMapping和Delete请求方法的组合,使用的较少,可用于删除操作。