How to handle requests that includes forward slashes (/)?

前端 未结 7 1364
南旧
南旧 2020-11-30 05:40

I need to handle requests as following:

www.example.com/show/abcd/efg?name=alex&family=moore   (does not work)
www.example.com/show/abcdefg?name=alex&         


        
7条回答
  •  我在风中等你
    2020-11-30 06:05

    The default Spring MVC path mapper uses the / as a delimiter for path variables, no matter what.

    The proper way to handle this request would be to write a custom path mapper, that would change this logic for the particular handler method and delegate to default for other handler methods.

    However, if you know the max possible count of slashes in your value, you can in fact write a handler that accepts optional path variables, and than in the method itself, assemble the value from path variable parts, here is an example that would work for max one slash, you can easily extend it to three or four

    @RequestMapping(value = {"/{part1}", "/{part1}/{part2}"}, method = RequestMethod.GET)
    public String handleReqShow(
            @PathVariable Map pathVariables,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String family, Model model) {
        String yourValue = "";
        if (pathVariables.containsKey("part1")) {
            String part = pathVariables.get("part1");
            yourValue += " " + part;
        }
        if (pathVariables.containsKey("part2")) {
            String part = pathVariables.get("part2");
            yourValue += " /" + part;
        }
        // do your stuff
    
    }
    

    You can catch all the path variables inside the map, the map @PathVariable Map pathVariables, but the downside is that the static part of the mapping has to enumarate all the possible variations

提交回复
热议问题