How to Create REST Client, the response should be come in JSP page?

1.4k Views Asked by At

I developed server side web services developed with rest. My Code working fine while checking with POSTMAN application. But i want to get the response for all the CRUD operation in JSP page. The every response should be display in JSP page and The Data consumes should be JSP page. Could you please provide way for how to develop REST Client. I am new to Rest Client.

Product.java

public class Product {

private long pid;
private String pname;
private String category;
private float price;
private long stock;
private String remarks;

public Product()
{

}

public Product(long pid,String pname,String category,float price,long stock,String remarks){
    this.pid=pid;
    this.pname=pname;
    this.category=category;
    this.price=price;
    this.stock=stock;
    this.remarks=remarks;
}
public long getPid() {
    return pid;
}
public void setPid(long pid) {
    this.pid = pid;
}
public String getPname() {
    return pname;
}
public void setPname(String pname) {
    this.pname = pname;
}
public String getCategory() {
    return category;
}
public void setCategory(String category) {
    this.category = category;
}
public float getPrice() {
    return price;
}
public void setPrice(float price) {
    this.price = price;
}
public long getStock() {
    return stock;
}
public void setStock(long stock) {
    this.stock = stock;
}
public String getRemarks() {
    return remarks;
}
public void setRemarks(String remarks) {
    this.remarks = remarks;
}

}

DatabaseClass.java

public class DatabaseClass {

private static Map<Long, Product> products=new HashMap<>();

public static Map<Long, Product> getProduct()
{
    return products;
}   

}

ProductDaoImpl.java

public class ProductDaoImpl implements ProductDao {

private Map<Long, Product> products=DatabaseClass.getProduct();

public ProductDaoImpl()
{
    products.put(1L, new Product(1L,"TV","Entertinement",10000F,250L,"This is best TV!"));
    products.put(2L, new Product(2L,"Computer","Technology",20000F,350L,"My Computer name Hp and SONY ViVo!"));
    products.put(3L, new Product(3L,"DeskTopComputer","Technology",15000F,150L,"My Desktop Computer name Accer and SONY ViVo!"));
}

//Get All products
public List<Product> getAllProducts() {

    return new ArrayList<Product>(products.values());
}

//Get product by product id
public Product getProduct(long pid) {

    return products.get(pid);
}

//To Add the products 
public Product addProduct(Product product) {
    product.setPid(products.size()+1);
    products.put(product.getPid(), product);
    return product;
}

//Update the product
public Product updateProduct(Product product) {
    if(product.getPid()<=0)
    {
        return null;
    }
    products.put(product.getPid(), product);
    return product;
}

// Delete the product
public Product deleteProduct(long pid) {

    return products.remove(pid);

}



//Get the product by category
public List<Product> getProductByCategory(String category) {

    List<Product> list = new ArrayList<Product>();

    if (products.size()<=0) {
        return null;
    }

    else{

        for(Product p: this.products.values()){

            if(p.getCategory().equals(category))
                list.add(p);    
        }
        return list;    
    }

}

//Get the product by price
public List<Product> getProductsBasedOnPrice(float startPrice, float endPrice) {

    List<Product> list = new ArrayList<Product>();

    if (products.size()<=0) {
        return null;
    }

    else{

        for(Product p: this.products.values()){

            if(startPrice<=p.getPrice() && endPrice>=p.getPrice())
            {
                list.add(p);    
            }
        }
        return list;    
    }

}}

ProductServiceImpl.java

@Path("/products")

public class ProductServiceImpl implements ProductService {

ProductDaoImpl productService=new ProductDaoImpl();

@GET
@Produces(MediaType.APPLICATION_XML)
public List<Product> getProducts() {

    return productService.getAllProducts();
}

@GET
@Path("/{pid}")
@Produces(MediaType.APPLICATION_XML)
public Product getProduct(@PathParam("pid") long pid)
{
    return productService.getProduct(pid);
}

@POST
@Produces(MediaType.APPLICATION_XML) 
@Consumes(MediaType.APPLICATION_XML)
public Product addMessage(Product product)
{
    return productService.addProduct(product);
}

@PUT
@Path("/{pid}")
@Produces(MediaType.APPLICATION_XML) 
@Consumes(MediaType.APPLICATION_XML)
public Product updateProduct(@PathParam("pid") long pid,Product product)
{
    product.setPid(pid);
    return productService.updateProduct(product);
}

@DELETE
@Path("/{pid}")
@Produces(MediaType.APPLICATION_XML) 
public void deleteMessage(@PathParam("pid") long pid)
{
    productService.deleteProduct(pid);
}

@GET
@Path("category/{category}")
@Produces(MediaType.APPLICATION_JSON)
public List<Product> getProductsBasedOnCategory(@PathParam("category") String category) {

    return productService.getProductByCategory(category);
}


@GET
@Path("basedOnPrice")
@Produces(MediaType.APPLICATION_JSON)
public List<Product> getProductsBasedOnPrice(@QueryParam("startPrice") float startPrice, @QueryParam("endPrice") float endPrice) {
            if(startPrice>0 && endPrice>0)
            {
            return productService.getProductsBasedOnPrice(startPrice, endPrice);    
            }
    return productService.getAllProducts();
}

}

2

There are 2 best solutions below

0
On

You can use Jquery to create promises or ajax calls to interact with the backend. Another way,If you are using only restful services and not the spring MVC modules,then is to use angularjs i.e angular 1.x in which you can use https modules to make restful calls and use routing modules to route the pages(this will also make you application a SPA)

1
On

You could use the jersey library for example, https://jersey.github.io/

then you will get somthing like this (JSON or XML to string)

    ...
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;

    // Create Client
         Client client = Client.create();

         WebResource webResource = client.resource("http://localhost:8080/<yourpath to resource>");

         ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

         // Status 200 is successful.
         if (response.getStatus() != 200) {
             System.out.println("Failed with HTTP Error code: " + response.getStatus());
             String error= response.getEntity(String.class);
             System.out.println("Error: "+error);
             return;
         }

         String output = response.getEntity(String.class);

         System.out.println("Output from Server .... \n");
         System.out.println(output);
         ...