Java – how to add parameters to a request from a containerrequestfilter
•
Java
I use Jersey spring I have Jersey filter, which implements containerrequestfilter. I need to transfer objects in my jersey resources
For example:
@Provider public class UnmarshalEntityFilter implements ContainerRequestFilter { private static final Logger LOGGER = LoggerFactory.getLogger(UnmarshalEntityFilter.class); @Override public ContainerRequest filter(ContainerRequest containerRequest) { final String xml = getRequestBody(containerRequest); // Parse this xml to Object // How I can add this Object to my request and get from Jersey Resource ? return containerRequest; } private String getRequestBody(ContainerRequest request) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = request.getEntityInputStream(); StringBuilder sb = new StringBuilder(); try { if (in.available() > 0) { ReaderWriter.writeTo(in,out); byte[] requestEntity = out.toByteArray(); sb.append(new String(requestEntity,"UTF-8")); } return sb.toString(); } catch (IOException ex) { throw new ContainerException(ex); } }
}
Solution
See containerrequest #setproperty (string, object) method
So you can simply call
final String xml = getRequestBody(containerRequest); containerRequest.setProperty("xml",xml);
Then inject HttpServletRequest into your handler and access it using httpservletrequest#getattribute ("XML")
Using Jersey 1.17, the corresponding method is containerrequest #getproperties (), which returns a variable map < string, Object > where you can put the properties to be synchronized with ServletRequest
You can retrieve the attributes in the Jersey resource from httpcontext:
@Context private HttpContext httpCtx ... final String xml = httpCtx.getProperties().get("xml")
Also, note the consumption request InputStream If some other component in the stack also needs to read from the stream, it will fail
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码