大家好!我有一个关于在@RestController中使用@RequestParam的问题。我想知道如何从客户端获取@RequestParam。 服务器代码(@RestController):
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<ProjectBean>> getAllBeans(@RequestParam(name = "head") Integer headId) {
Integer head = securityService.getLoggedAccountId();
List<ProjectBean> projects = (List<ProjectBean>) projectService.getByHead(head);
return new ResponseEntity<List<ProjectBean>>(projects, HttpStatus.OK);
}
和JSP / JavaScript:
function loadProjects() {
$.ajax({
url : 'rest/projects',
method : 'GET',
headers : {
'Content-Type' : 'application/json',
},
success: function(data){
$.each(data, function(index, project) {
addProject(project);
});
}
});
}
此函数会加载所有项目,但不会加载精确的headId
实体:
@Entity
@Table(name = "projects")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "project_name", nullable = false, length = 255)
private String projectName;
@Column(name="head")
private Integer head; //need to get projects with this value
@Column(name = "description")
private String description;
@Column(name = "photo")
private String photo;
@Column(name = "status", nullable = false, length = 200)
private String status;
}
答案 0 :(得分:1)
在我看来,推荐@ NayoR的建议。但实际上你需要在js中使用查询字符串,例如:
function loadProjects() {
$.ajax({
url : 'rest/projects?head=' + headId,
method : 'GET',
headers : {
'Content-Type' : 'application/json',
},
success: function(data){
$.each(data, function(index, project) {
addProject(project);
});
}
});
}
答案 1 :(得分:0)
您可以在@RequestMapping
注释中设置路径;
@RequestMapping(method = RequestMethod.GET, path = "rest/projects/{head}")
或使用@GetMapping
注释:
@GetMapping(path = "rest/projects/{head}")
并使用@PathVariable("head")
代替@RequestParam(name = "head")
对于Javascript部分,您应在网址中指定head
:
function loadProjects(head) {
$.ajax({
url : 'rest/projects/' + head,
method : 'GET',
headers : {
'Content-Type' : 'application/json',
},
success: function(data){
$.each(data, function(index, project) {
addProject(project);
});
}
});
}