SpringBoot Controller

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot Controller

UserLw   2022-09-29 我要评论

概述

Controller是Spring接受并处理网页请求的组件,是整个应用的入口,因此学会Controller的常用注解对理解一个应用是重中之重。SpringBoot的Controller中经常会用到注解@Controller、@RestController、@RequestMapping、@RequestBody等,本短文主要对这些常用的Controller注解进行简单介绍。

常用注解简介

1.@Controller

@Controller是最基本的控制层注解,继承了Spring的@Component注解,会把对应的类声明为Spring对应的Bean,并且可以被Web组件管理。使用@Controller注解返回的是view,而不是Json数据,例:

@Controller
@RequestMapping("/test")
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello World!");
        return "index";
    }
}

在该段代码中,用户若访问/test/hello,则会返回index页面。

2.@RestController

和@Controller一样,@RestController也是用于一个类的标注,不同的是@RestController标注的类的方法返回json。

例如:

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/index")
    public String testMethod(Model model) {
        return "index/index";
    }
}

访问的返回结果如图所示 :

3.@RequestMapping

@RequestMapping是用于标识类或者方法的访问地址的,提供路由信息,完成从url到controller的映射。例如上面代码块中的类上的@RequestMapping("/test")表示访问端口的/test就能访问到改控制器,而访问/test/index则能访问到该类的相应方法。@GetMapping/@PostMapping其实就是@RequestMapping和Get/Post的集合。@GetMapping(value = “hello”) 等价于@RequestMapping(value = “hello”, method = RequestMethod.GET)

4.@RequestBody

该注解的作用是将方法的返回值,以特定的格式写入到response的body区域,进而将数据返回给客户端。当方法上面没有写ResponseBody,底层会将方法的返回值封装为ModelAndView对象。如果返回值是字符串,那么直接将字符串写到客户端;如果是一个对象,会将对象转化为json串,然后写到客户端。@Controller+@ResponseBody等于@RestController。

5.@RequestParam

@RequestParam用于获取请求参数,从而使用请求所带的参数,

例如:

@RequestMapping("/user")
public String testRequestParam(@RequestParam("name") String name){
    System.out.println("请求姓名参数="+name);
    return "success";
}

该段代码会解析请求参数name,用于方法中的使用。

6.@PathVariable

@PathVariable与@RequestMapping配合使用,通过解析url中的占位符进行参数获取。

例如:

@RequestMapping("/user/{id}")
public String testPathVariable(@PathVariable("id") String id){
    System.out.println("路径上的占位符的值="+id);
    return "success";
}

上面的代码块就能从url中解析出id字段,用于方法中的使用。

总结

本文只是对常用的一些@Controller层的注解进行简介,对这些注解组合使用,才能够达到想要完成的目的任务。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们