Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access HttpServletRequest object from Jackson custom deserializer

I am trying to send an object via an ajax POST using JSON payload; this object has references to other objects stored in a database, handled by Hibernate; I need to access this database to resolve other objects references and store them in the new object obtained deserializing JSON payload of request.

Now, I have to access HttpServletRequest attribute in order to get a saved hibernate session to use to access to database. Is it possible?

The controller that handle the request is the following:

@RequestMapping(value = "/newproduct", method = RequestMethod.POST)
public @ResponseBody
Integer newProduct(HttpServletRequest request, @RequestBody Product product)
{
    //Controller code here
}

The deserializer where I have to be able to get request attribute "hibernate_session" is a custom deserializer, registered to Jackson and is the following:

public class ProductDeserializer extends JsonDeserializer<Product>
{

    @Override
    public Product deserialize(JsonParser jpar, DeserializationContext arg1)
        throws IOException, JsonProcessingException
    {

            Product newProduct = new Product();
            // I want to get request attribute or open a new hibernate session here 
            return newProduct;
    }

}

If necessary I'll post more code if needed.

Thanks

like image 633
gc5 Avatar asked Sep 15 '26 01:09

gc5


1 Answers

You may try following approach

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder

                .getRequestAttributes()).getRequest();
like image 132
kosa Avatar answered Sep 18 '26 08:09

kosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!