简体   繁体   English

如何使用Hibernate和Jersey在REST服务中发布

[英]How to POST in REST Service using Hibernate and Jersey

I wasn't able to find out proper format how to send Response back to .JSP page after POST. 我无法找到适当的格式,以便在POST之后如何将Response发送回.JSP页面。 First, how to obtain Response from Web service to Client? 首先,如何获得从Web服务到客户端的响应? Second question is how to call Client from Servlet. 第二个问题是如何从Servlet调用Client。

Because second part is quite straightforward (create class instance in servlet in the proper doGet, doPost method), I will focus on the first question. 因为第二部分非常简单(在servlet中使用正确的doGet,doPost方法创建类实例),所以我将重点关注第一个问题。

Snippet on the server side: 服务器端代码段:

import java.math.BigInteger;
import java.util.List;
import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.hibernate.SessionFactory;

// internal beans and classes
import com.deepam.util.BasicUtils;

import entities.CustomerRest;
import entities.DualInteger;
import entities.Dualloc;
import model.CustomerModel;
import model.DualModel;
import model.HibernateUtil;

@Path("/customer")
public class CustomerRestWS {

    private final static Logger LOGGER = Logger.getLogger(CustomerRestWS.class.getName());

    private CustomerModel cm = new CustomerModel();
    private DualModel dm = new DualModel();
    private final String CUSTSEQ = "customer_rest_seq";

    SessionFactory sessionFactory;

    /** Constructor
    */
    public CustomerRestWS() {
       super();
       LOGGER.info("***" + LOGGER.getName());
       sessionFactory = HibernateUtil.getSessionFactory();
    }

... ...

@GET
@Path("/findcustseq")
@Produces(MediaType.APPLICATION_XML)
public DualInteger selectCustSeq() {
    return cm.selectCustSeqNative(CUSTSEQ);
}

// post method how to save customer into DB
@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_JSON) // JSON is used for clearity between Consumes/Produces on the Client side
public Response create(final CustomerRest cust) throws JSONException {
    Response response;
    LOGGER.info("***" + LOGGER.getName() + " Insert Customer, id, name, last name: " + cust.getId() + ", " + cust.getFirstName() + ", " + cust.getLastName());
    try {
      cm.create(cust);
    }
    catch (Exception ex) {
      // internal error
      LOGGER.info("***" + LOGGER.getName() + " Exception: " + ex.getMessage());
      response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Response.Status.INTERNAL_SERVER_ERROR.toString()).build();
      return response;
    }
    // created
    response = Response.status(Response.Status.CREATED)
      .entity(Response.Status.CREATED.toString()).build();
    return response;
}

... ...

On the Client side: 在客户端:

import java.text.MessageFormat;
import java.util.logging.Logger;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;

// internal beans
import entities.Customer;
import entities.DualInteger;
import entities.ListCustomers;

    public class CustomerRestfulClient {
    private final static Logger LOGGER = Logger.getLogger(CustomerRestfulClient.class.getName());

    private WebResource webresource;
    private Client client;
    private static final String BASE_URI = "http://localhost:8080/RestfulOracleServer/rest/";

    public CustomerRestfulClient() {
        // init client
        client = Client.create(new DefaultClientConfig());
        // init webresource
        webresource = client.resource(BASE_URI).path("customer");
    }

... ...

    /** method getCustIdXML for obtaining unique ID (from sequence) */
public DualInteger getCustIdXML() throws UniformInterfaceException {
    WebResource resource = webresource.path(MessageFormat.format("findcustseq", new Object[] {}));
    return resource.accept(MediaType.APPLICATION_XML).get(DualInteger.class);
}


/** method saveCustXML call other method to obtain unique ID, than save Bean to DB */
public ClientResponse saveCustXML(String firstName, String lastName) throws UniformInterfaceException {
    DualInteger custId = getCustIdXML();
    LOGGER.info("Seqence number: " + (custId.getSeq()));
    Customer cust = new Customer(custId.getSeq(), firstName, lastName);
    ClientResponse response = webresource.path("create").
            accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_XML).post(ClientResponse.class, cust);
    LOGGER.info("Entity: " + response.getStatus());
    return response;
}

Notice classes Response on the Server side and ClientResponse on the Client Side. 注意服务器端的Response类和客户ClientResponse类。 Look how are treated @Consumes , @Produces annotations on server side to and accept , type methods on the Client side. 你看如何对待@Consumes@Produces在服务器端注释和accepttype在客户端的方法。 There were my sources of errors. 我有很多错误来源。 In servlet Controller for .jsp simply create Client for WS eg custClient = new CustomerRestfulClient(); 在.jsp的Servlet控制器中,只需为WS创建客户端,例如custClient = new CustomerRestfulClient(); in constructor and use the obvious methods doGet , doPost as obvious. 在构造函数中,并使用显而易见的方法doGetdoPost作为显而易见的方法。 The Servlet has its own Request , Response different from Request , Response of WS. 该servlet有它自己的RequestResponse来自不同的RequestResponse WS的。 Be carefully in MVC model, Controller is treated by server as Singleton. 在MVC模型中要小心,Controller被服务器视为Singleton。 In concurrent environment you must keep session continuity. 在并发环境中,必须保持会话连续性。 (The most simple way is to use local variables in methods, when it is indicated.) Links to similar topics: Is it ok by REST to return content after POST? (最简单的方法是在指示时在方法中使用局部变量。)链接到类似主题: REST是否可以在POST之后返回内容? RESTful Java Client with POST method 带有POST方法的RESTful Java客户端

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将一个对象发布到Jersey Rest Service - How to post an object to Jersey Rest Service REST Service-使用Jersey在https上以流形式进行多部分发布(JSON和文件) - REST Service - Multipart Post (JSON and File) as stream on https using Jersey 如何使用 POST 将数组发送到 REST-Service (Jersey) - How send Array to REST-Service (Jersey) with POST 如何使带有JSON数据的post ajax调用到Jersey休息服务? - How to make post ajax call with JSON data to Jersey rest service? Jersey UniformInterfaceException尝试代理REST POST服务 - Jersey UniformInterfaceException trying to proxy to REST POST service POST JSON到Jersey REST服务的问题 - Issue with POST JSON to a Jersey REST service CRUD在休眠状态下从ManyToMany中使用Jersey使用Java的REST API在REST API中使用POST方法读取JSON的问题 - CRUD issue reading a JSON using POST method in a REST API in Java using Jersey from a ManyToMany noted in hibernate 如何使用模拟对象测试Jersey休息服务 - How to test a Jersey rest service using mock objects 如何使用 Jersey Rest 服务传递.jad 文件? - How to deliver .jad file using Jersey Rest service? 如何使用 jersey 和 Z93F725A07423FE1C889F448B33 在 REST web 服务中进行身份验证 - how to do authenticate in REST web service using jersey and java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM