import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiController {
@RequestMapping("/hello")
public String hello() {
return "Hello, World!";
}
@RequestMapping("/user/{id}")
public User getUserById(@PathVariable int id) {
// 根据id查询数据库中的用户信息并返回
User user = userService.getUserById(id);
return user;
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public void addUser(@RequestBody User user) {
// 向数据库中添加用户信息
userService.addUser(user);
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public void updateUserById(@PathVariable int id, @RequestBody User user) {
// 根据id更新数据库中的用户信息
userService.updateUserById(id, user);
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public void deleteUserById(@PathVariable int id) {
// 根据id删除数据库中的用户信息
userService.deleteUserById(id);
}
}SpringMVC中使用注解配置可以使代码更加简洁易读,提高开发效率。在上述代码中,我们使用了@RestController注解将类声明为一个控制器,并使用@RequestMapping注解来映射请求路径。通过不同的HTTP请求方法和路径,我们可以定义不同的处理方法,实现对应业务逻辑的处理。
在示例中,我们定义了一个/api路径的基础路径,接下来每个处理方法的路径都是相对于基础路径的。例如,@RequestMapping("/hello")表示处理路径为/api/hello的请求,对应的处理方法返回"Hello, World!"。
在处理方法中,我们还可以使用@PathVariable注解来接收路径参数,使用@RequestBody注解来接收请求体中的数据。通过将处理方法的参数声明为对应的类对象,SpringMVC会自动将请求数据转换成对象,并传入方法中。
通过使用SpringMVC的注解配置,我们可以轻松地实现对不同请求的处理,并将处理结果返回给客户端,极大地简化了开发过程。