I'm new to REST and Spring. I'm doing an exercise where I have to fetch a client via url and return (GET) it in JSON format and insert (POST) a client in JSON format.
To search will be in the template 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 uses only the memory of instantiated objects.
My classes:
Customer
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 + "]";
}
}
ClientController
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);
}
}
ClientService
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.