MyFaces Orchestra adds a ?conversationContext=x to each resource on a page. Since I'm not using the conversation scope for the public part of my project (only for the admin part), I'd like to get rid of that parameter for two reasons:
it breaks the browser caching of static resources
it's ugly :)
I'm now going to take a look at Orchestra's source-code, and perhaps bypass something, but it would be best if there is an option for this I'm unaware of
The answer to that question is simple, and at the same time a bit of a workaround.
MyFaces orchestra uses a wrapper around the original HttpServletResponse in order to encode the contesationContext parameter.
There are two options of using Orchestra - with an interceptor (JSF) and a Filter.
Both of them try to wrap the response, if it isn't already wrapped. So if both the orchestra Filter and the interceptor are used, the Filter comes firest, wraps the response object, and sets an attribute in the request, which indicates to the interceptor, that it shouldn't wrap the response again.
The Filter can be configured to match a certain URL pattern if conversationContext is to be added. However, for my needs, that pattern matcher was too simple, so I made my own filter instead. So in order to tell the interceptor NOT to wrap the response, all that has to be done is this:
httpRequest.setAttribute(
RequestParameterServletFilter.REQUEST_PARAM_FILTER_CALLED,
Boolean.TRUE);
Related
I really like functional programming, I like its immutability concepts and also it's no side-effects concepts for functions.
I'm trying to take some of these concepts into java.
Now I have some kind of a servlet which receives a request and if browser did not send a cookie to server then i would like to create a cookie with a certain path to the user.
now inside the servlet i don't want to hold that logic because its common to multiple servlets.
so i extract it into some kind of a cookie manager which will do that:
CookieManager.java.handleCookies(request, response)
Check if browser sent cookie.
If not set cookie with new session cookie value with certain path.
however i don't like it because now the servlet will call the CookieManager.java.handleCookie will have a side effect I would rather it to return some kind of a response and further use it in my servlet wihtout having it effect its parameters that i'm passing into it.
anyone can suggest a solution which would both be elegant, no side effects, and excellent in performance?
thanks
You can make use of servlet filter. It would be well suited for your case. You can map your filter to URL pattern and write your code inside dofilter method. Filters are recommended if you want to have pre and post prcoess of request/response. Since you are doing preprocess for you request it would fit in your case. If is also loosely coupled, because you can remove it, modify it, or add another rule anytime without modifying the core servlet code.
One good solution is to use create a servlet which will act as a parent class for all other servlets.
Now in this servlet put this logic of cookie handling in a common function say handlecookie.
In your get and post APIs of this servlet first call this handleCookie and then service API of servlet (keep this empty)
In al child servlet classes you can only override the service class inherited from the parent class and things should work fine for you
Servlet filters are other solution that you can make use of.
This must have been answered previously, but my Google powers are off today and I have been struggling with this for a bit. We are migrating from an old PHP base to a Jersey-based JVM stack, which will ultimately provide a JSON-based RESTful API that can be consumed from many applications. Things have been really good so far and we love the easy POJO-to-JSON conversion. However, we are dealing with difficulties in Cross-Domain JSON requests. We essentially have all of our responses returning JSON (using #Produces("application/json") and the com.sun.jersey.api.json.POJOMappingFeature set to true) but for JSONP support we need to change our methods to return an instance of JSONWithPadding. This of course also requires us to add a #QueryParam("callback") parameter to each method, which will essentially duplicate our efforts, causing two methods to be needed to respond with the same data depending on whether or not there is a callback parameter in the request. Obviously, this is not what we want.
So we essentially have tried a couple different options. Being relatively new to Jersey, I am sure this problem has been solved. I read from a few places that I could write a request filter or I could extend the JSON Provider. My ideal solution is to have no impact on our data or logic layers and instead have some code that says "if there is a call back parameter, surround the JSON with the callback, otherwise just return the JSON". A solution was found here:
http://jersey.576304.n2.nabble.com/JsonP-without-using-JSONWithPadding-td7015082.html
However, that solution extends the Jackson JSON object, not the default JSON provider.
What are the best practices? If I am on the right track, what is class for the default JSON filter that I can extend? Is there any additional configuration needed? Am I completely off track?
If all your resource methods return JSONWithPadding object, then Jersey automatically figures out if it should return JSON (i.e. just the object wrapped by it) or the callback as well based on the requested media type - i.e. if the media type requested by the client is any of application/javascript, application/x-javascript, text/ecmascript, application/ecmascript or text/jscript, then Jersey returns the object wrapped by the callback. If the requested media type is application/json, Jersey returns the JSON object (i.e. does not wrap it with the callback). So, one way to make this work is to make your resource method produce all the above media types (including application/json), always return JSONWithPadding and let Jersey figure out what to do.
If this does not work for you, let us know why it does not cover your use case (at users at jersey.java.net). Anyway, in that case you can use ContainerRequest/ResponseFilters. In the request filter you can modify the request headers any way you want (e.g. adjust the accept header) to ensure it matches the right resource method. Then in the response filter you can wrap the response entity using the JSONWithPadding depending on whether the callback query param is available and adjust the content type header.
So what I ultimately ended up doing (before Martin's great response came in) was creating a Filter and a ResponseWrapper that intercepted the output. The basis for the code is at http://docs.oracle.com/cd/B31017_01/web.1013/b28959/filters.htm
Essentially, the filter checks to see if the callback parameter exists. If it does, it prepends the callback to the outputted JSON and appends the ) at the end. This works great for us in our testing, although it has not been hardened yet. While I would have loved for Jersey to be able to handle it automatically, I could not get it to work with jQuery correctly (probably something on my side, not a problem with Jersey). We have pre-existing jQuery calls and we are changing the URLs to look at the new Jersey Server and we really didn't want to go into each $.ajax call to change any headers or content types in the calls if we didn't have to.
Aside from the small issue, Jersey has been great to work with!
Today's browsers (or HTML < 5) only support HTTP GET and POST, but to communicate RESTful one need PUT and DELETE too. If the workaround should not be to use Ajax, something like a hidden form field is required to overwrite the actual HTTP method.
Rails uses the following trick:
<input name="_method" type="hidden" value="put" />
Is there a possibility to do something similar with JAX-RS?
Not strictly a JAX-RS solution but spring 3.0 comes with a HiddenHttpMethodFilter that implements exactly the trick that rails does, defaults to the same _method parameter.
Note that you don't need to be using all of spring to use this filter, you can just configure it in your web.xml and ignore the rest of spring.
Jersey also has something similar, filtering a header field though. Documentation can be found here
To quote Roy Fielding:
In any case, there are plenty of
RESTful services that do nothing but
GET and POST. The key is how those
methods are used, not what methods are
used. To give a specific example, what
makes a wiki more or less RESTful is
almost always determined by how it
(ab)uses GET and sessions -- whether
it uses PUT or POST for editing pages
is sugar topping in comparison.
Emphasis is mine, taken from this post
http://tech.groups.yahoo.com/group/rest-discuss/message/10746
I'm trying to log the raw body of HTTP POST requests in our application based on Struts, running on Tomcat 6. I've found one previous post on SO that was somewhat helpful, but the accepted solution doesn't work properly in my case. The problem is, I want to log the POST body only in certain cases, and let Struts parse the parameters from the body after logging. Currently, in the Filter I wrote I can read and log the body from the HttpServletRequestWrapper object, but after that Struts can't find any parameters to parse, so the DispatchAction call (which depends on one of the parameters from the request) fails.
I did some digging through Struts and Tomcat source code, and found that it doesn't matter if I store the POST body into a byte array, and expose a Stream and a Reader based on that array; when the parameters need to get parsed, Tomcat's Request object accesses its internal InputStream, which has already been read by that time.
Does anyone have an idea how to implement this kind of logging correctly?
In fact, Struts doesn't parse the parameters, it relies on the Servlet container to do that. And once the container has read the inputStream to create the parameters Map, of course there is nothing left to read. And in the Tomcat implementation, if you read the inputStream first, then the getParameter* family of methods has nothing left to work on, since, as you correctly note, it doesn't use getInputStream or getReader but accesses internally its optimized reader.
So your only solution in your ServletRequestWrapper is to override getInputStream, getReader, AND the getParameter* family on which Struts relies to read the parameters. Maybe you can have a look at org.apache.catalina.util.RequestUtil to not duplicate the POST body parsing part.
What you have to do in your filter is read the post content in its entirety then when you go to pass the request on to the chain; back the input stream with your own. For example you read the post to file on disk, then when you call:
chain.doFilter(new ServletRequest() {}, response);
You can delegate most methods invocations of your class to the original request, but when it comes time to opening the input stream you need to read from your file on disk.
You need to make sure you don't leak resources as this will be invoked quite frequently and can hurt if done incorrectly.
The in the question linked filter example looks good and ought to work. Maybe you're defining it in the web.xml after the Struts dispatcher filter. It would then indeed be too late to parse and log the request body and still make it available for Struts. You need to declare this filter before the Struts dispatcher filter. The filter ordering matters, they are invoked in the order as they're definied in web.xml.
I know, it depends on the webapp. But in the normal case, what do you do: one servlet, that serves different pages (like an standalone-application with changing content) or for every page a single servlet.
Take for instance a blog. There is the start-page with the most recent blog-entries, an article-view for displaying one blog-entry and an archive. Do you implement this with three different servlets, or one that is dispatching to the functions. At least a good part of the stuff is shared, like http-headers.
So, what are your experiences, what works best?
Usually you will create a servlet per use case. Servlets acts like controllers for your application. When you identify an interaction from a user then implement a servlet to control that interaction.
That is, if you are using plain servlet/JSP to build the site. If you are using a framework like struts you will find that they implement the front controller pattern and use a single servlet that recieves all the requests and forwards these requests to action classes that implement the actual logic of the user request. this is much harder to do yourself but its a good practice...its the reason why so many people use these frameworks.
So the short answer is, you will create many servlets per webapp since each webapp will expose several use cases.
[EDIT] Re-reading your question it seems as if you are using the term site to mean page or view. Again, it depends on what is happening on that view. For instance, To display the newest blog entry, you can have a servlet that constructs the list of entries from the database for display. If the user clicks on an entry then another servlet can retrieve that single entry for viewing and so on. Mainly, each action is a use case therefore a different servlet.
Most web frameworks use a dispatcher servlet (ex: Spring MVC) that takes care of routing requests to appropriate classes/controllers.
When you start having lots of pages, this approach works best because you have a more user friendly way (in regard to web.xml) of declaring/managing a class that handles http requests and its url. Example (spring mvc again):
#Controller
public class MyController {
#RequestMapping("/viewPosts")
public void doViewPosts(HttpRequest r, HttpResponse res) {
//...
}
}
Besides, having a dispatcher servlet keeps your code flow centralized.
It depends.
In my latest projects, I have implemented a single servlet that delegates to several servlet-like objects which are instantiated in a dependency injection fashion. For instance, I have something like this in my servlet (pseudo-code):
for(Handler handler : handlers) {
if(handler.handle(request, response)) {
return;
}
}
where Handler is an interface with a boolean handle(request, response) method. I obtain my handlers from a container (be it Spring or something even more lightweight).
The reason for this is that I really like dependency injection, and it is difficult to achieve it in Servlets; and I really don't feel much at home with most frameworks that provide web-component dependency injection- I like the simplicity of servlets.
Were not for this, I would go with multiple servlets, although there's a trade-off; either you have an enormous web xml with lots (and lots) of servlet mappings or you have a very complex servlet (unless you use something like my d-i approach).