简体   繁体   中英

Spring @GetMapping returning empty array

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.

add @PathVariable before your parameter like so

@PathVariable String username

With this annotation you are telling Spring to grab username from URL path

You need to use @PathVariable,

public List<Data> findByUsername(@PathVariable("username") 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM