(二)、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
  设置请求的路由路径(value = “/”)、请求方法(method = RequestMethod.GET)。
  从上面代码可以看出@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;
    }
}

总结:
  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介绍

猜你喜欢

转载自blog.csdn.net/u010986518/article/details/82187793
今日推荐