Search code examples
spring-mvcpath-variables

Can we pass a string( "emp id") as path variable to the controller in Spring?


I am writing an controller for one of spring based applications. I was extensively using path variable but I have few scenarios where I have stringswhich has spaces for example "bike racing" and I also have &


Solution

  • I think for doing that you need to define a regular expression on your request mapping, something like this:

    @RequestMapping("/home/{test:[a-zA-Z &+-]*}")
    public ModelAndView getTest(@PathVariable("test") String test) {
        ModelAndView model = new ModelAndView();
        model.setViewName("/test/teste");
        model.addObject("label_title", test);
    
        return model;
    }
    

    And then you will have your strings correctly: with space with &

    I hope I have helped you!