Explain the usage of annotations in the Java Struts Framework _java

Source: Internet
Author: User
Tags i18n throw exception tomcat tomcat server

To start using annotations in your project, make sure that the jar files in the Webcontent/web-inf/lib folder include the following:

    • Struts2-convention-plugin-x.y.z.jar
    • Asm-x.y.jar
    • Antlr-x.y.z.jar
    • Commons-fileupload-x.y.z.jar
    • Commons-io-x.y.z.jar
    • Commons-lang-x.y.jar
    • Commons-logging-x.y.z.jar
    • Commons-logging-api-x.y.jar
    • Freemarker-x.y.z.jar
    • Javassist-.xy.z.ga
    • Ognl-x.y.z.jar
    • Struts2-core-x.y.z.jar
    • Xwork-core.x.y.z.jar

Now, let's see how you can do it in the Struts.xml file and replace it with annotations.

Struts2 annotation of the concept of interpretation, we need to reconsider our validation as an example illustrated in the Struts2 chapter.

Here, we will take an example, employees employee will be captured by name and age using a simple page, we will put two validations to ensure that use always enters a name and age should be between 28 and 65. So let's start with the main JSP page example.

To create a home page:
Let's write the main JSP page file index.jsp, which will be used to collect information about the above employees.

<%@ 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>
 
 

In index.jsp using struts labels, we haven't covered them yet, but we'll look at the relevant chapters of these tags. But now, suppose the S:textfield label prints an input field s:submit print a Submit button. We have used the label attribute tag, each label is created for each tag.

To create a view:
We will use the success.jsp of the JSP file to return the action defined by the invocation to success.

<%@ 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>
 
 

To create an action:
This is where the annotation will be used. Let's redefine the comment for the action employee class and add a method called Validate (), as shown in the Employee.java file. Make sure that the action class extends the Actionsupport class, otherwise the Validate method will not be executed.

Package com.yiibai.struts2;

 import com.opensymphony.xwork2.ActionSupport; import
Org.apache.struts2.convention.annotation.Action;
Import Org.apache.struts2.convention.annotation.Result;
Import Org.apache.struts2.convention.annotation.Results;

Import com.opensymphony.xwork2.validator.annotations.*; @Results ({@Result (name= "Success", location= "/success.jsp"), @Result (name= "input", location= "/index.jsp")}) public C
  Lass Employee extends actionsupport{private String name;

  private int age;
  @Action (value= "/empinfo") public String Execute () {return SUCCESS;
  @RequiredFieldValidator (message = ' The ' name is required ') public String getName () {return name;
  public void SetName (String name) {this.name = name; @IntRangeFieldValidator (message = ' age must is in between ', Min = "I", max = "a") PU
  Blic int Getage () {return age;
  public void Setage (int age) {this.age = age; }
}

In this example, we have used some annotations. Let me explain one by one:

First, we have the result annotation. The result of the annotation is a collection. The result annotation, we have two result comments. The result of the name of the resulting annotation corresponds to the execution method. They also contain a location where the view should be the corresponding execute () return value.

The next annotation is the action annotation. This is used to modify the Execute () method. The action method also requires a value that invokes the action on the URL.

Finally, two validated annotations are used. The Age field "name" field and integer range validation for the required field validation have already been configured. A custom validation message is also specified.

Configuration file:
We do not need struts.xml configuration file, let us delete the file, and let us check the contents of the Web.xml file:

<?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</filte r-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> <ini T-param> <param-name>struts.devMode</param-name> <param-value>true</param-value> & lt;/init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <ur L-pattern>/*</url-pattern> </filter-mapping> </web-app>

 

Now, right click on the project name and click Export > War file to create a war document. This war is then deployed under 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 do not enter any required information, just click the "Submit" button. You will see the following results:

Enter the required information, but enter the wrong "from" field, let's say "test" and age 30, and then click the "Submit" button. You will see the following results:

Type of annotation for Struts 2
the Struts 2 application can use JAVA5 annotations as an alternative to XML and Java property configurations. You can check that the most important annotations involve different categories of lists:
The Struts 2 application can use JAVA5 annotations as an alternative to XML and Java property configurations. Here is the most important annotation about the different categories of the list:

namespace annotations (action notes):
The @ namespace comment allows the definition of the namespace of the Convention action in the Action class, rather than the 0 configuration.

@Namespace ("/content") public
class Employee extends actionsupport{...
}

Result Comment-(action):
The @ result annotation allows action results defined in the action class, not in an XML file.

@Result (name= "Success", value= "/success.jsp") public
class Employee extends actionsupport{
 ...
}

Result Comment-(action):
The @ Results annotation defines the result of a set of actions.

@Results ({
  @Result (name= "Success", value= "/success.jsp"),
  @Result (name= "error", value= "/error.jsp")
Public
class Employee extends actionsupport{...
}

After comment (block comment):
The @After annotation marks the main method of operation and the method of executing the result after the call is required. The return value is ignored.

public class Employee extends actionsupport{
  @After public
  void IsValid () throws validationexception {
   / /Validate Model object, throw exception if failed
  } public
  String execute () {
   //Perform secure ACTION
   return SUCCESS
  }
}

Comment before (block comment):
The @ before annotation tag requires the primary action method of an action method to be invoked before executing the result. The return value is ignored.

public class Employee extends actionsupport{
  @Before public
  void IsAuthorized () throws Authenticationexception {
   //Authorize request, throw exception if failed
  } public
  String execute () {
   //Perform secure action
   
    return SUCCESS
  }
}

   

Beforeresult Comment-(intercept note):
The @ beforeresult annotation marks the action method that needs to be performed before a result. The return value is ignored.

public class Employee extends actionsupport{
  @BeforeResult public
  void IsValid () throws Validationexception {
  //Validate model object, throw exception if failed
  }

  Public String Execute () {
   //Perform action return
   SUCCESS
  }
}

Conversionerrorfieldvalidator annotation-(verification):
This validation note if there are any conversion errors made in the field check and apply to them if they exist.

public class Employee extends actionsupport{
  @ConversionErrorFieldValidator (message = ' Default message ', 
            key = ' I18n.key ', Shortcircuit = true) public
  String GetName () {return
    name;
  }
}

Daterangefieldvalidator annotation-(verification):
This verifies that the value of the Date field is within the specified range.

public class Employee extends actionsupport{
  @DateRangeFieldValidator (message = ' Default message ', 
  key = ' I18n.key ", Shortcircuit = True, 
  min =" 2005/01/01 ", max =" 2005/12/31 ") public
  String Getdob () {return
    DOB ;
  }
}

Doublerangefieldvalidator annotation-(verification):
This validation note checks that two fields have a value that is within the specified range. Nothing can be done if it is neither the smallest nor the largest.

public class Employee extends actionsupport{

  @DoubleRangeFieldValidator (message = ' Default message ', 
  key = ' I18n.key ", Shortcircuit = True, 
  mininclusive =" 0.123 ", maxinclusive =" 99.987 ") public
  String Getincome () {
    Return income
  }
}

Emailvalidator annotation-(verification):
This validation note checks that a field is a valid e-mail address if it contains a non-empty string.

public class Employee extends actionsupport{

  @EmailValidator (message = "Default message", 
  key = "I18n.key", Shortcircuit = true) public
  String Getemail () {return
    email;
  }
}

Expressionvalidator annotation-(verification):
This type of non field-level validation verifies the regular expression provided.

@ExpressionValidator (message = ' Default message ', key = ' I18n.key ',
Shortcircuit = true, expression = "an OGNL expression")
Intrangefieldvalidator annotation-(verification):
This validation note checks that the value of a numeric field is within the specified range. Nothing can be done if it is neither the smallest nor the largest.

public class Employee extends actionsupport{

  @IntRangeFieldValidator (message = ' Default message ', 
  key = ' I18n.key ", Shortcircuit = True, 
  min =" 0 ", max =" n ") public
  String Getage () {return age
    ;
  }
}

Regexfieldvalidator annotation-(verification):
This annotation validates a string field, using regular expressions.

@RegexFieldValidator (key = "Regex.field", expression = "yourregexp")
RequiredFieldValidator annotation-(verification):
This validation note checks that a field is not empty. Annotations must be applied at the methodological level.

public class Employee extends actionsupport{

  @RequiredFieldValidator (message = ' Default message ', 
  key = ' I18n.key ", Shortcircuit = True) public
  String Getage () {return age
    ;
  }
}

Requiredstringvalidator annotation-(verification):
This validation note checks that a string field is not empty (that is, non-null, length > 0).

public class Employee extends actionsupport{

  @RequiredStringValidator (message = ' Default message ', 
  key = ' I18n.key ", Shortcircuit = true, Trim = true) public
  String GetName () {return
    name;
  }
}

Stringlengthfieldvalidator annotation-(verification):
This validation checks that the string field is the appropriate length. Assume that the field is a string. If the setting is neither minlength nor maximum length, nothing will be done.

public class Employee extends actionsupport{

  @StringLengthFieldValidator (message = ' Default message ', 
  key = ' I18n.key ", Shortcircuit = True, 
  trim = true, minlength =" 5 ", MaxLength =" a ") public
  String GetName () {
    R Eturn name;
  }
}

Urlvalidator annotation-(verification):
This validation checks that a field is a valid URL.

public class Employee extends actionsupport{

  @UrlValidator (message = "Default message", 
  key = "I18n.key", Shortcircuit = true) public
  String GetURL () {return
    URL;
  }
}

Verify comments-(verified):
If you want to use multiple annotations of the same type, these annotations must be nested within the @validations () comment.

public class Employee extends actionsupport{

 @Validations (
  requiredfields =
   {@RequiredFieldValidator ( Type = validatortype.simple, 
   fieldName = "CustomField", Message 
   = "Your must enter a value for field."},
  re Quiredstrings =
   {@RequiredStringValidator (type = validatortype.simple, 
   fieldName = "stringisrequired", Message 
   = ' You must enter a value for string. '}
  )
  Public String GetName () {return
    name;
  }
}

CustomValidator annotation-(verification):
This annotation can be used for custom validation. Use Validationparameter annotations to provide additional params.

@CustomValidator (type = "Customvalidatorname", FieldName = "MyField")

Conversion annotations-(type conversion notes):
This is a markup annotation type conversion type level. Conversion annotations must be applied at the type level.

@Conversion () Public
  class Conversionaction implements Action {
}

createifnull annotation-(type conversion note):
This annotation sets the type conversion createifnull. Createifnull annotations must be applied at the domain or method level.

@CreateIfNull (value = True)
private list<user> users;

element annotation-(type conversion note):
This annotation sets the element for type conversion. Annotations that must be applied to field fields or method-level elements.

@Element (value = com.acme.User)
private list<user> userlist;

Critical annotations-(type conversion notes):
This annotation setting is key to type conversion. Key annotations that must be applied at the domain or method level.

@Key (value = java.lang.Long.class)
private Map<long, user> UserMap;

Keyproperty annotation-(type conversion note):
This annotation sets the type conversion keyproperty. Keyproperty annotations must be applied at the domain or method level.

@KeyProperty (value = "UserName")
protected list<user> users = null;

typeconversion annotation-(type conversion note):
The annotations for this annotation are the conversion rules for classes and applications. Annotations can be applied to typeconversion at the level of properties and methods.

@TypeConversion (rule = conversionrule.collection, 
converter = "java.util.String") public
void Setusers (List Users) {
  this.users = users;
}

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.