学习写代码呀

导航

spring注解@controller,@RestController,@RequestMapping理解

@RestController("/test")
public class TestController {
    
    public String test1(@RequestParam String name){
        return "hi,"+name;
    }
    
    @RequestMapping
    public String test2(@RequestParam String name){
        return "hi,it is 2,"+name;
    }
    
    @RequestMapping("/3")
    public String test3(@RequestParam String name){
        return "hi,it is 3,"+name;
    }

}

1、@RequestMapping:映射 Request 请求与处理器,可以定义在类上,也可以定义在方法上。如果定义在类上,访问的就是相对路径,相对于类而言。如果定义在方法上,相对于方法的映射而言。

@RequestMapping默认post和get方式都可以访问。

2、@GetMapping请求参数可以加@RequestParam,也可以不加。

3、@Controller表明这个类是控制器类,里面有映射方法。

控制器类里面的方法如果不加@RequestMapping映射的话,就不会被扫描成映射,不会有调用这个接口的url。

一个Controller类里面,同一个路径只能有一个请求,比如@RequestMapping不再加路径的时候,不允许有两个相同请求。会报错:ambiguous map.

 

4、@RequestMapping(value = “createPickOrder.do”, produces = “application/json;charset=utf-8”, method = RequestMethod.POST)

produces = “application/json;charset=utf-8”:表示返回数据格式

 

method = RequestMethod.POST表示请求格式

 

post请求,如果是接收json格式(要求传输参数是json(application/json;charset=utf-8),接收参数要是一个参数或者是一个对象并且参数前加上@RequestBody注解);如果是表单提交(application/x-www-form-urlencoded),接收参数没有要求即可以是对象也可以是多个参数的接收方式

 

get请求,参数不能是json(application/json;charset=utf-8)格式,只能是表单(application/x-www-form-urlencoded)格式

5、@PathVaribale 获取url中的数据

@RequestParam 获取请求参数的值

 

@RequestMapping(value="/hello/{id}",method= RequestMethod.GET)

public String sayHello(@PathVariable("id") Integer id){

return "id:"+id;

}

 

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

public String sayHello(@RequestParam("id") Integer id){

return "id:"+id;

}

 

 

 

posted on 2020-11-11 10:43  学习写代码呀  阅读(226)  评论(0编辑  收藏  举报