Object search/registration via REST url and registration with SPRING

Asked

Viewed 1,826 times

3

I’m new to REST and Spring. I am doing an exercise where I have to search a client via url and return (GET) it in JSON format and insert(POST) a client in JSON format.

To search for sera in the model below, using GET:

http://localhost:8080/clientes/?nome=paulo

and return:

{
     "nome": "paulo",
     "cpf": 1231243434,
     "idade": 34,
     "sexo": M,
}

to insert into the template using POST:

{
     "nome": "paulo",
     "cpf": 1231243434,
     "idade": 34,
     "sexo": M,
}

This using only the memory of instantiated objects.

My classes:

Client

package model;
public class Cliente {

private String nome;
private String cpf;
private Integer idade;
private String sexo;

public Cliente(String nome, String cpf, Integer idade, String sexo) {
    this.nome = nome;
    this.cpf = cpf;
    this.idade = idade;
    this.sexo = sexo;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getCpf() {
    return cpf;
}

public void setCpf(String cpf) {
    this.cpf = cpf;
}

public Integer getIdade() {
    return idade;
}

public void setIdade(Integer idade) {
    this.idade = idade;
}

public String getSexo() {
    return sexo;
}

public void setSexo(String sexo) {
    this.sexo = sexo;
}

@Override
public String toString() {
    return "Cliente [nome=" + nome + ", cpf=" + cpf + ", idade=" +   idade + ", sexo=" + sexo + "]";
}
}

Clientecontroller

package controller;

import java.util.Hashtable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import model.Cliente;
import service.ClienteService;

@RestController
@RequestMapping("/clientes")
public class ClienteController {


@Autowired
ClienteService cli;

@RequestMapping("/all")
public Hashtable<String, Cliente> getAll(){
    return cli.getAll();
}

//não esta buscando desta forma
@RequestMapping("{nome}")
public Cliente getCliente(@PathVariable("nome") String nome){   
    return cli.getCliente(nome);
}
}

Clienteservice

package service;
import java.util.Hashtable;
import org.springframework.stereotype.Service;
import model.Cliente;

@Service
public class ClienteService {
Hashtable<String, Cliente> clientes = new Hashtable<String, Cliente>      ();

public ClienteService(){

    Cliente c1 = new Cliente("paulo","123.123.123-22",28,"M");
    Cliente c2 = new Cliente("diego","123.123.123-22",24,"M");
    Cliente c3 = new Cliente("Debora","123.123.123-22",21,"F");

    clientes.put("1", c1);
    clientes.put("2", c2);
    clientes.put("3", c3);

}

public Cliente getCliente(String nome){
    if(clientes.containsKey(nome)){
        return clientes.get(nome);
    }else{
        return null;
    }

}
public Hashtable<String, Cliente> getAll(){
    return clientes;
}

}

So far I’ve been able to show all clients instantiated in JSON format, I’ve done some research and I’m not able to solve this.

3 answers

2

Are you trying to make an appointment by query param (clientes?nome=paulo) but implemented a search for path param. (clientes/paulo)

Try changing your search to:

@RequestMapping(method = RequestMethod.GET)
public Cliente getCliente(@RequestParam("nome") String nome){   
    return cli.getCliente(nome);
}

And, taking advantage, correct your other query by removing the all at the end. In Rest good practices, when you call a resource without mentioning anything, you will be asking for all available resources. For this, change this way:

@RequestMapping(method = RequestMethod.GET)
public Hashtable<String, Cliente> getAll(){
    return cli.getAll();
}

And just do:

http://localhost:8080/clientes/

To return all customers

1

0

Hello, young man!

You are using "@Pathvariable" instead of "@Requestparam". If you’re going to use it like that, the code should look like this:

@RequestMapping(value = "/{nome}", method = RequestMethod.GET)
public Cliente getCliente(@PathVariable("nome") String nome){   
    return cli.getCliente(nome);
}

Then you will have to give the GET through the URI:

http://localhost:8080/clientes/paulo

There are other ways to do this. If your intention is just to search by name only, you can attack like this:

@RequestMapping(method = RequestMethod.GET)
public Cliente getCliente(@RequestParam("nome") String nome){   
    return cli.getCliente(nome);
}

Or you can still strike like this:

@RequestMapping(method = RequestMethod.GET)
public Cliente getCliente(Cliente cliente){   
    return cli.getCliente(cliente.getNome());
}

For these two examples, Uri is the one you wrote:

http://localhost:8080/clientes?nome=paulo

In the second case, spring itself already takes care of transforming what you send to the customer. Since you will want to transition Client, you need to implement Serializable.

public class Cliente implements Serializable{
    private static final long serialVersionUID = 1L;

Any questions, just ask

  • Opa long thanks for the help Jean!

  • I implemented a method to search by name and Cpf so that when I run the program spring returns me error. @Requestmapping(method = Requestmethod.GET) public Client getCliente(@Requestparam("name") String name)' Return cli.getClient(name); } @Requestmapping(method = Requestmethod.GET) public client getCpf(@Requestparam("Cpf") String Cpf)' Return cli.getCliente(Cpf); }

  • It informs: org.springframework.Beans.factory.Beancreationexception: Error Creating bean with name 'requestMappingHandlerMapping' defined in class path Resource [org/springframework/boot/autoconfigure/web/Webmvcautoconfiguration$Enablewebmvcconfiguration.class]: Invocation of init method failed; nested Exception is java.lang.Illegalstateexception: Ambiguous Mapping. Cannot map 'clienteController' method public model.Client controller.ClienteController.getCpf(java.lang.String) to {[/clients],methods=[GET]}: There is already 'clienteController' bean method

  • @Diegosantos, man, as both methods have similar signatures, when it comes to routing, he’s getting lost and doesn’t know which to put to Ql. Both are accessed through the same Uri, and have a parameter that receives a string. I confess that I never had a case like this to solve. I imagine that you can create a bean for guy one and good. I would attack differently, creating a specific route for each one. I think it is even more polite to consume.

  • It would look something like: @Restcontroller @Requestmapping("/clients") public class Clientecontroller { @Requestmapping(value = "/search/Cpf/{value}", method = Requestmethod.GET) public Responseentity<? > getCpf(@Pathvariable("value") String Cpf){ Return new Responseentity<>(Cpf, Httpstatus.OK); } @Requestmapping(value = "/search/name/{value}", method = Requestmethod.GET) public Responseentity<? > getCliente(@Pathvariable("value") String person){ Return new Responseentity<>(person, Httpstatus.OK); } }

Browser other questions tagged

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