Spring MVC之Controller

一、请求映射信息配置

Spring MCV使用org.springframework.web.bind.annotation包中的以下几个Annotation配置请求映射信息:

  1. 通用请求——@RequestMapping
  • 对应接口:org.springframework.web.bind.annotation.RequestMapping
  • 应用位置:类和方法
  1. Get请求——@GetMapping
  • 对应接口:org.springframework.web.bind.annotation.GetMapping
  • 应用位置:方法
  1. Post请求——@PostMapping
  • 对应接口:org.springframework.web.bind.annotation.PostMapping
  • 应用位置:方法
  1. Delete请求——@DeleteMapping
  • 对应接口:org.springframework.web.bind.annotation.DeleteMapping
  • 应用位置:方法
  1. Patch请求——@PatchMapping
  • 对应接口:org.springframework.web.bind.annotation.PatchMapping
  • 应用位置:方法
  1. Put请求——@PutMapping
  • 对应接口:org.springframework.web.bind.annotation.PutMapping
  • 应用位置:方法

二、参数接收

第一类:有注解

  1. @PathVariable
  • 对应接口:org.springframework.web.bind.annotation.PathVariable
  • 应用场景
    从URL路径中获取参数,例如:
    http://example.com/demo/11253
@RepuestMapping(value="/demo/{id}")
public void demo(@PathVariable(name = "id") String id) {
    String address = orderMapper.getAddressById(id);
    ...
}
  1. @RequestParam
  • 对应接口:org.springframework.web.bind.annotation.RequestParam
  • 应用场景
    从Get请求中获取参数,并且方法的参数名可以与请求中的参数名不一样,例如:
    http://example.com/demo?data=11253
@GetMapping(value="/demo")
public void demo(@RequestParam(name = "data") String id) {
    String address = orderMapper.getAddressById(id);
    ...
}
  1. @RequestBody
  • 对应接口:org.springframework.web.bind.annotation.RequestBody
  • 应用场景
    从Post请求中获取参数,例如:

http://example.com/demo

{“name”:“Alice”, “tel”:13212348765, “sex”:“Female”}

@RepuestMapping(value="/add")
public void add(@RequestBody User user) {
    long id = userMapper.insert(user)
    ...
}
  1. @ModelAttribute注解
  • 对应接口:org.springframework.web.bind.annotation.ModelAttribute
  • 应用场景

http://example.com/demo

{“name”:“Alice”, “tel”:13212348765, “sex”:“Female”}

@PostMapping(value="/add")
@ResponseBody
public void add(@ModelAttribute User user) {
    long id = userMapper.insert(user)
    ...
}

第二类:无注解

当方法参数无注解时,不可直接从URL路径中获取前端传入的参数。同时,方法参数名(或参数字段名)必须与前端传入的参数名完全一致。

  • 应用示例:GET请求

http://example.com/demo?name=Alice&sex=Female

public void demo(String name, String sex) {
    String address = orderMapper.selectByCondition(name, sex);
    ...
}
  • 应用示例:POST请求

http://example.com/demo

{“name”:“Alice”, “tel”:13212348765, “sex”:“Female”}

@RepuestMapping(value="/add")
public void add(User user) {
    long id = userMapper.insert(user)
    ...
}

第三类:HttpServletRequest接收请求参数

Controller还可以使用HttpServletRequest来接收参数,接收的参数均为String类型。

  • 应用示例:
@RequestMapping(value="demo")
public String request(HttpServletRequest request, HttpServletResponse response) {
    String name = request.getParameter("name");
    String tele = request.getParameter("tel");
    return name + ": " + tele;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值