Controller的使用

来源:互联网 发布:魅色软件 编辑:程序博客网 时间:2024/05/22 17:21

  • Controller
  • RestController
    • 访问不同路径进到同一个方法
    • 整个类配置路径
    • GET POST
      • 写法
      • postman工具
    • 请求参数
      • 获取url中的参数
      • 获取url中的参数并设置默认值

这里写图片描述

@Controller

需要配合模板使用!

//pom.xml文件中:<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency></dependencies>

建立模板文件:
这里写图片描述

//controller中:@Controller  //使用该标签public class HelloController {    @Autowired    private GirlProperties girlProperties;    @RequestMapping(value="/hello",method = RequestMethod.GET)    public String say(){        return  "index"; //返回页面;    }}

@RestController

@RestController

等同于

@Controller@ResponseBody

访问不同路径,进到同一个方法

//RequestMapping中配置路径集合;@RestControllerpublic class HelloController {    @Autowired    private GirlProperties girlProperties;    @RequestMapping(value={"/hello","hi"},method = RequestMethod.GET)    public String say(){        return  girlProperties.getCupSize();    }}

整个类配置路径

@RestController@RequestMapping("/hello") //配置整个类路径public class HelloController {    @Autowired    private GirlProperties girlProperties;    @RequestMapping(value={"say"},method = RequestMethod.GET)    public String say(){        return  girlProperties.getCupSize();    }}

GET POST

写法

  //@RequestMapping(value="say",method = RequestMethod.GET) //常用写法    @GetMapping(value="say") //简化写法    public String say(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myid){        return  "id = " + myid;    }

postman工具

请求参数

获取url中的参数

//http://localhost:8080/girl/hello/say/100 @RequestMapping(value="say/{id}",method = RequestMethod.GET)    public String say(@PathVariable("id") Integer myid){        return  "id = " + myid;    }
//http://localhost:8080/girl/hello/100/say @RequestMapping(value="{id}/say",method = RequestMethod.GET)    public String say(@PathVariable("id") Integer myid){        return  "id = " + myid;    }
http://localhost:8080/girl/hello/say?id=100  @RequestMapping(value="say",method = RequestMethod.GET)    public String say(@RequestParam("id") Integer myid){        return  "id = " + myid;    }注意:http://localhost:8080/girl/hello/say?id=此时id=nullhttp://localhost:8080/girl/hello/say此时页面报错

获取url中的参数,并设置默认值

//url中没有参数时,显示默认参数,不报错;@RequestMapping(value="say",method = RequestMethod.GET)    public String say(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myid){        return  "id = " + myid;    }
原创粉丝点击