Spring portlet go to render phase from action phase - jsr286

If in spring portlet controller, I have one methof annotated with #ActionMapping and another method annotated with #RenderMapping(params = "action=detail"), I see that to come from method #1 to method #2, we do not call the method#2 directly, instead we set a Actionresponse.setRenderParameter("action", "detail") in method #1 and method#2 will pick it up from here.
My first question is what advantages are we getting from separating the render phase from the Action Phase (or should I say Request Phase)? And also why we do not do a direct method call and instead call the method by setting a render parameter?

To answer your questions
Portlets can co-exist on a page. Irrespective of what action you performed on a portlet, the Portal container will invoke render() method on all the portlets to collect the html fragments and aggregate them, in an effort to prepare the whole page view and serve to the browser. Having 2 methods is not only an advantage but an enforcement to implement the aforementioned requirement which separates the business logic - processAction() that may change the state of your system as #Mark Chorley said, which you are aware of the execution "AND" render logic - render() which decides the view to render, which sometimes you are not aware of the execution.
This is simple, why do you call start() rather then run() on a Thread though you can invoke run method directly. There are many reasons why you shouldn't call the method directly
You are not responsible for the aggregation of html fragments from all the Portlets residing on the page.
You are not the one who make the Public Render parameters available in the render() method of the interested Portlets.
Definitely you dont want to take the headache of delegating the Events to the subscribed portlets

This is what portlets do basically. As to what advantage you get - well it allows you to separate your action (typically modifying data) from preparing data for your view.
Both Action and Render are different stages of a single request. Action requests precede Render requests as you say. "Request phase" sounds a confusing term to me. Action Phase and Render Phase are more helpful terms.
Why you don't call it directly - well the portlet container will do it for you. Also you must remember that the render methods will be called on all the visible portlets, but the action request will target only your portlet.
So given that the portlet container is guaranteed to call all the render methods on all the visible portlets, it doesn't make sense to call the render method manually on one portlet just because the action request targeted it.
If you only have one portlet visible this is perhaps less clear. It makes more sense when you have multiple portlets on a single page.

Related

How to handle service-calls in a portlet-environment (2 requests per action)

I am looking for alternatives to a session-flag when using a portlet (jsr-286) together with JSF 2.0.
The problem is that I have to use #PostConstruct to load data from the backend. The reason is because the portlet is loaded within a dynamic portlet-page at runtime. So when the portlet is loaded the first time, RESTORE_VIEW is called for the RenderRequest and several Webservices are called to load some data.
When triggering an action on the page I run into the problem with the two requests in a portlet-runtime: first the ActionRequest is handled, again RESTORE_VIEW is called, and the LifeCycle continues till the end of INVOKE_APPLICATION.
Now, the RenderRequest is processed which calls RESTORE_VIEW and RENDER_RESPONSE.
My BackingBeans are all #RequestScoped and this means that #PostContruct is called twice when invoking an action, and this causes an performance issue because the webservices are also called twice.
The simplest idea now was to use a session-flag within the portlet that is used to control when backend-services need to be called and when not.
Are there better alternatives to this approach? How do other people handle Bean-Initialization in a Portlet-JSF2-Environment?

How to set ViewBag for _Layout in MVC4 using async in every action

The usecase is simple. Info for logged in user is displayed in _Layout.cshtml. That info needs to be refreshed every time.
I found two ways to do that
Have BaseController and in its OnActionExecuting method set ViewBag.UserInfo = ...; which is later used in _Layout.cshtml
In _Layout.cshtml do #{Html.RenderAction("GlobalUserInfo", "UserInfo");}
The problem is that these two ways fail miserably with deadlocks or exceptions if UserInfo is returned from an async public async Task<UserInfo>GetUserInfo(){...} method.
So the question is this: How to set ViewBag properties on every action when data is retrieved using async/await.
MVC is not quite fully async-friendly, particularly with filters.
You could write your own RenderAsyncAction extension method or duplicate the code in all your async actions.
Alternatively, you could attempt a bit of a hack. I describe on my blog why using Result in ASP.NET can deadlock, but there's a workaround: use ConfigureAwait(false) on every await in GetUserInfo.
Then you can define a synchronous wrapper:
public UserInfo GetUserInfoBlocking()
{
return GetUserInfo().Result;
}
You should be able to use GetUserInfoBlocking in OnActionExecuting or RenderAction.
Please note the side effects:
This approach uses multiple threads per request, so this will decrease scalability. The pure async approach uses multiple requests per thread, so it increases scalability.
Any exceptions from GetUserInfo will be wrapped in an AggregateException, so be sure your logging will capture the InnerException details or you'll get meaningless errors in your logs.
It's definitely best to use async all the way down instead of blocking like this. But sometimes MVC doesn't leave you a choice (hopefully this will change in the future).

Struts Interceptor workflow

In Struts2 if we have define an interceptor stack and it is called in First in First Out manner.
So in post processing phase what happened if one of the earlier interceptor return a control string which in result render the response to the client.
I want to know that would the left interceptor will be processed or not.
Well it will work like this.
Your action method will only called once the interceptor stack has been called fully.This means that once the first interceptor has been called successfully in the stack it will call the next interceptor defined in the stack and there reference being stored in the stack this chain will keep on calling till the last interceptor in the stack is called
invocation.invoke()
this call is the key to call next interceptor defined in the stack or of this is the last it will call the desired function in your action class.
now in other case suppose some of the interceptor failed say workflow it will return the result as INPUT and will halt the further execution of the interceptor and framework will output the desired JSP/Tempelate to the user.
Than comes the post -processing/cleaning in this case interceptors will be called in reverse order i.e top most or latest executed interceptor will be called first and den so on so.
The idea for this post-processing is to do any clean-up work or any other things which needs to be done (like cleaning up resources etc)
Hope this will give you some idea.

What things can I put inside a BaseController to make my MVC life simpler

My base controller has:
[Authorize(Roles = "sys_admin")]
I want to have one action in a controller that's different and is available to "user" and "sys_admin". Can I override and how do I do that?
Also any suggestions on what else I could put in a base controller that might make my coding simpler. For example what's in your base controllers?
Anything that you use in every controller - attributes, methods, properties, etc. The same stuff you would put in any base class.
Just to add to the discussion, I have a few extra utility methods in my shared controller. I write a bunch of little apps for corporate use, so I try to repeat code as little as possible here.
getContext(): Puts together an object containing user info like IP, hostname, id, etc. for logging purposes.
Shared Views/Partials such as Error, Default, and Redirect (used for redirecting ajax requests).
RedirectToError(): I created this to use similar to RedirectToAction. I load up an ErrorObject with info, throw it in session, and return a Redirect to my Error page.
General logging and tracing methods so I can quickly spit out information to a file.
I override OnActionExecuting and check if my session is still valid and redirect to login if its not. Probably better with attributes...went with quick and dirty. Also trace Url.PathAndQuery for debugging here.
Any data access actions that I would use across views with ajax, like loading up a list of departments.
OnException is overridden, as well.
That's what I got in mine so far.
In my base controllers I actually put some utility method ([NonAction]) collected over time. I prefer to add functionalities to Controllers by decorating with Attributes if possible.
Lately my base controller has:
some Properties for retrieving information about the current user (my app
specific informations, not the User.Identity stuffs)
A simple protected override void OnException(ExceptionContext
filterContext); override for at least logging unhandled exception and have
some sort of automatic notifications
A bunch of Cookies related methods (WebForms auth cookies management
for example)
A bunch of usefull standard attributes (usually [Authorize], [HandleError], [OutputCache]) in its declaration.
some standard method for preparing widely used json data types on the fly (when possible I prefer to have a standard json object with ErrorCode, ErrorMessage and a UserData).
With time you'll find more and more utilities to keep with your controllers, try to keep an assembly with the simpler ones (avoiding heavy dependencies), will come handy with your next MVC projects. (the same goes for Helpers and to some degree also for EditorTemplates).
For the Authorize Attribute part, well, I think the cleanest way is to write your own AuthorizeAttribute class, specifically a NonAuthorizeAttribute. I think I've also seen it somewhere on SO.
You can also play with the Order Property of the default AuthorizeAttribute - put different Order in BaseController and in Action, in order to have Action's one executed first, but I cannot recall if you can actually break the Attributes processing chain.
Regards,
M.
We cant tell you what you need in your base controller, you have to reveal these kind of thing as you implement your controllers and see repeating code.. Dont hesitate to refactor these things to your BaseController, and keep in mind, that maybe you should have 2 or more BaseControllers, or 2-layer hierarchy of BaseControllers.
I give you two tips, what i always have in my BaseController :
super-useful helper method for interface-based model binding :
protected T Bind<T, U>()
where T : U, new()
where U : class
{
T model = new T();
TryUpdateModel<U>(model);
return model;
}
You can then have multiple "sets" of properties you want to bind in different scenarios implemented as interfaces, and simple model bind your object (even existing object, from DB) with incoming values.
2.If you use custom AcionResults (maybe your specific Json builders etc.), make your "shortcuts" methods in BaseController. Same thing as View() method is shortcut for return new ViewResult(...)
To add more to the good responses already here -
caching caching caching caching
See
Disable browser cache for entire ASP.NET website

The MVC Snake - What do these other stages such as 'ViewFactory' mean?

First check the slide that is referenced here: http://weblogs.asp.net/leftslipper/archive/2007/12/10/asp-net-mvc-design-philosophy.aspx
Since I have been using ASP.NET MVC I have in my mind conceptually been aware of the 'URL Routing', 'Controller', and 'View' stages that are shown here...
But what is meant by all the other stages? Can anyone give a synopsis of them? Especially the ViewFactory, what the heck is that and am I suppose to be using it? Right now my Controller just returns Views...
The View Factory (AKA View Engine) is what actually creates the view classes that process the markup you write. If you want to replace the default MVC Views with something like Spark or NHaml then this is the stage you need to change/intercept.
An HTTP handler lets you intercept messages at the protocol level before the request really hits your "application". For example you might plug in a custom error handler for certain response codes. Or you might plug in a special HTTP handler for media you host like images and movies, to prevent other sites from hot-linking.
The MVC Route Handler itself is an HTTP handler; it "handles" HTTP requests by creating the Controller class.
The last piece is the Route which I think is pretty self-explanatory.

Resources