I am trying to do deep clone of httpservletRequest object so that I have copy of all referenced objects in order to use it my business logic. Can I make deep clone of httpservletRequest ? any implementation Idea will be great!
Thanks
Related
I'm using spring data rest with #RepositoryRestResource where all the verbs are automatically handled for all the entities in the system.
There is no controller necessary for my project.
But I do want to perform certain action before the GET call is made to an entity. What is the best way to do this without writing a custom controller?
There are event handlers I can write in Spring Data Rest like #HandleAfterDelete but there are not handlers for GET.
I'm afraid there is currently no solution which would provide this out of the framework itself. However, there is a pull request which was discussed but not yet implemented as there are still open questions with regard to the universality of findBy* methods.
In case you do not need a that general solution the yet suggested HandlerInterceptor is the way to go…
public class YourInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
// decide on request.getMethod() what to do next
}
}
I can define a GET method in two ways:
public ResponseEntity<Pet> getPetById(Long id);
and
public Pet getPetById(Long id);
They seem to be equivalent, except that the first one involves more boilerplate code.
So, what is the reason to use ResponseEntity and what advantages it brings?
The difference is quite easy to explain. When you use ResponseEntity, you have full control about the contents of your response. You can change your headers, status code, ...
When you don't use ResponseEntity as the return type of a controller method, spring will "automagically" create a default ResponseEntity.
So the biggest advantage in using ResponseEntity is that you have full control. The disadvantage is that it is more verbose than letting Spring work its magic.
I have a situation where i have to update the request before i process it. basically, I will have to update the request with a property which can change with time. It is not practical to ask the consumer send the property along with request.. So, I feel like the only way to do it is.. update the request in controller method before processing it..
#RequestMapping(value="/**", method=RequestMethod.POST)
public void processRequest(HttpServletRequest servletRequest, HttpServletResponse response )
Untill now, HttpServletRequest is used in the controller method. the request is then read as stream and then converted to json string to get processed. I am thinking to replace it with #RequestBody and have the request read into a pojo, then update, then process. But, I also need the pathInfo from HttpServletRequest to identify which uri i need to process the request for..
So, Can i use both #RequestBody and HttpServletRequest in the same method??
I tried it and i dint see any issues.. But, I wanted to check if there is any thing i am missing..
#RequestMapping(value="/**", method=RequestMethod.POST)
public void processRequest(#RequestBody final DateRequest request, HttpServletRequest servletRequest, HttpServletResponse response )
Please advise..
This is fine and supported by Spring. As a matter of fact, I just finished writing a controller method virtually identical to the one you use in your example. Spring is very flexible with what is allowed for a method decorated with #RequestMapping. According to the documentation:
#RequestMapping handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values. ... The table below shows supported controller method arguments.
[ See documentation for complete table ]
In the table of acceptable argument types, it specifically allows HttpServletRequest, HttpServletResponse, and objects annotated with #RequestBody.
So you should be set, according to your findings, the fact that other people are doing this, and the documentation specifically mentioning it.
In our application, all rest apis are of the form:
http://{context}/{product_id}/{rest_url_path}
I have to verify the {product_id} inside a Spring Security Filter/SpringMVC interceptor, by fetching the ProductDetails from DB for the product_id. The ProductDetails will be used inside Spring Controllers/Service classes.
I don't want to fetch the ProductDetails again inside Controllers/Service. So I want to store the ProductDetails object somewhere for that RequestScope.
I have 3 approaches in mind. But each have their pros and cons. Please let me know which one better out of the 3. Also suggest any alternative approach.
Approach-1:
Save the ProductDetails object inside request attribute.
Inside Controller, i can easily get the HttpRequest. Inside Service, I can get HttpRequest by:
#Autowired
HttpServletRequest request;
or
RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = null;
if (attribs instanceof ServletRequestAttributes) {
request = ((ServletRequestAttributes) attribs).getRequest();
}
But I don't want to have HTTP request dependency inside Service to make to code more independent from WebLayer logic.
Approach-2:
Use any in memory cache based on product_id to stored ProductDetails
But this I think a over kill only for this use case. Increasing unnecessary dependencies of a cache.
Approach-3:
Store the Object in a ThreadLocal variable to store request scope data.
But not sure if it correct this way.
Let me know an efficient approach to solve this problem
1st and 3rd are suitable for your problem statment but first one is more elegant as data will stored only for current request scope and will get automatically lost when server send response. You can also use threadLocal but you have to be cautious ,if you forget to remove object it will hang around in an environment that uses a thread pool.
The first approach you mentioned is more efficient way to access the same data in both filter and controller even though you have to inject the dependency of HttpservletRequest in SpringController.
If the data is very user specific like other user will not have access to those data in that case you should use ThreadLocal.
I have some POJOs which are the basis for this RESTful API I am working on. However, some of the responses I need to include some other information to make the API more complete. I really don't want to put these extra information in the POJO, but include it at the web service layer as if it were.
It deals with "People" who have "Appointments". Each appointment only has one person.
So, I have a RESTful call like /Patients/1 and it basically grabs the POJO for the Person and I am currently using XStream to serialize it and send it on its way. This works great, but I would like to do something like this:
<Person>
<firstName>James</firstName>
... other fields ...
<nextAppointment href="/Appointment/12345>2010-02-19</nextAppointment>
<prevAppointment href="/Appointment/12346>2010-01-01</prevAppointemnt>
</Person>
Where next and prev appointment are not actually included in the Person POJO. I am looking for a good "spring way" to accomplish this. The client could do something like this /Patients/1/PreviousAppointment and /Patients/1/NextAppointment, but I am looking to cut the amount of calls (maybe pre-optimization?) and give them a way to get more information if they need it by using he href.
It is very elegant using the XStreamMarshaller since all I do it hand the view the POJO or list of POJO and it handles it. But I need to doctors those up a bit before they are sent out.
Thanks!
This is the problem with handing your business objects directly to the marshaller - you have very little flexibility in how they turn that object into the response. There is something to be said for pre-transforming the objects yourself, you get more control that way.
So if you have a specific output structure that you want, then with XStream you need to build a class structure that looks like it. You then transform your business objects into that class structure, and pass that to XStream instead.
It may seem less elegant, but your system will be much less prone to being broken by small changes in your business object model, which you your current XStream-based system will be.
Solution to your problem : CREATE A CUSTOMIZEDCONVERTER...
public class CustomizedConverter implements Converter {
#Override
public void marshal(Object source, HierarchicalStreamWriter writer,MarshallingContext context) { ....}
#Override
public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {..}
#Override
public boolean canConvert(Class clazz) {..}
}
To know what to use the converter with the Marshaller refer this.
So basically the CONVERTER works on the POJO and ensures we get the XML response as given in the contract.