JSON passando parametros para query de consulta

10 respostas Resolvido
W

Boa tarde, não tenho muito conhecimento(quase nenhum) de JSON, consegui montar e consumir um JSON com Jersey com uma consulta fixa ao banco de dados, porém preciso enviar parâmetros para esta consulta(data por exemplo) e retornar somente os dados daquela consulta. Alguém pode me ajudar?
Grato.

10 Respostas

G

Nos mostre o que você já tem…

Método @Post e sua classe de manipulação do banco.

:wink:

W

Opa, boa tarde, tenho o método @Get, onde aponto o @Path

@Path ("/tag")
public class TagsResource {
    
    @GET
   // @Path("/listarDados")
    @Produces("application/xml")
    public ArrayList<Tags> listarDados(){
        return new TagController().listarTodos();
    }
    
}

e a classe de acesso ao banco

public class TagDAO extends ConnectionFactory{
    
    private static TagDAO instance;
    
    public static TagDAO getInstance(){
        if(instance == null){
            instance = new TagDAO();
        }
        return instance;
    }
    
    public ArrayList<Tags> listarTags(){
        Connection conexao = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        
        ArrayList<Tags> tags = new ArrayList<>();
        
        conexao = criarConexao();
        
        try {
            pstm = conexao.prepareStatement("SELECT top(20) c.Id, c.Value, c.Id_tag, d.Description, d.Tag FROM Coleta c INNER JOIN DadoTag d ON d.Id = c.Id_tag ORDER BY d.Tag");
            rs = pstm.executeQuery();
            
            while(rs.next()){
                Tags tagsadd = new Tags();
                
                tagsadd.setId(rs.getInt("Id"));
                tagsadd.setValue(rs.getDouble("Value"));
                tagsadd.setIdTag(rs.getInt("Id_Tag"));
                tagsadd.setDescription(rs.getString("Description"));
                tagsadd.setTag(rs.getString("Tag"));
                
                tags.add(tagsadd);
            }
            
        } catch (Exception e) {
            System.out.println("Erro ao listar clientes: " + e);
            e.printStackTrace();
        }finally{
            fecharConexao(conexao, pstm, rs);
        }
        return tags;
    }

}
public class ConnectionFactory {
    
    //caminho do banco de dados
    
    
    public Connection criarConexao(){
        Connection conexao = null;
        try {
            //Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            //conexao = DriverManager.getConnection(URL);  
            //conexao = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databaseName=RDADOSH;selectMethod=cursor","sa","4dm1n");
            //conexao = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks;integratedSecurity=true;");
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            conexao = DriverManager.getConnection("jdbc:jTDS:sqlserver://127.0.0.1:1433/RDADOSH","sa","4dm1n");
        } catch(SQLException ex){
            System.out.println("Erro: " + ex);
            ex.printStackTrace();
        }
        catch (Exception e) {
            System.out.println("Erro ao criar a conexão com o banco: " + e);
            e.printStackTrace();
        }
        return conexao;
    }
    
    public void fecharConexao(Connection conexao, PreparedStatement pstm, ResultSet  rs){
        try {
            if(conexao != null){
                conexao.close();
            }
            if(pstm != null){
                pstm.close();
            }
            if(rs != null){
                rs.close();
            }
        } catch (Exception e) {
            System.out.println("Erro ao fechar bd");
        }
    }

}
G

Faltou esse carinha:

TagController().listarTodos();

W

Vou passar tudo, está bem simples, pois estou testando para aprender…

public class TagController {
    
    public ArrayList<Tags> listarTodos(){
        return TagDAO.getInstance().listarTags();
    }
}
@XmlRootElement
public final class Tags {
    
    private Integer id;
    private Integer idTag;
    private Double value;
    private String description;
    private String tag;
    
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getIdTag() {
        return idTag;
    }
    public void setIdTag(Integer idTag) {
        this.idTag = idTag;
    }
    public Double getValue() {
        return value;
    }
    public void setValue(Double value) {
        this.value = value;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getTag() {
        return tag;
    }
    public void setTag(String tag) {
        this.tag = tag;
    }
    @Override
    public String toString() {
        return "Tags [id=" + id + ", idTag=" + idTag + ", value=" + value + ", description=" + description + ", tag="
                + tag + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((description == null) ? 0 : description.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((idTag == null) ? 0 : idTag.hashCode());
        result = prime * result + ((tag == null) ? 0 : tag.hashCode());
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Tags other = (Tags) obj;
        if (description == null) {
            if (other.description != null)
                return false;
        } else if (!description.equals(other.description))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (idTag == null) {
            if (other.idTag != null)
                return false;
        } else if (!idTag.equals(other.idTag))
            return false;
        if (tag == null) {
            if (other.tag != null)
                return false;
        } else if (!tag.equals(other.tag))
            return false;
        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        return true;
    }

}

e o web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>TesteWS</display-name>
    <servlet>
        <servlet-name>Jersey RESTful</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>

            <param-value>br.com.restful.resource</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey RESTful</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>
G

Da uma olhada com calma nesse material:

http://www.mkyong.com/webservices/jax-rs/jax-rs-queryparam-example/

Acredito que vai ajudar muito no que você quer.

:wink:

Qualquer coisa vai perguntando ai…

W

Opa, boa tarde, utilizando queryparam vai ficar complicado para o que estou querendo fazer, vi que é possível utilizar a anotação @PathParam para pegar um valor da URL, porém está sempre retornando 404. Fiz igual aos exemplos da net mas não estou conseguindo.
Fonte

@Path("/tag")
public class TagsResource {
    
    @GET
    @Path("/listarDados")
    @Produces("application/JSON")
    public ArrayList<Tags> listarDados(){
        return new TagController().listarTodos();
    }
    
    @Path("{id}")
    @GET
    @Produces({ MediaType.APPLICATION_JSON })        
    public ArrayList<Tags> consultaId(@PathParam("id") int id){
        return new TagController().consultaDados(id);
    }
}

quando chamo a URL(http://localhost:8080/Teste/tag/{1}), tenho o erro 404.

G

Nao sei se ele aceita endpoint tao generalista assim…

De qualquer forma, o que me chamou atenção foi que em @Path("{id}") pelo menos deveria ser assim: @Path("/{id}"), ele esta certo em dar 404, de fato a url que tais tentando acessar nao existe, pois tu nao mapeou o “/” no seu @Path.

Caso continue nao dando certo… tente deixar mais especifico essa url… algo tipo
@Path("/consulta/{id}")

:wink:

D
Solucao aceita

testa assim sem as chaves
http://localhost:8080/Teste/tag/1

G

Olha ai hein… nao tinha visto que ele digitou a url com as { } … no entando acho que no mapeamento tem que ter a “/”

@Path("/{id}")

W

Deu certo, obrigado a todos.

Criado 6 de janeiro de 2016
Ultima resposta 7 de jan. de 2016
Respostas 10
Participantes 3