Spring Boot 从入门到放弃:Spring MVC 常用注解详解

wshunli
2018-01-28 / 0 评论 / 58 阅读 / 正在检测是否收录...

本文介绍 Spring MVC 常用注解,包括 @Controller、@RequestMapping、@PathVariable、@RequestParam、@RequestBody、@ResponseBody、@RestController 等等。

1、@Controller

Controller 控制器是通过服务接口定义的提供访问应用程序的一种行为,它解释用户的输入,将其转换成一个模型然后将试图呈献给用户。

其实 @Repository、@Controller、@Service 都组合了 @Component 元注解。

@Controller
public class PersonController {
}

2、@RequestMapping

@RequestMapping 注解用于映射 Web 请求(访问路径和参数)、处理类和方法的。

@RequestMapping 可以注解在类和方法上,注解在方法上的路径会继承注解在类上的路径;支持 Servlet 的 request 和 response 作为参数。

@Controller
@RequestMapping(value = "api/person")
public class PersonController {

    @RequestMapping(value = "{name}", method = RequestMethod.GET)
    @ResponseBody
    public String index() {
    }
}

@PathVariable 用来接收路径参数,比如 /api/person/{name} 可接受 name 作为参数。

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    @ResponseBody
    public String index(
            @PathVariable("name") String name) {
        System.out.printf("Person name :" + name);
        return name;

    }

发送 GET 请求示例 :http://127.0.0.1:8080/api/person/wshunli

@RequestParam 用来接收参数,比如 /api/person/?name=wshunli 可接受 name 的值 wshunli 作为参数的值。

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public String create(
            @RequestParam(value = "name", required = false) String name) {
        System.out.printf("Person name :" + name);
        return name;

    }

发送 POST 请求示例 :http://127.0.0.1:8080/api/person?name=wshunli

3、@RequestBody

@RequestBody 允许 request 的参数在 request 体内,而不是直接在地址后面。

未完待续。。

参考资料:
1、springmvc常用注解标签详解 - 木叔 - 博客园
https://www.cnblogs.com/leskang/p/5445698.html
2、详解Spring MVC 常用的那些注解 - CSDN博客
http://blog.csdn.net/u010783583/article/details/52176382

0

评论 (0)

取消