construct a dynamic url using path variables in spring controller

7.5k Views Asked by At

i would like to generate a dynamic url like http://example.com/path/to/page?name=ferret&color=purple

where i can send name and color two separate input fields from my form to controller as a single parameter. can someone please help me with the corresponding jsp and spring controller coding.

the following is my controller :

@RequestMapping(value = "/ws/jobs/{title}/{location}/{experience}")
     public ModelAndView openRequirementsRedirect(JobSearchRequest jobSearchRequest) throws Exception{
     ModelAndView model = new ModelAndView();
         model.addObject("title", jobSearchRequest.getTitle());
     model.addObject("location", jobSearchRequest.getLocation());
     model.addObject("experience", jobSearchRequest.getExperience());
     model.setViewName("openJobs/openjobs");
     return model;
}

i am having pojo :

public class JobSearchRequest {
    private String title;
    private String location;
    private String experience;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public String getExperience() {
        return experience;
    }
    public void setExperience(String experience) {
        this.experience = experience;
    }
}

and y jsp call is something like this :

window.location.href = example+"/abc?&title="+title+"&location="+location+"&experience="+experience;
2

There are 2 best solutions below

1
On

Here is the simple example:

@RequestMapping(value = "/project/{projectId}/{bookmark}", method = RequestMethod.GET)
public @ResponseBody boolean bookmarkProject(@PathVariable("projectId") UUID projectId,
                                             @PathVariable("bookmark") boolean bookmark) {
    return userService.bookmarkProject(projectId, bookmark);
}
0
On

Basically you are trying the read query param, so, you have to use @RequestParam annotation to the api method.

@RequestMapping(value = "/ws/jobs/{title}/{location}/{experience}")
public ModelAndView openRequirementsRedirect(   JobSearchRequest jobSearchRequest,
                                                @RequestParam(required = false, value = "name") String name,
                                                @RequestParam(required = false, value = "color") String color
 ) throws Exception{

     ModelAndView model = new ModelAndView();
     model.addObject("title", jobSearchRequest.getTitle());
     model.addObject("location", jobSearchRequest.getLocation());
     model.addObject("experience", jobSearchRequest.getExperience());
     model.setViewName("openJobs/openjobs");
     return model;
}

The above method will work if the resource url would be

http://example.com/title1/loc1/exp1?name=ferret&color=purple