英文:
Spring @GetMapping returning empty array
问题
当在Postman上使用GET请求访问链接http://localhost:8081/api/data/mydatas/admin时,我得到一个空数组。我还尝试添加{ "username": "admin" },但仍然返回一个空数组。
这是我的Java服务中的代码:
@GetMapping("/mydatas/{username}")
public List<Data> findByUsername(String username) {
Query q = em.createQuery("select data from Data data where data.username = :username");
q.setParameter("username", username);
List<Data> mydatas = q.getResultList();
return mydatas;
}
然而,如果我像下面这样添加username = "admin";
,它会返回一个包含数据的数组。
username = "admin";
@GetMapping("/mydatas/{username}")
public List<Data> findByUsername(String username) {
username = "admin";
Query q = em.createQuery("select data from Data data where data.username = :username");
q.setParameter("username", username);
List<Data> mydatas = q.getResultList();
return mydatas;
}
我做错了什么?请注意,我是一个新手,仍在努力理解基础知识。
英文:
When use GET with postman on link http://localhost:8081/api/data/mydatas/admin
i get an empty array. I've also tried adding
{ "username": "admin" } but it still returns as an empty array.
this is the code in my java service:
@GetMapping("/mydatas/{username}")
public List<Data> findByUsername(String username) {
Query q = em.createQuery("select data from Data data where data.username = :username");
q.setParameter("username", username);
List<Data> mydatas = q.getResultList();
return mydatas;
}
However, if i add username = "admin"; as below. It will send back the array with full of data.
@GetMapping("/mydatas/{username}")
public List<Data> findByUsername(String username) {
username = "admin";
Query q = em.createQuery("select data from Data data where data.username = :username");
q.setParameter("username", username);
List<Data> mydatas = q.getResultList();
return mydatas;
}
What am i doing wrong? Ps i am a novice still struggling with the basics.
答案1
得分: 4
在你的参数前面添加@PathVariable,就像这样:
@PathVariable String username
通过这个注解,你告诉Spring从URL路径中获取username。
英文:
add @PathVariable before your parameter like so
@PathVariable String username
With this annotation you are telling Spring to grab username from URL path
答案2
得分: 2
public List findByUsername(@PathVariable("username") String username)
英文:
You need to use @PathVariable,
public List<Data> findByUsername(@PathVariable("username") String username)
答案3
得分: 0
@PathVariable
注解应该在findByUsername
之前的参数中以双引号""的形式传递,作为"String username"的参数。
英文:
The @PathVariable annotation should be passed in with the name of the field in speechmarks "" as the argument for findByUsername before "String username"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论