I am getting two different instances of same bean when scope is different in property bean (request scope) in spring xml file - spring-mvc

I have a bean let say MyRequestBean whose scope is defined as "request" in spring xml file.
This bean is added as a property in another spring bean let say MyConversationBean whose scope is defined as "conversation".
<bean id="myRequestBean"
class="com.systemx.ui.request.view.MyRequestBean"
scope="request" parent="UIController"/>
<bean id="myConversationBean"
class="com.systemx.ui.conversation.view.MyConversationBean"
scope="conversation" init-method="initialise">
<property name="myRequestBean" ref="myRequestBean" />
myConversationBean is initialised with an instance of myRequestBean. But on a user action there's a method in myConversationBean which gets invoked and the instance of myRequestBean is used to set value in myRequestBean fields but when this method finished the user is redirected to detail page where I find different instance of myRequestBean which doesn't contain the value previously set on user action. This instance is what it had been intially when http request was made.
This works when I change the myRequestBean scope to "conversation".
My question is I have two different instances when I check the version of bean why? is there a way to set value in request scope bean instance?
I did a work around when the control flows to detail page then I access the instance of myRequestBean and set value in fields and it did work but this isn't a good fix.

Related

What is the complete lifecycle of an OData controller http request in WebApi 2

I wonder what is the full lifecycle of an odata http request over an ODataController hosted in IIS.
For instance:
What are the IIS pipelining steps ?
How is the request handled when entering the ASP.NET controllers area ?
When routing is applied ?
When the Attributes such HttpPost, ApplyFilter are applied ?
Maybe this thread can help you:
The ASP.NET Web API 2 HTTP Message Lifecycle in 43 Easy Steps
It all starts with IIS:
IIS (or OWIN self-hosting) receives a request.
The request is then passed to an instance of HttpServer.
HttpServer is responsible for dispatching HttpRequestMessage objects.
HttpRequestMessage provides strongly-typed access to the request.
If one or more global instances of DelegatingHandler exist on the pipeline, the request is passed to it. The request arrives at the instances of DelegatingHandler in the order said instances were added to the pipeline.
DelegatingHandler instances can skip the remainder of the pipeline and create their own response. I do exactly this in my Custom Validation with FluentValidation post.
If the HttpRequestMessage passes the DelegatingHandler instances (or no such handler exists), then the request proceeds to the HttpRoutingDispatcher instance.
HttpRoutingDispatcher chooses which routing handler to call based on the matching route. If no such route exists (e.g. Route.Handler is null, as seen in the diagram) then the request proceeds directly to Step 10.
If a Route Handler exists for the given route, the HttpRequestMessage is sent to that handler.
It is possible to have instances of DelegatingHandler attached to individual routes. If such handlers exist, the request goes to them (in the order they were added to the pipeline).
An instance of HttpMessageHandler then handles the request. If you provide a custom HttpMessageHandler, said handler can optionally return the request to the "main" path or to a custom end point.
The request is received by an instance of HttpControllerDispatcher, which will route the request to the appropriate route as determined by the request's URL.
The HttpControllerDispatcher selects the appropriate controller to route the request to.
An instance of IHttpControllerSelector selects the appropriate HttpControllerDescriptor for the given HttpMessage.
The IHttpControllerSelector calls an instance of IHttpControllerTypeResolver, which will finally call...
an instance of IAssembliesResolver, which ultimately selects the appropriate controller and returns it to the HttpControllerDispatcher from Step 11.
NOTE: If you implement Dependency Injection, the IAssembliesResolver will be replaced by whatever container you register.
Once the HttpControllerDispatcher has a reference to the appropriate controller, it calls the Create() method on an IHttpControllerActivator...
which creates the actual controller and returns it to the Dispatcher. The dispatcher then sends the request into the Select Controller Action routine, as shown below.
We now have an instance of ApiController which represents the actual controller class the request is routed to. Said instance calls the SelectAction() method on IHttpActionSelector...
Which returns an instance of HttpActionDescriptor representing the action that needs to be called.
Once the pipeline has determined which action to route the request to, it executes any Authentication Filters which are inserted into the pipeline (either globally or local to the invoked action).
These filters allow you to authenticate requests to either individual actions, entire controllers, or globally throughout the application. Any filters which exist are executed in the order they are added to the pipeline (global filters first, then controller-level filters, then action-level filters).
The request then proceeds to the [Authorization Filters] layer, where any Authorization Filters which exist are applied to the request.
Authorization Filters can optionally create their own response and send that back, rather than allowing the request to proceed through the pipeline. These filters are applied in the same manner as Authentication Filters (globally, controller-level, action-level). Note that Authorization Filters can only be used on the Request, not the Response, as it is assumed that if a Response exists, the user had the authorization to generate it.
The request now enters the Model Binding process, which is shown in the next part of the main poster. Each parameter needed by the action can be bound to its value by one of three separate paths. Which path the binding system uses depends on where the value needed exists within the request.
If data needed for an action parameter value exists in the entity body, Web API reads the body of the request; an instance of FormatterParameterBinding will invoke the appropriate formatter classes...
which bind the values to a media type (using MediaTypeFormatter)...
which results in a new complex type.
If data needed for a parameter value exists in the URL or query string, said URL is passed into an instance of IModelBinder, which uses an IValueProvider to map values to a model (see Phil Haack's post about this topic for more info)....
which results in a simple type.
If a custom HttpParameterBinding exists, the system uses that custom binding to build the value...
which results in any kind (simple or complex) of object being mappable (see Mike Stall's wonderful series on this topic).
Now that the request is bound to a model, it is passed through any Action Filters which may exist in the pipeline (either globally or just for the action being invoked).
Once the action filters are passed, the action itself is invoked, and the system waits for a response from it.
If the action produces an exception AND an exception filter exists, the exception filter receives and processes the exception.
If no exception occurred, the action produces an instance of HttpResponseMessage by running the Result Conversion subroutine, shown in the next screenshot.
If the return type is already an HttpResponseMessage, we don't need to do any conversion, so pass the return on through.
If the return type is void, .NET will return an HttpResponseMessage with the status 204 No Content.
If the return type is an IHttpActionResult, call the method ExecuteAsync to create an HttpResponseMessage.
In any Web API method in which you use return Ok(); or return BadRequest(); or something similar, that return statement follows this process, rather than any of the other processes, since the return type of those actions is IHttpActionResult.
For all other types, .NET will create an HttpResponseMessage and place the serialized value of the return in the body of that message.
Once the HttpResponseMessage has been created, return it to the main pipeline.
Pass the newly-created HttpResponseMessage through any AuthenticationFilters which may exist.
The HttpResponseMessage flows through the HttpControllerDispatcher, which at this point probably won't do anything with it.
The Response also flows through the HttpRoutingDispatcher, which again won't do anything with it.
The Response now proceeds through any DelegatingHandlers that are set up to handle it. At this point, the DelegatingHandler objects can really only change the response being sent (e.g. intercept certain responses and change to the appropriate HTTP status).
The final HttpResponseMessage is given to the HttpServer instance.
which returns an Http response to the invoking client
Looking at the source code ,ODataController is another controller which is inherited from
ApiController with custom routing and formatting. So I guess all the logic applied for ApiController
applies to that as well.It also has Custom Formatting and Custom Routing applies using ODataFormatting and ODataRouting
What are the IIS pipelining steps ?
IIS pipelining steps are same like any other mvc controller .In essense,we have all the httpmodules and handlers which forms the pipeline.More details can be found asp.net application lifecycle. From this pieline,when an mvc request comes URLRoutingModule,MvcRouteHandler and Mvchandler works in tandem to serve an MVC request. Explained detailed for the next question.
How is the request handled when entering the ASP.NET controllers area ? When is routing applied ?
Everything starts with an ODataController .Almost everything in MVC is extensible(13 extensibility points in asp.net mvc) you name it and all those points are extended for OData. e.g Starting with Custom Controllers,we have
custom ODataActionSelector which is from IHttpActionSelector .You can find a sample implementation here
IActionValueBinder ,sample implementation here
IContentNegotiator
etc like this many more.
/// Defines a base class for OData controllers that support writing and reading data using the OData formats
/// </summary>
[ODataFormatting]
[ODataRouting]
[ApiExplorerSettings(IgnoreApi = true)]
public abstract class ODataController : ApiController
Receive first request for the application -> In the Global.asax file, Route objects are added to the RouteTable object.
Perform routing -> The UrlRoutingModule module uses the first matching Route object in the RouteTable collection .From ODataRouting, The routes are added to RouteTable collection.
Create MVC request handler -> The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler
Create controller -> The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object to create the controller instance with
Execute controller -> The MvcHandler instance calls the controller's Execute method
Invoke action -> For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method
7.Action returns all custom CreatedODataResult,UpdatedODataResult etc
There are Custom ODataMediaTypeFormatter registered for ODATA to format the data.

How to pass an Object from a Servlet to JSR-356 WebSocket

I have a JSP-type servlet that registers a WebSocket Endpoint with the Servlet container.
I want to pass a reference of that servlet, and/or some of its objects, to the WebSocket Endpoint, so that I can use the code from that servlet, e.g. for Authentication or Session management (the servlet has its own non-Java EE Session management).
I was hoping that I could set some attribute somewhere when I call addEndpoint() on ServerContainer, because at that point I have access to the objects that I want to use later, but none of the classes that I've seen at that point have an attribute collection, e.g.
objectThatWillBeAvailableAtWebSocket.addAttribute("some.custom.object", someObject);
By the time my code reaches an ServletRequestListener, ServerEndpointConfig.Configurator, or the registered Endpoint, I do not have any reference to the original servlet that added the Endpoint.
How can I pass an Object to the WebSocket servlet? I'm running my test code in Embedded Jetty, but I'm aiming for Container-agnostic code.

Role of servlet context,set attribute and request dispatcher in servlets program

ServletContext sc=getServletContext();
sc.setAttribute("UserName", str1);
what is the role of these codes in servlets.
Based on your code
ServletContext sc=getServletContext();
sc.setAttribute("UserName", str1);
This is to set the value of str1 to the "UserName" attribute and the value can be used in the entire application in servlets or JSP's wherever needed.Setting the attribute to the context makes sure that the attribute value is available and accessible in the entire application

How do you create CouchDB Views using Spring Bean Deployment with LightCouch

I am using Spring-MVC LightCouch and CouchDB and I have custom Views that need to be inserted into the DB on deployment. I have found the LightCouch has a method for pulling documents "from desk" as noted on their website:
DesignDocument designDoc = dbClient.design().getFromDesk("example");
Response response = dbClient.design().synchronizeWithDb(designDoc);
This Works good from within JAVA code, however I need to be able to do it in the Spring ApplicationContext.xml I have more than one so I would like to mimick the call of:
dbClient.dessign().synchronizeAllWithDB()
How would I do this in the bean definition of the ApplicationContext I already have this:
<bean id="dbClient" class="org.lightcouch.CouchDbClient" lazy-init="false" destroy- method="shutdown">
<constructor-arg value="couchdb.properties" />
</bean>
It seems you can't do it with Spring xml config, as the init method falls under a different instance; that is returned by the call to design() factory method. Maybe you can try Java code equivalence, i.e. #PostConstruct.
I ended up having to make a bean that synchronized the database on init and created that when the app starts

When, exactly, #Inject annotation initiates injection of SessionScoped bean in Servlet?

I need to modify a user session object (SessionScoped bean - CDI) in a Servlet, so I have to obtain that bean somehow. I used injection in the following way:
#Inject
private UserSession user;
where UserSession is the SessionScoped CDI bean. user methods are called from either doPost or doGet servlet methods.
This works perfectly; every time the #Inject annotation injects the appropriate UserSession bean, but I don't understand how this behavior is achieved.
I assumed that the beans, annotated with #Inject, are injected only once (when the object - Servlet instance in this case - is created), but it is obviously a wrong presumption.
So, when are these beans injected into the servlet? Per request? And how does this approach avoids conflicts (one servlet instance - multiple threads to deal with it) when there are multiple UserSession objects?
The CDI uses the proxy pattern. The injected instance is actually not the real instance, but a proxy which locates the real instance depending on the current context and delegates all methods to it (like as how EJBs work). The autogenerated class of your UserSession bean looks roughly like this:
public UserSessionCDIProxy extends UserSession implements Serializable {
public String getSomeProperty() {
UserSession instance = CDI.resolveItSomehow();
return instance.getSomeProperty();
}
public void setSomeProperty(String someProperty) {
UserSession instance = CDI.resolveItSomehow();
instance.setSomeProperty(someProperty);
}
}
This mechanism allows you to inject instances of a narrower scope in instances of a broader scope and allows you to still get the expected instance in the current context. The standard JSF #ManagedProperty annotation doesn't support it, simply because it does not use a proxy, but injects the desired instance directly. That's why it's not possible to inject something of a narrower scope by #ManagedProperty.
See also:
Backing beans (#ManagedBean) or CDI Beans (#Named)?
Get JSF managed bean by name in any Servlet related class
When using #EJB, does each managed bean get its own #EJB instance?
How to choose the right bean scope?
Your answer lies in the C of CDI, which stands for Contexts.
What happens is that not the actual bean is injected, but a proxy. This proxy is contextual and resolves to the actual session scoped bean depending on the context of the caller on who's behalf the proxy is executed.

Resources