Search code examples
javajsonweb-servicesrestsapui5

Full RESTFUL WebService with GSON and Java


I have created a RESTFUL webservice, witch returns a json, but at this time i only consult and show a simple select * , i need to create a complete CRUD solution, if anyone have some samples to share, i'll appreciate.

Best Regards to all

My code until now are:

DAO - Access.java

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import dto.Usuarios;

public class Access
{
    public ArrayList<Usuarios> getUsuarios(Connection con) throws SQLException
    {
        ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM usuarios");
        ResultSet rs = stmt.executeQuery();
        try
        {
            while(rs.next())
            {
                Usuarios usuariosObj = new Usuarios();
                usuariosObj.setUsr_id(rs.getInt("usr_id"));
                usuariosObj.setUsr_login(rs.getString("usr_login"));
                usuariosObj.setUsr_pwd(rs.getString("usr_pwd"));
                usuariosList.add(usuariosObj);

            }
        } catch (SQLException e)
        {       
            e.printStackTrace();
        }
        return usuariosList;

    }
}

DTO - Usuarios.java

package dto;

public class Usuarios
{
    private int usr_id;
    private String usr_login;
    private String usr_pwd;

    public Usuarios()
    {

    }

    public Usuarios(int usr_id, String usr_login, String usr_pwd)
    {
        super();
        this.usr_id = usr_id;
        this.usr_login = usr_login;
        this.usr_pwd = usr_pwd;
    }

    public int getUsr_id()
    {
        return usr_id;
    }

    public void setUsr_id(int usr_id)
    {
        this.usr_id = usr_id;
    }

    public String getUsr_login()
    {
        return usr_login;
    }

    public void setUsr_login(String usr_login)
    {
        this.usr_login = usr_login;
    }

    public String getUsr_pwd()
    {
        return usr_pwd;
    }

    public void setUsr_pwd(String usr_pwd)
    {
        this.usr_pwd = usr_pwd;
    }


    @Override
    public String toString()
    {
        return "[ {usr_id=" + usr_id + ", usr_login=" + usr_login + ", usr_pwd=" + usr_pwd + "} ]";
    }

}

Model - AccessManager.java

package model;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import dao.Access;
import dao.Database;
import dto.Usuarios;

public class AccessManager
{
    public ArrayList<Usuarios> getUsuarios() throws Exception
    {
        ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
        Database db = new Database();
        Connection con = db.getConnection();
        Access access = new Access();
        usuariosList = access.getUsuarios(con);
        return usuariosList;
    }
}

WebService - UsuariosService.java

package webService;

import java.util.ArrayList;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import com.google.gson.Gson;

import model.AccessManager;
import dto.Usuarios;

@Path("/UsuariosService")
public class UsuariosService
{
    @GET
    @Path("/usuarios")
    @Produces("application/json")
    public String usuarios()
    {
        String usuarios = null;
        ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
        try
        {
            usuariosList = new AccessManager().getUsuarios();
            Gson gson = new Gson();
            //usuarios = gson.toJson(usuariosList);
            usuarios = "{\"usuarios\" :" + gson.toJson(usuariosList) + "}";
        } catch (Exception e)
        {
                e.printStackTrace();
        }
        return usuarios;
    }
}

Solution

  • Usually you should ask a specific trouble you have instead of ask for samples. It looks like you have a structured code and all you need is implement all operations exposing as a service.

    In case you need a sample, there quite a lot of resources on the web. Something like this: https://code.google.com/p/javaee6-crud-example/

    I'll try give you some quick tips below:

    WebService - UsuariosService.java

    @POST
    @Path("/usuarios")
    public Response save(Usuario user) {
        try {
            manager= new AccessManager();
            manager.save(user);
            return Response.ok("User has been created.").build();
        } catch (Exception e) {
                e.printStackTrace();
        }
        return usuarios;
    }
    
    @DELETE
    @Path("/usuarios/{id}")
    public Response delete(@PathParam("id") String id) {
        try {
            manager= new AccessManager();
            manager.delete(id);
            return Response.ok("User has been deleted.").build();
        } catch (Exception e) {
                e.printStackTrace();
        }
        return usuarios;
    }
    
    @PUT
    @Path("/usuarios/{id}")
    public Response delete(@PathParam("id") String id, Usuario user) {
        try {
            manager= new AccessManager();
            manager.update(id, user);
            return Response.ok("User has been updated.").build();
        } catch (Exception e) {
                e.printStackTrace();
        }
        return usuarios;
    }
    

    If you don´t understand the usage of PUT, DELETE, POST and so on, I recommend you to read HTTP Method Tutorial. There is several discussion regarding this but you might skip it for a while.

    I think you might get an idea from here. Your DAO needs to implement methods to perform CRUD interface as well. The link I've added has a very simple sample that might help as well. You might also check this JPA link.

    Not sure whether info above helped but I think it is a start since you have to code it in order to understand more about it :)