使用spring控制器中的路径变量构造动态URL

时间:2017-11-30 06:38:25

标签: java spring querystringparameter spring-config

我想生成一个动态网址 http://example.com/path/to/page?name=ferret&color=purple

我可以将名称和颜色两个单独的输入字段从我的表单发送到控制器作为单个参数。 有人可以请相应的jsp和弹簧控制器编码帮助我。

以下是我的控制器:

@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;
}

我有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;
    }
}

和y jsp调用是这样的:

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

2 个答案:

答案 0 :(得分:0)

以下是一个简单的例子:

@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);
}

答案 1 :(得分:0)

基本上你正在尝试读取查询参数,因此,你必须对api方法使用@RequestParam注释。

@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;
}

如果资源网址为

,则上述方法将有效

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