These annotations are all based on Spring MVC.

@RequestMapping is mainly used to declare the request path, while @PathVariable and @RequestParam are both used to receive parameters sent from the frontend to the backend. In practice, they can feel similar because both are about accepting input values.

Here is the original example:

@RequestMapping("/")
    public String indexString(){
        return "index";
    }

    @RequestMapping("hello")
    public String helloSting(){
        return "hello";
    }

    @RequestMapping("hello/{xiaonan}/{id}")
    //@PathVariable("username") String username,@PathVariable("password") Integer password)

    //方法
    //前端传入路径hello/xiaonan/888
    //后端接收按照这样的
    //RequestMapping("hello/{参数一,名字为--->xiaonan}/{参数二,名字为---->id}")
    //@PathVariable("把参数一名字填写到这理 xiaonan") String xiaonan1这里名字随意,
    //@PathVariable("把参数二名字填写到这里 id") Integer id1这里名字随意
    //一般来说名字随意的这个地方和参数名字一样
    public String jiequString(@PathVariable("xiaonan") String xiaonan1, @PathVariable("id") Integer id1){

        System.out.println("username:"+xiaonan1+"id:"+id1);
        return "hello";
    }

What @RequestMapping does

This annotation defines which path should be handled by a method.

  • @RequestMapping("/") maps the root path / to indexString().
  • @RequestMapping("hello") maps the hello path to helloSting().
  • @RequestMapping("hello/{xiaonan}/{id}") maps a path that contains dynamic values.

So if the frontend sends a request like hello/xiaonan/888, the method with hello/{xiaonan}/{id} will receive those two values from the URL.

How @PathVariable works

@PathVariable is used to extract values directly from the path.

In the example above:

  • xiaonan is the name of the first path variable
  • id is the name of the second path variable

They are then received in the method like this:

  • @PathVariable("xiaonan") String xiaonan1
  • @PathVariable("id") Integer id1

The variable names inside the method, such as xiaonan1 and id1, can be changed freely. What matters is that the names inside @PathVariable(...) match the placeholders defined in @RequestMapping(...).

Usually, people keep the method parameter name the same as the path variable name, because it is easier to read.

About @RequestParam

@RequestParam is also used to receive parameters sent from the frontend. Compared with @PathVariable, the role feels similar in the sense that both are used for passing values into the backend.

A simple way to think about it is:

  • @RequestMapping: declares the path
  • @PathVariable: gets values from the path itself
  • @RequestParam: gets request parameters sent by the frontend

The main point here is that both @PathVariable and @RequestParam are used to accept frontend parameters, while @RequestMapping is responsible for mapping the URL path.