Difference between the Action Context and ServletActionContext - struts2

Hi I have Question we can use both Action Context and Servlet Action Context to access the resources But why Struts2 people implemented two if they work same

They don't work the same; one has web-app-specific functionality.
XWork is not a web app framework--hence the ActionContext. WebWork/Struts 2 added web-specific functionality, hence ServletActionContext, which is a subclass of ActionContext, and adds web-related stuff.

As quoted in:
Servlet Action Description
Servlet Action Context is a sub class of Action Context.
"ServletActionContext is Web-specific context information for actions".This class adds access to web objects like servlet parameters, request attributes and things like the HTTP session. In simple terms one can say Action Context is generic while the servlet action context is more specific in terms of its usage
For Example: GenericServlet and HttpServlet; GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets etc. while HttpServlet is more specific.

Related

What is the role of the action mapper in Struts 2?

Can somebody explain the role of the Action Mapper in Struts 2?
The role of ActionMapper interface in Struts2 framework is to extract mapping from the request's URL.
When given an HttpServletRequest, the ActionMapper may return null if no action invocation request matches, or it may return an ActionMapping class that describes an action invocation for the framework to try.
You can read more about this feature here.
Th first method returns a mapping to try, it doesn't guarantee that this action will be executed.
The ActionMapping returned by the action mapper contains all necessary information to invoke an action if there's an action config corresponding to this mapping is available in runtime configuration.
Different implementation of this interface can be used to override the default behavior for mapping URLs to actions in Struts2.

Scopes of ActionMapper, ActionProxy, ActionInvocation, ActionContext objects in Struts2?

Can any one please describe me when the objects of ActionMapper, ActionProxy, ActionInvocation, ActionContext are created in a Struts2 application. As I am new to Struts2 framework, I am very much confused about the scopes of these objects.
The ActionMapper is created on startup, it has a singleton scope.
The ActionContext is created by the Dispatcher in preparing an action to execute, it's ThreadLocal, and it doesn't have any scope.
When action is executing the ActionInvocation and ActionProxy are created that also don't have a scope.
You can see this on a big picture of Struts2 architecture.

What is the difference between FacesContext and ExternalContext

What is the difference between FacesContext and ExternalContext? When can I use one or other? What has the one and what has the other?
The following sample is from the book JavaServer Faces 3rd edition:
<h:commandButton ... actionListener="#{rushmore.handleMouseClick}" />
Backing bean:
public void handleMouseClick(ActionEvent e) {
FacesContext context = FacesContext.getCurrentInstance();
String clientId = e.getComponent().getClientId(context);
Map<String, String> requestParams = context.getExternalContext().getRequestParameterMap();
// ...
}
Why is request parameter in ExternalContext? What is clientId? Is it generated by JSF when the application is started?
Carefully look in their javadocs to see what methods they offer and what exactly those methods all do.
FacesContext javadoc
ExternalContext javadoc
If you look closer at those methods listed in the javadoc, you'll notice that the FacesContext generally offers access to JSF-specific artifacts which are further in no way related to the "underlying" Servlet or Portlet API for which JSF is been designed to run on top of. E.g. creating converters, validators, components, EL expressions, etcetera and obtaining information about view root, supported locales, etcetera and adding phase listeners, system event listeners, etcetera. Everything which is specific to JSF API.
And, ExternalContext generally offers access to Servlet or Portlet-specific artifacts which JSF is currently using "under the covers". E.g., when running on a Servlet container, the HTTP servlet request, HTTP servlet response, HTTP session and Servlet context and inherently also all of their artifacts. Click those links, you'll see that they in turn offer methods which are also been delegated by the ExternalContext, such as getRequestParameterMap(). See also the javadoc. Yes, also click that link, you'll see that it explicitly mentions the servlet request:
Servlet: This must be the set of parameters available via the javax.servlet.ServletRequest methods getParameter() and getParameterNames().
There's nothing which can be offered by the both contexts. So there would be absolutely no reason to prefer the one or the other. Just use the right one for the job you need to perform.
As to the client ID, it's indeed generated by JSF, but definitely not on server's startup. It's just generated for every single JSF component on a per-view basis. In case of input components like <h:inputText>, which generates a HTML <input> element, it also becomes the name attribute like so
<input type="text" id="formId:inputId" name="formId:inputId" ... />
The formId:inputId is exactly the JSF client ID. It becomes the request parameter name. The HTML representation of the command button has also a name which ends up as request parameter name with the button's value as parameter value.

HTTP module vs action filter in asp.net-mvc

I am developing an application in asp.net MVC3 and I have the following questions:
When should I write an HTTP module and when should I write an action filter?
Filter are more MVC approach of doing thing whereas Http Module are more of ASP.NET way of doing thing. Both serve similar purpose by providing hook in the processing pipline.
HttpModule is more generic and when you want some thing to be processed on every request. Filters are useful for adding action specific behaviour.
If you want some thing to be executed only once per Http Request, you should use an HttpModule. ActionFilter may get executed several times during a request until and unless you check IsChildActionOn.
HttpModule are called before and after the request handler executes. They are intended to enable a developer to intercept, participate, or modify each request. There are 22 available events that can be subscribed to that enables the module to work on the request in various stages of the process. The events are useful for page developers who want to run code when key request pipeline events are raised. They are also useful if you are developing a custom module and you want the module to be invoked for all requests to the pipeline.
Filters are designed to inject logic in between MVC request life cycle. Specifically before and after de action is invoked, as well as, before and after the result is processed. Filters provide users with powerful ways to inspect, analyze, capture and instruments several things going around within MVC projects. As of MVC5, there are 5 types of filters :
Authentication
Authorization
Action
Result
Exception
So if you want to intercept, participate, or modify in a specific of the 22 events in the http request pipeline choose the modules. If your logic is is strictly related to the action method you better server overriding one of the following ActionFilterAttribute methods:
OnActionExecuting
OnActionExecutted
OnResultExecuting
OnResultExecuted
HttpModule is how IIS allows an Web application to override the default behavior or add custom logic by letting you attach event handlers to HttpApplication events.
Different IIS modes (Integrated or Classic) even use has different Web.config settings.Reference:
http://msdn.microsoft.com/en-us/library/ms227673(v=vs.100).aspx
Example: redirect non-www to www URLs
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += this.Application_PreRequestHandlerExecute;
}
private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
Uri requestUrl = HttpContext.Current.Request.Url;
string host = requestUrl.Authority.ToLower();
if (!host.StartsWith("www"))
{
HttpContext.Current.Response.Redirect(requestUrl.Scheme + "://www." + host + requestUrl.PathAndQuery);
HttpContext.Current.Response.End();
}
}
An Action Filter is an attribute decorating controllers or action methods. It is an abstraction layer between MVC routing and action methods. With action filters, we can apply same logic to multiple controllers or action methods. for example, custom logging.

RouteUrl in class

How can I generate a URL by RouteName outside of a view or controller?
I want generate a URL by RouteName in a seperate class for an e-mail, but if I try to use UrlHelper.GenerateUrl. Then I don't see where I can get rest of the parameters for this function.
How i can generate URL by RouteName outside view or conroler ?
You shouldn't be needing/doing this. Urls should be generated only in the front layers where you have access to an HTTP context and passed to backed layers as arguments.
Of course you could always perform some horrible grotesque hack in your backend layer and hardcode some static HttpContext.Current in order to instantiate an UrlHelper and thus render your backed layers strongly coupled to the HTTP stack, making it impossible to be reused in isolation and unit tested.
Oh and by the way checkout MvcMailer if you need to send emails in your application. This way you can define the email body as templates where you will have access to helpers and stuff and won't need to perform the aformentioned grotesque hack.

Resources