spring-boot Web开发基础1-注解部分

本文介绍了Spring Boot Web开发中的注解使用,包括@GetMapping、@PostMapping、@PutMapping等HTTP操作注解,以及@RequestParam参数传递,@PathParam从URL获取参数,和@RestController的使用。@RestController注解表明方法直接以JSON形式输出,同时提到了Content-Type的重要性及其设置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、@GetMapping @PostMapping @PutMapping等

二、@RequestParam  传递参数

            value-指定参数名字  defaultValue:默认值,可选 required:是否必选

   /**
     * @GetMapping:Spring4.3新特性,只支持get请求
     * @PostMapping,@PutMapping同理
     * @RequestParam:传递参数:value:指定参数名字 defaultValue:默认值,可选
     * required:是否必须
     */ 
@ResponseBody
    @GetMapping("/getmapping")
    public String get(@RequestParam(value = "username", defaultValue = "houzheng") String usrename,
                      @RequestParam(value = "password", required = true) String password) {
        return "get springboot" + usrename + "---" + password;

    }

 三、@PathParam 获取url中的参数

   /**
     * @PathParam:获取url中的参数 , 可直接注入servlet的api
     */
    @ResponseBody
    @PostMapping("/postmapping/{id}")
    public String post(@PathParam("id") String id, HttpServletRequest req) {
        req.getRemoteHost();
        return "post springboot";
    }

四、@RestController

        用于类上,表示方法可以直接用body输出,不用再写@ResponseBody

        虽然结果会输出为json,但是如果不设置Content-Type,默认是html。

        设置作用:

        Content-Type 实体头部用于指示资源的MIME类型 media type 。在响应中,Content-Type标头告诉客户端实际返回的内容的内容类型。浏览器会在某些情况下进行MIME查找,并不一定遵循此标题的值; 为了防止这种行为,可以将标题 X-Content-Type-Options 设置为 nosniff。在请求中 (如POST 或 PUT),客户端告诉服务器实际发送的数据类型。


     

      Spring留了一个设置响应消息Content-Type的接口。在注解@RequestMapping增加一个produces参数项即可。

       @RequestMapping(value = { "/api/v1/test" }, method = { RequestMethod.POST }, produces="application/json;charset=UTF-8")

        相当于在代码中设置

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

良之才-小良

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值