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

前端 未结 7 1245
南旧
南旧 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:24

    You have to create two methods then one having the @RequestMapping(value = { "/{string:.+}" }) annotation and the other having @RequestMapping(value = { "/{string:.+}", "/{string:.+}/{mystring:.+}" }) and then act accordingly in each, because you can't have optional path variables.

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    @RequestMapping("/show")
    public class HelloController {
    
        @RequestMapping(value = { "/{string:.+}" })
        public String handleReqShow(@PathVariable String string,
                @RequestParam(required = false) String name,
                @RequestParam(required = false) String family, Model model) {
            System.out.println(string);
            model.addAttribute("message", "I am called!");
            return "hello";
        }
    
        @RequestMapping(value = { "/{string:.+}", "/{string:.+}/{mystring:.+}" })
        public String whatever(@PathVariable String string,
                @PathVariable String mystring,
                @RequestParam(required = false) String name,
                @RequestParam(required = false) String family, Model model) {
            System.out.println(string);
            System.out.println(mystring);
            model.addAttribute("message", "I am called!");
            return "hello";
        }
    }
    
    0 讨论(0)
提交回复
热议问题