[英]How can I deal with @RequestParam in JSP file?
大家! 我有一个关于在@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;
}
我认为@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);
});
}
});
}
您可以在@RequestMapping
注解中设置路径;
@RequestMapping(method = RequestMethod.GET, path = "rest/projects/{head}")
或使用@GetMapping
批注:
@GetMapping(path = "rest/projects/{head}")
并使用@PathVariable("head")
代替@RequestParam(name = "head")
对于Javascript部分,您应该在url中指定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);
});
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.