Struts2: Why to extend ActionSupport class? - struts2

I am a beginner to Struts2. Please tell me why to extend ActionSupport class? (When one doesn't have the requirement of validation or internationalization)
Are there any other benefits provided by extending ActionSupport class?

Convenience and access to basic, common functionality.
It has default implementations of common methods (e.g., execute(), input()), gives access to Action.SUCCESS and other result names, etc.
Note that the I18N functionality goes a bit beyond simple translation, but includes some formatting, allows non-programmers to provide labels/texts, and so on.
There's rarely (ever?) a good reason not to extend it. Even REST plugin actions, e.g., those that handle JSON endpoints, often use validation and I18N support.

IF you don't want to use out of the box features provided by the struts2 you can always avoid using ActionSupport class
This is basically a helper class which provides many out of the box features for you, but at same time Struts2 framework do not ask to use this class, all it want is an entry method for your action class with return type as String and which can throw a general Exception
beside validation or Internationalization this class also provides many other features like Action level Errors etc.
Follow the documentation for detail
ActionSupport

Related

Which interface/abstract class is for grails Domain class behaviour?

I have a generic method for doing a common operation on many domain class
static Map getNumberOfPropertyByTopicIds(def criteriaClass, List ids) {
criteriaClass.createCriteria(). //Some GORM methods used
}
I wanted autocomplete on various things applied on criteriaClass. But for doing that I need to replace def criteriaClass to InterfaceForDomainClassBehaviour criteriaClass.
But I don't know InterfaceForDomainClassBehaviour is what. Which interface/abstract class implements Domain class behaviour?
There isn't one.
Grails uses "convention over configuration", so unlike other frameworks where you extend a base class, implement one or more interfaces, use annotations, etc., you simply put your artifact classes (domain classes, services, etc.) in the correct directory under grails-app, use the appropriate class naming convention (except for domain classes), and Grails mixes in behavior for you. You can configure things of course, e.g. with the mapping block, etc.
Before Grails 2 adding methods was mostly done using Groovy runtime metaprogramming, and in Grails 2 most of the behavior is added at compile time using ASTs, and runtime metaprogramming is used mostly for dynamic code like findAllByHeightAndWeightAndHairColorAndShoeSize where it would be impractical and/or impossible to compile in every combination.
Over 100 methods are added to domain classes (decompile some - it's pretty amazing to see how much ends up in your classes considering how small the Groovy source is) and dozens are added to controllers. But this is all mixed in, so although there is significant overlap between your domain classes, there's no common base class or interface unless you add them yourself.

Access Properties from utility classes used by Action

I just want to know if there's a way to access the properties from a utility class used by an Action class. To access the properties from an Action class we extend the ActionSupport and use the getText("property.key.name") method.
So, my question is -should every other class extend the ActionSupport to access properties, even though its not an Action class? or is there any other way?
Thanks
I wouldn't extend ActionSupport unless you're actually defining an action.
The S2/XW2 ActionSupport class uses com.opensymphony.xwork2.DefaultTextProvider; you might be able to use it in your own classes. I'm a little wary of this since I'm not convinced non-action classes should be accessing the web-app's resources, but I haven't given it much thought, so it could be valid. I also haven't tried to do it.
ActionSuport is kind of helper class being developed by S2 developers to supplement the Development as it provides many features OOTB.
getText() is one of the use-case where S2 provides a way to read the property files.This method is specific to S2 as it know how to transverse the hierarchy to read the property files and in what order.
There are many ways to read the property files in a application and few of them are
ResourceBundle
if you are using Spring, it has a very handy mechanism to read property files
- how-to-read-properties-file-in-spring
Apache Common also provides a way to read the file
Apache-Common
In short to read properties file there are many ways, S2 getText() is a way developed by the S2 to read the property file with respect to your actions.
//I wanna make you understand how struts doing it.
public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {
//Action support implementation.
//Here TextProvider takes care about resource bundle thing.
}

Rails: what are the main reasons for making methods private?

If the end_user cannot access the source code of the app, why we still need to make some methods private?
I'm reading the Pragmatic Agile Web Development with Rails and I couldn't understand why we need to make the following method private (even after reading the explanation):
private
def current_cart Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
end
It says that it will never allow Rails to make it available as an action, but as a coder, why would I ever do that myself?
As you say there may be no external reason to make it private. However, it also prevents you — or somebody else using your code — from accidentally making use of the method where you're not supposed to.
See it as a sanity check on your own future behaviour if you will.
It aims to encourage good practices and good code.
The idea is that you have two separate parts to your code:
"Above the line" (Public). This is the interface to the rest of the world. This is the API, where calls are made when using instances of the object. Once created, you know that THIS is the area where changes can affect current usages of the code.
"Below the line (Private). This is where detailed logic resides. This code can be changed and refactored freely without any affect to the public interface.
It may help guide your test writing
Private methods may or may not be (unit) tested.
Public methods are more encouraging of both unit and integrated tests as the fact that is is public means that it is serving as the public face for that code and as it is public it might be called from any other point in the future, so having good tests to make sure it continues to work as advertised is essential.
It may help with security as you have greater control who calls private methods (i.e. only public methods in the same class calling them).
It may help reduce name collisions as you have less names in the public space.
End user might not be able to access your code but someone else in your team can definitely access it and they might change it.
The other benefit of encapsulation is that it allows one class ("server") to make a contract with another class ("client") to provide some service with only a very few things being required to be known about the "server" class such as method signature and return type. The benefit is only realized if the contract of what is required and what is returned remains the same. So, in your example, there is no benefit since the contract was broken by Class A.
Instead of class A changing int type to float, class A should create another new variable of type float for other classes to use so that class B is not "broken" or that contract is not broken between them. Class C could refer to new float variable and Class B could still refer to old int variable and everyone is happy. Better yet, methods would used to retrieve values such as: "getUsersAddress" and "getUSersPhoneNumber" depending on what was wanted.
The real benefit of good encapsulation is that Class A can be completely re-written from top to bottom and as long as the contract is honored as to what Class A is expected to do(have methods "getUsersAddress" and "getUSersPhoneNumber"), then everything in Class B and C works the same. Think carefully about what is exposed and how it is exposed. Things that will change often and break other classes need to be considered carefully before exposing. Good encapsulation means hiding things that are expected to change often so to avoid breaking other classes.
It says that it will never allow Rails to make it available as an action,
Hmm, is this in a Rails Conroller class? And is the book you are working through written for Rails 2.x?
In Rails 2.x, by default any public method in a Controller can be triggered by someone accessing the url /name_of_controller/name_of_method .
But there are some methods in your controller that you don't want anyone on the web to trigger, they weren't intended as 'action methods'. So in Rails 2.x, you mark those as protected or private, something not public. "action method" means a method you intend to be directly triggered via a URL.
In Rails 3.x, routing has generally changed such that only certain methods you explicitly route to are available to be triggered via a URL. However, it might still make sense to mark non-action-methods in a Controller as protected or private so:
It's more clear from skimming the source which methods are action methods and which aren't
As a precaution in case someone changes the routing in such a way that would allow a URL to trigger those methods not intended as action methods
Or for general reasons of code organization that other answers mention, that are not specific to Rails controller classes.
There are several reasons as mentioned above. The interesting thing about this encapsulation in ruby is that it can be violated.
See the "send" method and its brother "public_send".
And for a very common metaprogramming technique that uses this method see:
dynamic finders

Is it possible to extend the User.Identity structure (ASP.Net/MVC) somehow?

Is it possible to store additional data specific to the currently logged on user somehow?
Certainly! If you are not familiar with writing an extension, there are the VB.NET and C# guides on the subject.
You will need to extend the System.Security.Principal.IIdentity interface. As an example:
Declaration:
Imports System.Runtime.CompilerServices
Module Extensions
<Extension()>
Function GetMyCustomProperty(anIdentity As System.Security.Principal.IIdentity, myParameter As Integer) As Object
Return New Object()
End Function
End Module
Usage:
User.Identity.GetMyCustomProperty(4)
NOTES:
The C# code is a fair deal different so it's worth looking at the
guides on how extensions are implemented in general. Running this
code through a VB.NET => C# converter is not enough.
Extensions may only be methods. You may not program custom properties. This will likely mean implementing getter/setter methods if you want property-like behavior.
EDIT:
After seeing your comments, I assume you are doing this to provide a sort of crude functionality similar to a user profile. Consider using a profile provider in concert with any membership you are currently using if you'd like this functionality.

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