@RequestParam vs @PathVariable

前端 未结 7 926
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:22

What is the difference between @RequestParam and @PathVariable while handling special characters?

+ was accepted by @Re

7条回答
  •  -上瘾入骨i
    2020-11-22 06:48

    @RequestParam annotation used for accessing the query parameter values from the request. Look at the following request URL:

    http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
    

    In the above URL request, the values for param1 and param2 can be accessed as below:

    public String getDetails(
        @RequestParam(value="param1", required=true) String param1,
            @RequestParam(value="param2", required=false) String param2){
    ...
    }
    

    The following are the list of parameters supported by the @RequestParam annotation:

    • defaultValue – This is the default value as a fallback mechanism if request is not having the value or it is empty.
    • name – Name of the parameter to bind
    • required – Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail.
    • value – This is an alias for the name attribute

    @PathVariable

    @PathVariable identifies the pattern that is used in the URI for the incoming request. Let’s look at the below request URL:

    http://localhost:8080/springmvc/hello/101?param1=10¶m2=20

    The above URL request can be written in your Spring MVC as below:

    @RequestMapping("/hello/{id}")    public String getDetails(@PathVariable(value="id") String id,
        @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
    .......
    }
    

    The @PathVariable annotation has only one attribute value for binding the request URI template. It is allowed to use the multiple @PathVariable annotation in the single method. But, ensure that no more than one method has the same pattern.

    Also there is one more interesting annotation: @MatrixVariable

    http://localhost:8080/spring_3_2/matrixvars/stocks;BT.A=276.70,+10.40,+3.91;AZN=236.00,+103.00,+3.29;SBRY=375.50,+7.60,+2.07

    And the Controller method for it

     @RequestMapping(value = "/{stocks}", method = RequestMethod.GET)
      public String showPortfolioValues(@MatrixVariable Map> matrixVars, Model model) {
    
        logger.info("Storing {} Values which are: {}", new Object[] { matrixVars.size(), matrixVars });
    
        List> outlist = map2List(matrixVars);
        model.addAttribute("stocks", outlist);
    
        return "stocks";
      }
    

    But you must enable:

    
    

提交回复
热议问题