The writing of action and the use of interceptor in the Java Struts Framework _java

Source: Internet
Author: User
Tags class definition create index exception handling extend tomcat server

Struts2 action/Action
actions are the core of the STRUTS2 framework because of their any MVC (model-View-Controller) framework. Each URL is mapped to a specific action that provides the processing logic required by the user's request to provide the service.

But the action also offers two other important abilities. First, the operation plays an important role in the transmission of the request data by way of a view, either a JSP or other type of result. Two, the action must assist the frame, in determining the result should render the view, in response to the request will be returned.

To create an action:
in the Struts2 action, the only requirement is that there must be an argument-free method to return a string or the result of an object that must be a pojo. If a method without parameters is unspecified, the default action is to use the Execute () method.

You can also choose to extend the Actionsupport class to implement 6 interfaces, including the action interface. The action interface is as follows:

Public interface Action {public
 static final String SUCCESS = "SUCCESS";
 The public static final String none = "None";
 public static final String error = "error";
 public static final String input = "input";
 public static final String login = "Login";
 Public String Execute () throws Exception;
}

Let's look at how the Hello World example operates:

Package com.yiibai.struts2;

public class helloworldaction{
 private String name;

 Public String Execute () throws Exception {return
  "success";
 }
 
 Public String GetName () {return
  name;
 }

 public void SetName (String name) {
  this.name = name;
 }
}

To illustrate this, the operation method controls the view, let's make the following change execution methods and extend the class Actionsupport as follows:

Package com.yiibai.struts2;

Import Com.opensymphony.xwork2.ActionSupport;

public class Helloworldaction extends actionsupport{
 private String name;

 Public String Execute () throws Exception {
  if (' SECRET '. Equals (name))
  {return
   SUCCESS;
  } else{return
   ERROR; 
  }
 
 Public String GetName () {return
  name;
 }

 public void SetName (String name) {
  this.name = name;
 }
}

In this example, we have some of the name attributes that are viewed in the logic of the Execute method. If the attribute equals the string "SECRET", we return the result of the success, otherwise we return the result of the error. Because we have extended actionsupport, we can use the success and error of string constants. Now, let's revise our Struts.xml file as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts public
 "-//apache Software foundation//dtd struts Configuration 2.0//en"
 "http:// Struts.apache.org/dtds/struts-2.0.dtd ">
 <struts>
  <constant name=" Struts.devmode "value=" true "/>
  <package name=" HelloWorld "extends=" Struts-default ">
   <action name=" Hello " 
   class=" Com.yiibai.struts2.HelloWorldAction "
   method=" "Execute" >
   <result name= "Success" >/helloworld.jsp </result>
   <result name= "error" >/AccessDenied.jsp</result>
   </action>
  < /package>
</struts>

Create a View
Let's create the following JSP file helloworld.jsp the WebContent folder in the Eclipse project. To do this, right-click the WebContent folder in Project Explorer and select New >jsp File. The file will require the returned result to be success, which is a string constant "success" defined in the action interface:

<%@ page contenttype= "text/html; Charset=utf-8 "%>
<%@ taglib prefix=" s "uri="/struts-tags "%>
 
 

The following is the file that will be called by the result of the action of the frame, which is equal to the error of the string constant "fault". Here's what accessdenied.jsp.

<%@ page contenttype= "text/html; Charset=utf-8 "%>
<%@ taglib prefix=" s "uri="/struts-tags "%>
 
 

We also need to create index.jsp in the WebContent folder. The file will act as the initial action URL, and the user can click to tell the Struts 2 framework to invoke the Helloworldaction class's Execute method and render the helloworld.jsp view.

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "
 pageencoding=" iso-8859-1 "%> <%@ taglib prefix="
S "uri="/struts-tags "%>
 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" 
"HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
< html>
 
 

That's it, no need to change the Web.xml file, so let's use the same web.xml, which is before we've created the example chapter. Now we are ready to run the Hello world application using the Struts 2 framework.

Executing the application
Right-click the project name and click Export > War file to create a war document. Then deploy the war in Tomcat's WebApps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you the following picture:

Let's "SECRET" and enter a word that should see the following page:

Now enter any word instead of "SECRET" and you should see the following page:

To create multiple actions:
you often define more than one action to handle different requests and provide different user URLs, so you can define different class definitions as follows:

Package com.yiibai.struts2;
Import Com.opensymphony.xwork2.ActionSupport;

 Class Myaction extends actionsupport{public
  static String good = SUCCESS;
  public static String bad = ERROR;
 }

 public class HelloWorld extends actionsupport{...
  Public String Execute ()
  {
   if (' SECRET '. Equals (name)) return myaction.good;
   return Myaction.bad;
  }
  ...
 }

 public class SomeOtherClass extends actionsupport{...
  Public String Execute ()
  {return
   myaction.good;
  }
  ...
 }

Configure these operations in the Struts.xml file as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts public
 "-//apache Software foundation//dtd struts Configuration 2.0//en"
 "http:// Struts.apache.org/dtds/struts-2.0.dtd ">
struts>
 <constant name=" Struts.devmode "value=" true "/ >
 <package name= "HelloWorld" extends= "Struts-default" >
  <action name= "Hello 
   class=" Com.yiibai.struts2.HelloWorld " 
   method=" "Execute" >
   <result name= "Success" >/helloworld.jsp</ result>
   <result name= "error" >/AccessDenied.jsp</result>
  </action>
  < Action name= "Something" 
   class= "Com.yiibai.struts2.SomeOtherClass" 
   method= "execute" >
   < Result name= "Success" >/Something.jsp</result>
   <result name= "error" >/accessdenied.jsp</ result>
  </action>
 </package>
</struts>

As seen in the above hypothetical example, the result of the action is repetitive success and error. To resolve this issue, it is recommended that you create a class that contains the results of the results.

Struts2 Interceptor
The concept of interceptors is the same as the servlet filter or JDK proxy class. Interceptors allow crosscutting functionality to be implemented separately from the action, as well as the framework. Using interceptors, you can achieve the following:

    • Providing preprocessing actions is called logic before.
    • Called after a post processing logical action is provided
    • Catch exceptions so that they can be substituted.

Many of the features provided by the STRUTS2 framework use examples of interception implementations, including exception handling, file uploads, lifecycle callbacks, and validations, which, in fact, serve as the basis for Struts2, which function to intercept, which may have 7 or 8 interceptors assigned to each action.

Interceptor for STRUTS2 framework:
The Struts 2 framework provides a good box intercept list to preset and ready to use. Several important interceptions are listed below:

See the full details of the Struts 2 document mentioned above for interception. will tell how to use the Struts application in an interceptor.

How do I use interceptors?
Let's look at how to use the existing interception, our "Hello World" program. We will use the timer to measure how long it took to perform the operation, the purpose of which is to intercept. The params interceptor is also used to send the action of the request parameter. You can try not to use this to intercept your example and find that the Name property is not set because the parameter is not able to reach the action.

We will continue to helloworldaction.java,web.xml the helloworld.jsp and index.jsp files as they have established the sample chapters, but let's modify the Struts.xml file as follows and add an interceptor


<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts public
 "-//apache Software foundation//dtd struts Configuration 2.0//en"
 "http:// Struts.apache.org/dtds/struts-2.0.dtd ">
<struts>
 <constant name=" Struts.devmode "value=" true "/>
 <package name=" HelloWorld "extends=" Struts-default ">
  <action name=" Hello " 
   class=" Com.yiibai.struts2.HelloWorldAction "
   method=" "Execute" >
   <interceptor-ref name= "params"/>
   <interceptor-ref name= "Timer"/>
   <result name= "Success" >/HelloWorld.jsp</result>
  < /action>
 </package>
</struts>

Right-click the project name and click Export > War file to create a war document. Then deploy this war in Tomcat's WebApps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you the following picture:

Now, enter the word in the given text box and click the Say Hello button to perform the defined action. Now, if you will check the generated log, you will find the following text:


Info:server Startup in 3539 Ms
27/08/2011 8:40:53 PM 
Com.opensymphony.xwork2.util.logging.commons.CommonsLogger Info
info:executed action [//hello!execute] took 109 Ms.

Here the bottom line is being generated because this tells the action to execute a total of 109ms timer interceptor.

Creating a custom Interceptor
using custom interceptors in your applications is an elegant way to provide crosscutting application functionality. Creating a custom interceptor is easy, requiring an extended interface, the following interceptor interface:


Public interface Interceptor extends serializable{
 void Destroy ();
 void Init ();
 String Intercept (actioninvocation invocation)
 throws Exception;
}

As its name suggests, the init () method provides a way to initialize the interceptor, and the Destroy () method provides a tool to intercept cleanup. Different actions that intercept being reused across requests and needs are thread-safe, especially The Intercept () method.

The Actioninvocation object can access the Run-time environment. It allows access to the action itself and the action of the method call, and determines whether the action has been invoked.

If you do not need to initialize or clear code, you can extend the Abstractinterceptor class. This provides a default-free implementation of the Init () and Destroy () methods.

To create an interceptor class:
Let's create the Java Resources myinterceptor.java> src folder:


Package com.yiibai.struts2;

Import java.util.*;
Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class Myinterceptor extends Abstractinterceptor {public

 String intercept (actioninvocation invocation) Throws exception{

  /* Let us do some pre-processing
  /String output = "pre-processing"; 
  SYSTEM.OUT.PRINTLN (output);

  * Let us call action or next interceptor *
  /String result = Invocation.invoke ();

  * Let us do some post-processing * *
  output = "post-processing"; 
  SYSTEM.OUT.PRINTLN (output);

  return result;
 }


As you can see, the actual action will use the interceptor to execute the Invocation.invoke () call. So, you can do some pretreatment and some processing upon demand.

The framework itself is initiated during the first call to invoke () of the Actioninvocation object. Each time invoke () is invoked, the state of the Actioninvocation's advisory and the execution is quasi intercepted next. The following data graph shows the same concept through the request stream:

To create an action class:
Let's create a Java file Helloworldaction.java Java resources > src below the content package named Com.yiibai.struts2.

Package com.yiibai.struts2;

Import Com.opensymphony.xwork2.ActionSupport;

public class Helloworldaction extends actionsupport{
 private String name;

 Public String Execute () throws Exception {
  System.out.println ("Inside action ...");
  Return "Success";
 } 

 Public String GetName () {return
  name;
 }

 public void SetName (String name) {
  this.name = name;
 }
}

In the previous example, we have seen that this is the same class. We have the standard "name" property of the getter and setter methods, and return the string "Success" method of execution.

Create a View
Let's create the following JSP file helloworld.jsp in the Eclipse project in the WebContent folder.

<%@ page contenttype= "text/html; Charset=utf-8 "%>
<%@ taglib prefix=" s "uri="/struts-tags "%>
 
 

To create a page:
We also need to create index.jsp in the WebContent folder. The file will act as the initial action URL where the user can click to tell the Struts 2 framework to invoke the Helloworldaction class definition method to render the helloworld.jsp view.

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "
 pageencoding=" iso-8859-1 "%> <%@ taglib prefix="
S "uri="/struts-tags "%>
 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" 
"HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
< html>
 
 

The Hello action definition in the above view file will be mapped to the Helloworldaction class and its execution method uses the Struts.xml file.

Configuration file
now we need to register our interceptor and call it the default interceptor in the previous example. To register a newly defined intercept, place the label plugin Struts.xml file directly under the <interceptors>...</interceptors> tab <package>. You can skip this step as the default interceptor, just as we did in our previous example. But here, let's register and use it as follows:


<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts public
 "-//apache Software foundation//dtd struts Configuration 2.0//en"
 "http:// Struts.apache.org/dtds/struts-2.0.dtd ">

<struts>
 <constant name=" Struts.devmode "value=" true "/>
 <package name=" HelloWorld "extends=" Struts-default ">

  <interceptors>
   < Interceptor Name= "Myinterceptor"
   class= "Com.yiibai.struts2.MyInterceptor"/>
  </interceptors>

  <action name= "Hello" 
   class= "com.yiibai.struts2.HelloWorldAction" 
   method= "execute" >
   <interceptor-ref name= "params"/> <interceptor-ref name= "myinterceptor"/> <result "name=
   " Success ">/HelloWorld.jsp</result>
  </action>

 </package>
</struts>

It should be noted that you can register multiple interceptors <package> tags within, at the same time, you can call multiple intercept inside the <action> tag. You can call the same interceptor with a different action.

Web.xml files need to be created under the Web-inf folder WebContent as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi=
"Http://www.w3.org/2001/XMLSchema-instance" "
 xmlns=" Http://java.sun.com/xml/ns/javaee " 
 xmlns:web=" http://java.sun.com/xml/ns/javaee/web-app_2_5. xsd "
 xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_3 _0.xsd "
 id=" webapp_id "version=" 3.0 ">
 
 <display-name>struts 2</display-name>
 < welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>
   Org.apache.struts2.dispatcher.FilterDispatcher
  </filter-class>
 </filter>

 < filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</ url-pattern>
 </filter-mapping>
</web-app>

Right-click the project name and click the Export > War file File to create a war document. Then deploy this war in Tomcat's WebApps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you the following picture:

Now, enter any word in the given text box and click the "Say Hello" button to perform the defined action. Now, if you check the generated log, you will find the following text below:


pre-processing
Inside action ....
Post-processing

Stacking multiple interceptors:
as you can imagine, configuring multiple interceptors will quickly become very difficult to control. For this reason, interceptors are managed with interceptor stacks. The following is an example directly from the Struts-default.xml file:


<interceptor-stack name= "Basicstack" >
 <interceptor-ref name= "Exception"/>
 < Interceptor-ref name= "Servlet-config"/>
 <interceptor-ref name= "Prepare"/>
 <interceptor-ref Name= "checkbox"/> <interceptor-ref name= "params"/> <interceptor-ref name=
 "Conversionerror" />
</interceptor-stack>

The above stack is called Basicstack and can be used in configuration, as shown below. This configuration node is placed under the <package.../> node. Each <interceptor-ref ... The/> tag references an interceptor or interceptor stack that has been configured on the current interceptor stack. Therefore, it is very important to ensure that the name is unique to all interceptor and interceptor stack configurations when the initial interceptor and interceptor stack are configured.

We've seen how to apply the blocking action to make the interceptor stack no different. In fact, we use the same label entirely:


<action name= "Hello" class= "com.yiibai.struts2.MyAction" >
 <interceptor-ref name= "Basicstack"/>
 <result>view.jsp</result>
</action

The above registered "Basicstack" All 6 interceptors completes the registration of the stack Hello action. It should be noted that the order in which interceptors are executed is in the configuration. For example, in the above case, the exception will be executed, servlet configuration, and so on.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.