Receiving object by parameter

Asked

Viewed 1,575 times

1

I’m using Spring MVC and use some mapping to receive an object for example and access that specific object in controller.

For example:

@GetMapping("/pessoa/{idPessoa}")
public ModelAndView editaPessoa(@PathVariable("idPessoa") Pessoa pessoa) {
.....
}

So, if I have a listing, I need to pass a link to the controller href by passing the id of the person I wanted to edit for example. However, I wanted to hide the person’s id via browser, so that the url would not expose the object ids

http://site.com.br/editar/pessoa/32

Is there any way to just call the mapping without passing the id by url and be able to retrieve that object inside the controller ?

1 answer

0


Yes, just use the @Requestbody and create a POJO class that contains a String id attribute. Note that you will not be able to pass the href of the link, so you will have to create a request forwarding the json via Javascript.

For example:

@GetMapping("/pessoa/")
public ModelAndView editaPessoa(@RequestBody PessoaInterface pessoa) {
.....
}

Personal Interface.java

public class PessoaInterface {
    String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

Note that in Personal.java interface you can add a List and pass numerous Ids in a single request.

Optimal solution

You are using the GET method to make an edit. One of the principles of REST is to respect the Https codes and use the correct verbs, that is, use GET only in a case where you need to access something. The ideal is for you to use PUT or PATCH for editing (I can’t say which one for sure because I don’t know your scenario).

Note that it is not only a matter of respecting the patterns, there is a long thread about forwarding body in a GET request (https://stackoverflow.com/questions/978061/http-get-with-request-body) and some Servers even refuse by default requests Gets with body. Speaking of REST, this is definitely not accepted.

And if you wanted to get an element without having to pass the ID?

Assuming that your problem is not a person edit but getting a person passing the ID, in these cases we continue to pass it on via path param but is used Guids instead of Ids.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.