Spring @RequestMapping

RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

首先是作用的地方

//RequestMapping作用于方法上
//请求的url:http://127.0.0.1 / 项目名 / h1
@Controller
public class ControllerDemo {
    @RequestMapping("/h1")
    public String hello1(Model model){
        model.addAttribute("msg","HelloSpringMVC");
        return "to";
    }
}

作用在类上

//请求的url:http://127.0.0.1 / 项目名/hello / h1
@Controller
@RequestMapping("/hello")
public class ControllerDemo {
    @RequestMapping("/h1")
    public String hello1(Model model){
        model.addAttribute("msg","HelloSpringMVC");
        return "to";
    }
}

可以指定处理 HTTP 请求的方法

GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE

使用方法

@RequestMapping(value = "/h1",method = RequestMethod.GET)

不过存在几个方法的变体

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

重点是get方法,因为默认的get方式,提交的参数会显示在url路径上,非常不安全

@Controller
public class ControllerDemo {
    @RequestMapping("/h1")
    public String hello1(int a,int b,Model model){
        int res=a+b;
        model.addAttribute("msg",""+a+"+"+b+"="+res);
        return "to";
    }
}

所以通常会使用Restful风格的提交方式 @PathVariable用于显示地将url映射参数到方法参数

@Controller
public class ControllerDemo {
    @RequestMapping(value = "/h1/{a}/{b}",method = RequestMethod.GET)
    public String hello1(@PathVariable int a,@PathVariable int b,Model model){
        int res=a+b;
        model.addAttribute("msg",""+a+"+"+b+"="+res);
        return "to";
    }
}

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值