Showing posts with label Struts2. Show all posts
Showing posts with label Struts2. Show all posts

Thursday, February 16, 2012

Interceptors in Struts

The power of annotation is now available in struts2. All your validations can be made easy just by annotating the field, which you want to validate. Example, you can make a null check, email validation and some more built in validation annotators.

You can get the power of annotation in your application just , by annotating the getter method of the respective field in the JSP page.
Example
If I have a field name username in my struts2 JSP page, and I want to make a validation on it(If value is not entered, a message should be thrown) then, just annotate the action class using @validation and you can do the validation for textfield like

@RequiredStringValidator(message="Enter username ")
public String getUsername() {
return username;
}
And in the JSP page you can get the message in the same way, as how you get when you add a fielderror.

You can also invoke a method, before invoking your action class method, after execution of your action class method and before returning result from action method, by using @before, @after, and @before result annotations. For this to work you have to configure interceptor stack in your struts.xml .

  1. <interceptors>
  2. <interceptor name="annotationWorkFlow" class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/>
  3. <interceptor-stack name="demostack">
  4. <interceptor-ref name="defaultStack" />
  5. <interceptor-ref name="annotationWorkFlow"/>
  6. /span>interceptor-stack>
  7. interceptors>
  8. <default-interceptor-ref name="demostack" />
If you add the above line within action tag then the interceptor tag will be applicable for that particular action alone. If you add the line out of the action tag then all the actions will pass through the set of interceptors.

You can also define your own interceptor classes.
For that your interceptor class should implement the interceptor interface. The example class is as shown below. Your request will pass through this interceptors in the order specified in the struts.xml file .
  1. public class TestInterceptor implements Interceptor{
  2. public String intercept(ActionInvocation next) throws Exception {
  3. long t1 = System.currentTimeMillis();
  4. String s= next.invoke();
  5. long t2 = System.currentTimeMillis();
  6. System.out.println("From Interceptor Action "+next.getAction().getClass().getName()+" took "+(t2-t1)+" millisecs");
  7. return s;
  8. }
  9. public void destroy() {
  10. }
  11. public void init() {
  12. // TODO Auto-generated method stub
  13. }
  14. }
Here the interceptor class just calculates the time taken to fullfill the request. The ActionInvoactions , invoke method will invoke the corresponding method in the action class.

To access the request and response within the Interceptor class, you need to getInvocationContext() and you need to get the HttpServletRequest and HttpServletResponse like this
HttpServletRequest request=(HttpServletRequest)next.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);

HttpServletResponse response=(HttpServletResponse)next.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);

Thus annotations and Interceptors gives flexibility and ease of development of our application.

Accessing Session Variables in struts2

Accessing session variables in Struts2
Here in this post, I am going to show how to access variables in different scope , in struts2. In struts 2 we can set objects in the following scopes, say request, session, page and application.
To share the object between Java and Jsp expressions, we need to set the java object in any of the above said scopes and can access it using the struts tag in Jsp page.


For Example....
If I have a variable named foodCollection which contains a collection of different food items, I can set this in different scopes and can access it.
1. Session
In Java Action class
ActionContext.getContext().getSession().setAttribute("foodCollection",foodCollection);
In Struts2 Jsp page
#session.foodCollection
2.Request
request.setAttribute("foodCollection",foodCollection);
In Struts2Jsp
#request.foodCollection
3.Page
pageContext.setAttribute("foodCollection",foodCollection);
In Struts2Jsp
#attr.foodCollection

Here is a simple example of using struts2.
First add the following entry in your web.xml, so that all your requests pass through the filterdispatcher filter instead Action servlet in struts1.2.
<filter
filter-namestruts2filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcherfilter-class>
filter>

<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>*.dourl-pattern>
filter-mapping>

The default URL pattern is .action which can be changed by using the struts.properties file.

Next write your struts.xml file and place it in the package where you want.
Struts.xml contains the mapping between the request and the corresponding action class.
<package name="struts2" extends="struts-default">
<action name="showLogin">
<result>/jsp/master/login.jsp</result>
action>

action name="doLogin" class="action.Login">
<result name="input">/jsp/master/login.jspresult>
<result name="error">/jsp/master/login.jspresult>
<result>/jsp/master/loginsuccess.jspresult>
action>

package>

Write a java class which extends ActionSupport class of struts2, you can either have a default execute method or any method name according to the requirements.

In the action class you cant access the request and session directly, you need to either use ActionContext class like this,

ActionContext.getContext().getSession().put("TestLoop1",testingVos);

or need to implement the ServletRequestAware and ,ServletResponseAware and override its setter method, also you define your getter method which returns the request and response and you can access like the one shown below

getServletRequest().getSession().setAttribute("testSessionVar", "From Action class set in session");
getServletRequest().setAttribute("TestVariable", "From Action class set in request");

Suppose if you want to access a collection in the action class in JSP page you dont have to set the collection in session or request, you can access it in the JSP page by just having the name of the collection and a getter method for that collection in the StrutsAction class like this
I have a collection named testingVos which is a collection of testing vo
In Action class, the code snippet will be like the one....
public ArrayList getTestingVos(){
return testingVos;
}


In JSP page the code snippet will be

<s:iterator value="testingVos">
<s:property value="code"/><s:property value="type"/>
s:iterator>