Search code examples
javajax-ws

Jax-ws: Log request and response in database


I have a web service which contains getEmployeeList method and i need to log request and response in a database like;

***Column**  **Id   Request       Response       ResponseTime*** 
               1    Request1      Response1      600ms
               2    Request2      Response2      400ms

My employee service class;

@WebService
@HandlerChain(file="employeehandler-chain.xml")
public interface EmployeeWS {

@WebMethod
List<Employee> getEmployeeList(
        @WebParam(name = " EmployeeReq")  EmployeeReq  employeeReq);

My custom handler class ;

public class EmployeeHandler implements SOAPHandler<SOAPMessageContext> {

 @Override
 public boolean handleMessage(SOAPMessageContext context) {


    Boolean outBound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    try {
        SOAPMessage soapMsg = context.getMessage();

Is there a way to correlate the request and response in my handler ?


Solution

  • You can create an id when you are handling an inbound message and save into the SOAPMessageContext and get it when you are handling the response:

    Boolean outBound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    
    if (!outbound) {
        Long messageId = createId();
        context.put("messageId", messageId);
        saveRequestToDatabase(context.getMessage(), messageId);
    } else {
        saveResponseToDatabase(context.getMessage(), context.get("messageId"));
    }
    

    Each request creates a new SOAPMessageContext which is kept alive until the end of the response process, so even if there are various requests being executed concurrently each context will be different.