What happed if some one make an object of the action class in another class in struts 2? - struts2

In our code new freshers had made object of the action classes and used the methods.
How system affected if action class object used throughout the system.

There's nothing special about an S2 action class.
Turn this question around: since you're (apparently) not a "fresher", what do you think happens when a class is instantiated? How do you think S2 process a request? (Hint: it instantiates an action class, which is then eventually used to process the request.) How might an instantiated class, given that an S2 action can be a POJO, affect the rest of the system?
All this said:
From an architectural standpoint this is a bad idea, because logic used across classes should be properly extracted into a service/utility/etc. class and not tied up with a specific action.
It's also confusing from a cognitive load viewpoint: there's no reason to expect mainline code to manually instantiate an action--actions are instantiated by the framework for the sole purpose of processing requests.

Related

Getting Injectee from Jersey vs HK2

Short story: I want to get the Injectee from within a Supplier that is bound using Jersey's AbstractBinder.bindFactory(Class) method.
Basically to work around JERSEY-3675
Long story: I was using the org.glassfish.hk2.api.Factory method to create an instance of my RequestScoped Object and life was good.
I moved my registration into a Feature and then life was not good because of JERSEY-3675.
Long story short, org.glassfish.hk2.utilities.binding.AbstractBinder do not work inside Features. No problem, I thought, I will use org.glassfish.jersey.internal.inject.AbstractBinder.
Slight problem I encountered: Jersey's AbstractBinder.bindFactory() method takes in Supplier not Factory. No problem, I thought, I will use Supplier (I like it better, anyway).
Bigger problem I encountered: I had been using org.glassfish.hk2.api.Injectee to get the InstantiationData about who was calling the injection. This does not get injected if I do not use HK2's Factory. The javadoc even says the method is 'indeterminate' if not called from Factory.provide().
Even though there is a Jersey Injectee (org.glassfish.jersey.internal.inject.Injectee), this seems to only be available when using Jersey's InjectionResolver. I do not want to use InjectionResolver because
HK2's InjectionResolver must be Singleton but I want to have RequestScoped stuff in my injected object.
On second read, though, Jersey's InjectionResolver does not say anything about needing to be Singleton. Can anyone confirm?
I do not want to create my own annotation for this (I have created my own annotations and InjectionResolvers for other cases)
I do not feel confident overriding #Inject with an InjectionResolver. Not sure what that means or how I would be able to register multiple of those and have them work together (one for each Feature)
In meantime, I am using the workaround mentioned in the bug.
I am new to DI scene, so if something (or all of it) does not make sense, please let me know.

Declaring DbContext for an MVC controller

Looking at some of the MVC examples online, I've see that typically in a controller the DbContext variable is declared as a private member variable (i.e. global) and accessible to all the methods.
But, I recently came across an article on ASP.NET Identity, and noticed in the controller, the DbContext is declared within each method (that requires it).
Is there a security benefit to this approach? Perhaps limit the lifespan of the security object(s) for better overall security?!?!
If not, then I see the first approach being more efficient, where the database context is instantiated upon the controller loading.
Below is all I could find about DbContext, but nothing to really answer my question.
DbContext declaration - Framework 4.1 - MVC 3.0
MVC, DbContext and Multithreading
On every request, a new instance of the controller is constructed. Therefore, for all intents and purposes, it does not really matter whether the dbcontext is instantiated in the constructor vs encapsulated in any given method.
Aside from a style choice, reasons to declare and contain a dbcontext in a given method is that:
Methods that do not need it will not instantiate the context, eliminating the overhead (if there is any). This can also be accomplished using a lazy initialization pattern.
The context is disposed of immediately as soon as a method is done with it, rather than at the end of the request. Generally this should not be a concern though; usually if users are waiting around for longer than a few seconds you have a bigger problem.
Different methods use different contexts.
Among others, some reasons to declare a single context and instantiate it once:
You have only one place that instantiates a context rather than many. In a typical application, most pages will need some information from the database anyway.
Methods that call other methods will not each hold on to their own instance of a context object.
You can create a base controller class that by default creates a dbcontext object, allowing you to be DRY in all inherited controllers.
Answer from #Ic. is pretty good. I wanted to add that if you need to pass information from your Request into your DbContext constructor then you need to create the instance of your DbContext inside your action methods. The reason is the Request object will be null till the control enters your action method.
More information: I had a need to build connection string dynamically depending on the location of the user. I saved the location as a cookie that I accessed through Request object. I had a valid Request inside the action method but it was null inside the constructor or at the class level properties of the controller.

Where to put needed initialization code when using Dependency Injection?

When my constructors are pure arguments-to-propeties setters then I'm not sure where to put other code that a class needs to properly work.
For example in JavaScript I'm programming a WindowMessageController that processes message events on the window object.
In order for this to work, I must somewhere attach the handler:
var controller = this;
this.applicableWindow.addEventListener("message", function(event) {
controller.messageAction(event.data);
}
Where does this stuff correctly belongs?
in the constructor
in the .initialize() method - introduces temporal coupling
in the WindowMessageControllerFactory.create(applicableWindow) - quite a distant place for so central piece of code. This means that even such a small class would be split into two pieces.
in the composition root itself - this would multiply its size when doing all the time
in some other class WindowMessageRouter that would have only one method, the constructor, with this code
EDIT
This case seems special because there is usually only one instance of such a controller in an app. However in more generalized case what would be the answer if I was creating an instances of Button class that would wrap over some DOM <button /> element? Suddeny a
button = buttonFactory.create(domButtonEl);
seems much more useful.
Do not put any real work into constructors. Constructors are hardly mockable. Remember, seams aka methods are mockable. Constructor are not mockable because inheritance and mocking.
Initialize is a forbidden word, to much general.
Maybe, but you can implement factory as a static method of class too, if you are scared of many classes ,)
Composition root is just an ordinary factory. Except it is only one, because your app probably have just one entry point ,)
Common, we are using Javascript. If you need just one factory method, why you need class for it? Remember, functions are first class objects.
And for edit. There is nothing special on singetons, unless they do NOT control own lifecycle.
Golden rule: Always (almost ,) do separation between app wiring and app logic. Factories are wiring. Just wiring, no logic, therefore nothing to test.
I would place this code into initialize(window) method but this method cannot be part of WindowMessageController's public API - it must be visible and called by direct users (so composition root and tests) only.
So when DI container is returning WindowMessageController instance then it is container's responsibility that initialize method has been called.
Reply to EDIT: Yes, this factory seems to be the best way for me. Btw. don't forget that the factory should probably have a dispose method (i.e. unbinds the event handler in case of button)...
I think you need to create a Router class that will be responsible for events distribution. This Router should subscribe to all the events and distribute them among the controllers. It can use some kind of the message-controller map, injected into constructor.

Why there is no Singleton concept for Action class in Struts2?

I was going through differences of Struts1 vs Struts2, and came across this point:
Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action.
Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
Now my question is: in Struts2, why there are no singleton concept for Action class? As I think because, unnecessarily, there is more Object creation for every request.
Please correct me if I am wrong.
Object creation is ridiculously fast in Java. Programming thread-safe action classes (and servlets, etc.) is irritating and error-prone.
Like with everything, there's a trade-off.
New instance in the sense, its not creating new object but jvm will create instance of that object hence there is no matter that how many request is comming for a particular object...even if the instance is more, the applcation will not hang...

What are good candidates for base controller class in ASP.NET MVC?

I've seen a lot of people talk about using base controllers in their ASP.NET MVC projects. The typical examples I've seen do this for logging or maybe CRUD scaffolding. What are some other good uses of a base controller class?
There are no good uses of a base controller class.
Now hear me out.
Asp.Net MVC, especially MVC 3 has tons of extensibility hooks that provide a more decoupled way to add functionality to all controllers. Since your controllers classes are very important and central to an application its really important to keep them light, agile and loosely coupled to everything else.
Logging infrastructure belongs in a
constructor and should be injected
via a DI framework.
CRUD scaffolding should be handled by
code generation or a custom
ModelMetadata provider.
Global exception handling should be
handled by an custom ActionInvoker.
Global view data and authorization
should be handled by action filters.
Even easier with Global action filters
in MVC3.
Constants can go in another class/file called ApplicationConstants or something.
Base Controllers are usually used by inexperienced MVC devs who don't know all the different extensibility pieces of MVC. Now don't get me wrong, I'm not judging and work with people who use them for all the wrong reasons. Its just experience that provides you with more tools to solve common problems.
I'm almost positive there isn't a single problem you can't solve with another extensibility hook than a base controller class. Don't take on the the tightest form of coupling ( inheritance ) unless there is a significant productivity reason and you don't violate Liskov. I'd much rather take the < 1 second to type out a property 20 times across my controllers like public ILogger Logger { get; set; } than introduce a tight coupling which affects the application in much more significant ways.
Even something like a userId or a multitenant key can go in a ControllerFactory instead of a base controller. The coupling cost of a base controller class is just not worth it.
I like to use base controller for the authorization.
Instead of decorating each action with "Authorize" attribute, I do authorization in the base controller. Authorized actions list is fetched from database for the logged in user.
please read below link for more information about authorization.
Good practice to do common authorization in a custom controller factory?
I use it for accessing the session, application data etc.
I also have an application object which holds things like the app name etc and i access that from the base class
Essentially i use it for things i repeat a lot
Oh, i should mention i don't use it for buisiness logic or database access. Constants are a pretty good bet for a base class too i guess.
I have used base controller in many of my projects and worked fantastic. I mostly used for
Exception logging
Notification (success, error, adding..)
Invoking HTTP404 error handling
From my experience most of the logic you'd want to put in a base controller would ideally go into an action filter. Action Filter's can only be initialized with constants, so in some cases you just can't do that. In some cases you need the action to apply to every action method in the system, in which case it may just make more sense to put your logic in a base as opposed to annotating every action method with a new actionFilter attribute.
I've also found it helpful to put properties referencing services (which are otherwise decoupled from the controller) into the base, making them easy to access and initialized consistently.
What i did was to use a generic controller base class to handle:
I created BaseCRUDController<Key,Model> which required a ICRUDService<TModel> object as constructor parameter so the base class will handle Create / Edit / Delete. and sure in virtual mode to handle in custom situations
The ICRUDService<TModel> has methods like Save / Update / Delete / Find / ResetChache /... and i implement it for each repository I create so i can add more functionality to it.
using this structure i could add some general functionality like PagedList / AutoComplete / ResetCache / IncOrder&DecOrder (if the model is IOrderable)
Error / Notification messages handling: a part in Layout with #TempData["MHError"] code and a Property in base Controller like
public Notification Error
{
set { TempData["MHError"] = value; }
get { return (Notification) TempData.Peek("MHError"); }
}
With this Abstract classes i could easily handle methods i had to write each time or create with Code Generator.
But this approach has it's weakness too.
We use the BaseController for two things:
Attributes that should be applied to all Controllers.
An override of Redirect, which protects against open redirection attacks by checking that the redirect URL is a local URL. That way all Controllers that call Redirect are protected.
I'm using a base controller now for internationalization using the i18N library. It provides a method I can use to localize any strings within the controller.
Filter is not thread safe, the condition of database accessing and dependency injection, database connections might be closed by other thread when using it.
We used base controller:
to override the .User property because we use our own User object that should have our own custom properties.
to add global OnActionExecuted logic and add some global action-filters

Resources