简体   繁体   中英

How can I GET object only by 1 field under @RequestBody annotation?

I need an advice. I am not too good at Spring framework and I just want to ask you a simple question.

I have a next POJO object on Server side:

@Entity
@Table(name = "AutoRate")
public class AutoService {

    public AutoService() {
    }

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    private long id;

    @Column(name = "serviceName", nullable = false)
    private String serviceName;

    @Column(name = "imageURL", nullable = false)
    private String imageURL;

    @Column(name = "mapCoordinate", nullable = false)
    private String mapCoordinate;

    @Column(name = "websiteURL", nullable = false)
    private String websiteURL;

    @Column(name = "phoneNumber", nullable = false)
    private String phoneNumber;

    @JsonManagedReference
    @OneToMany(mappedBy = "autoService", fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
    private List<Service> services = new ArrayList<Service>();}

It contains all getters and setters; I just want to save space.

Next: I want to get 1 object from database for client, and I want to do that using only serviceName variable in database.

I have a next controller method:

@RequestMapping(value = "/getAutoService", method = RequestMethod.GET)
    @ResponseBody
    public AutoService getAutoService(@RequestBody String serviceName){
        AutoService autoService = dataBaseService.getByName(serviceName);
        return autoService;
    }

After call from client I get next error:

117899 [http-apr-8080-exec-1] WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.webserverconfig.user.entity.AutoService com.webserverconfig.user.controller.ServiceController.getAutoService(com.webserverconfig.user.entity.AutoService)

I think that I am using @RequestBody annotation wrong.

Can anybody give an advice ?

You are using GET method which passes its data in the query string and not within the HTTP body, POST method does pass the HTTP message in its body.

Thus, it's not right to use @RequestBody annotation, try to use @PathVariable instead.

@RequestBody annotation indicates that you're trying to bind data in HTTP body message to the method parameter.

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