(二)、Spring Boot的相关注解@RestController和@Controller、@RequestMapping、@RequestParam和@RequestBody等

上篇博客我们创建了一个SpringBoot,接下来就是操作SpringBoot。他会用到几个关键注解@RestController、@RequestMapping、@RequestParam。有些感觉比较简单就写的很简单,欢迎讨论。

1.@RestController
  使用此注解的方法表示一个控制器,返回json。原来返回一个json需要@Controller和@RequestBody配合使用。使用@Controller会返回一个html 和jsp页面。
  源码如下,看出他被@Controller、@ResponseBody注解:

/**
 * A convenience annotation that is itself annotated with
 * {@link Controller @Controller} and {@link ResponseBody @ResponseBody}.
 * <p>
 * Types that carry this annotation are treated as controllers where
 * {@link RequestMapping @RequestMapping} methods assume
 * {@link ResponseBody @ResponseBody} semantics by default.
 *
 * <p><b>NOTE:</b> {@code @RestController} is processed if an appropriate
 * {@code HandlerMapping}-{@code HandlerAdapter} pair is configured such as the
 * {@code RequestMappingHandlerMapping}-{@code RequestMappingHandlerAdapter}
 * pair which are the default in the MVC Java config and the MVC namespace.
 *
 * @author Rossen Stoyanchev
 * @author Sam Brannen
 * @since 4.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";
}

我们使用其如下:

@RestController
@RequestMapping("/cs")
public class ApiHelloController {
    @RequestMapping(value = "/hello")
    public String sayHello() {
        System.out.println("hello");
        return "hello";
    }
    
    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    public String index(@RequestParam(value = "nameI", required = false) String name,HttpServletRequest request) {
        
        String test=request.getHeader("test");
        
         
        System.out.println("hello:"+name);
        System.out.println("header:"+test);
        return "hello "+name+",this is first messge";
    }
    
    
    @RequestMapping("/auth/is_authorized")
    public boolean isAuthorized(@RequestParam(name="uri") String uri, @RequestParam(name="userId")String userId) {
        if(userId.equals("0"))
            return false;
        return true;
    }
}

进入http://localhost:8080/cs/hello等路径查看。
  
2.@Controller
  相信学过MVC的兄弟们看到的这个注解很兴奋啊,是不是很熟悉。不管你熟不熟悉,本博主不熟悉,真心的。但是百度过很多网上的知识,还是略略明白一二。
  在MVC中,C代表的正是Controller。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器。而他返回的不是Json数据,而是页面类数据。可以参考博客SpringBoot 中常用注解@Controller/@RestController/@RequestMapping介绍
  i.在pom.xml文件中添加如下模块依赖:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

ii.在resources目录下新建templates目录,并且在templates目录下添加一个hello.html文件,具体工程目录结构如下:
  iii.原来控制器代码改为:
  我们可以看出只有sayHello()变了。他返回的hello会去templates下面找到对应的文件作为返回,他返回的是一个页面。

@Controller
@RequestMapping("/cs")
public class ApiController {
    @RequestMapping(value = "/hello")
    public String sayHello() {
        System.out.println("hello");
        return "hello";
    }
    
    @ResponseBody
    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    public String index(@RequestParam(value = "nameI", required = false) String name,HttpServletRequest request) {
        
        String test=request.getHeader("test");
        
         
        System.out.println("hello:"+name);
        System.out.println("header:"+test);
        return "hello "+name+",this is first messge";
    }
    
    @ResponseBody
    @RequestMapping("/auth/is_authorized")
    public boolean isAuthorized(@RequestParam(name="uri") String uri, @RequestParam(name="userId")String userId) {
        if(userId.equals("0"))
            return false;
        return true;
    }
}

3.@RequestMapping和@GetMapping
  @RequestMapping可以作用在类上,也可以作用在方法上。
  @GetMapping其实就是@RequestMapping和Get的集合:
  @GetMapping(value = “hello”) 等价于@RequestMapping(value = “hello”, method = RequestMethod.GET)

4.@RequestParam、@PathVaribale与@RequestBody的区别
  想必每次提到@RequestParam的时候,很多人就会想到他与@RequestBody的区别。
  他们 的区别本人的理解为:当你只需要传递个别参数的时候使用@RequestParam,而你传递对象的时候使用@RequestBody
  为什么呢?我理解的是一个对象如果只包含一个成员变量,这时使用@RequestParam和使用@RequestBody差不多,不过一个传的是对象,一个传的是多个参数。
  后来遇到高人指点啊:@RequestParam注解接受的是来自于requestHeader中,即请求头,也就是在url中,格式为xxx?username=123&password=456,而RequestBody注解接收的参数则是来自于requestBody中,即请求体中。(与后来发现的博客一模一样:
spring boot的@RequestParam和@RequestBody的区别
。但是这篇博客里边有一点不对,其实能用get方法的基本都能用Post方法,反之不然。
  @RequestBody例子如下:

@RestController
@RequestMapping("/cs")
public class ApiController {  
    @RequestMapping(value = "chen", method = RequestMethod.POST)
    public StuResponse getStudent(@RequestBody Student student) {
        StuResponse stuResponse = new StuResponse();
        stuResponse.setName(student.getName());
        stuResponse.setHoby(student.getHoby());
        return stuResponse;
    }
}

使用的Model类这里就不说了。我们可以看出这样作为接口使用很方便。用Postman测试如下:
  这里写图片描述
  可以看出返回一个正确的对象给调用他的前端程序员。
  如果你想把这个方法的POST(method = RequestMethod.POST)换成GET(method = RequestMethod.GET)则运行错误如下:
  这里写图片描述
  
  @RequestParam例子如下:

@RestController
@RequestMapping("/cs")
public class ApiController {
    @RequestMapping(value = "shuai", method = RequestMethod.GET)
    public StuResponse getStudents(@RequestParam(value = "name") String name, @RequestParam(value = "hoby") String hoby) {
        StuResponse stuResponse = new StuResponse();
        stuResponse.setName(name);
        stuResponse.setHoby(hoby);
        return stuResponse;
    }
}

使用postman测试正确,如下:
这里写图片描述
  也可以使用post,但是传递信息时还是要写在请求头中。如下:
  这里写图片描述

@PathVaribale:获取url中的数据
  例子如下:

@RestController
public class HelloController {

    @RequestMapping(value="/hello/{id}",method= RequestMethod.GET)
    public String sayHello(@PathVariable("id") Integer id){
        return "id:"+id;
    }
}

Post跟Get的区别:
1.一般查询使用Get,增、删、改使用Post
2.字段少的时候使用Get,字段多的时候使用Post
3.GET跟POST的使用原理是一样的,有人说GET没有POST安全是因为数据显示在url后面,可见
4.GET比POST要快,GET会发一个TCP包,而POST会发两个。

添加信息,用@PostMapping,
如果是更新信息,用@PutMapping

总结:
  1.如果直接要在Controller层返回一个页面,用注解@Controller;如果让其作为一个接口,用@RestController。
  2.@RequestBody一般接受请求体中的数据,@Requestparam接受请求头中的数据。RequestBody只能用POST方法,而Requestparam查询用GET方法,上传数据或者需要改变数据库中的值还是用POST。
  
参考博客:
1、SpringBoot 中常用注解@Controller/@RestController/@RequestMapping介绍
2、Controller
3、spring boot的@RequestParam和@RequestBody的区别
4、SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@RestController是一个Spring框架的注解,用于标记一个类为RESTful风格的控制器。它的作用相当于@Controller和@ResponseBody的结合体。 使用方法如下: 1. 首先,在你的Spring Boot应用程序中,确保你已经添加了相关的依赖,比如spring-boot-starter-web。 2. 在需要使用@RestController注解的类上添加@RestController注解。 3. 在该类中,你可以定义多个处理HTTP请求的方法,这些方法可以使用@RequestMapping注解来指定请求的URL和HTTP方法。 例如,以下是一个使用@RestController的简单示例: ```java @RestController public class UserController { @GetMapping("/users") public List<User> getUsers() { // 处理获取所有用户的逻辑 // 返回用户列表 } @GetMapping("/users/{id}") public User getUserById(@PathVariable int id) { // 处理根据用户ID获取用户的逻辑 // 返回用户对象 } @PostMapping("/users") public User createUser(@RequestBody User user) { // 处理创建用户的逻辑 // 返回创建的用户对象 } // 其他处理HTTP请求的方法... } ``` 在上面的例子中,我们使用@GetMapping、@PostMapping、@PathVariable和@RequestBody注解来定义了处理HTTP请求的方法。这些方法会根据请求URL和HTTP方法来匹配对应的处理逻辑,并返回相应的结果。 请注意,使用@RestController注解的类中的方法默认会将返回值转换为JSON格式,通过HTTP响应返回给客户端。如果你想返回其他类型的数据(如HTML页面),可以使用其他注解(如@Controller)来替代@RestController。 希望能帮到你!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值