Explain how to configure the action in the Java STRUTS2 Framework _java

Source: Internet
Author: User
Tags gettext

In Struts2, the action part, the controller layer, uses a low intrusion method. Why do you say that? This is because the action class in Struts2 does not need to inherit any base class, or implement any interfaces, nor is it directly coupled to the Servlet API. It is usually more like a normal Pojo (usually contains a parameterless Execute method), and it can be reused by defining a series of methods (parameterless methods) in the content, and by configuring each method as a separate action.
For example:

package example;

public class Useraction {

    private String username;

    private String password;

  Public String Execute () throws Exception {

       //

    ...... Return "Success";

  }

  Public String GetUserName () {return

    username;

  }

  public void Setusername (String username) {

    this.username = username;

  }

  Public String GetPassword () {return

    password;

  }

  public void SetPassword (String password) {

    this.password = password;

  }

}

Action Access Servlet

The attributes in this action class can encapsulate both the parameters and the processing results. They are not strictly differentiated by the system.

But in order for the user to develop the action class more specification, STRUTS2 provides us with an interface action that defines the following:

Publicinterface Action {

  publicstaticfinal String error= "ERROR";

  Publicstaticfinal String input= "INPUT";

  Publicstaticfinal String none= "NONE";

  Publicstaticfinal String login= "LOGIN";

  Publicstaticfinal String success= "SUCCESS";

  Public String Execute () throws Exception;

}

But our write action usually does not implement the interface, but rather inherits the implementation class Actionsupport of the interface.

The code for this class is as follows:

public class Actionsupport implements Action, Validateable, Validationaware, Textprovider, Localeprovider, Serializable {.... public void Setactionerrors (Collection errormessages) {validationaware.setactionerrors (err, ...).

  Ormessages);

  Public Collection getactionerrors () {return validationaware.getactionerrors ();

  public void Setactionmessages (Collection messages) {validationaware.setactionmessages (messages);

  Public Collection Getactionmessages () {return validationaware.getactionmessages ();

  Public Collection Geterrormessages () {return getactionerrors ();

  Public Map geterrors () {return getfielderrors ();

  //Set form field checksum error public void Setfielderrors (Map errormap) {validationaware.setfielderrors (ERRORMAP);

  Public Map getfielderrors () {return validationaware.getfielderrors ();

    Public Locale GetLocale () {Actioncontext CTX = Actioncontext.getcontext (); if (CTX!)= null) {return Ctx.getlocale ();

      else {log.debug ("Action context not initialized");

    return null;

  The method of obtaining internationalization information is public string GetText (string atextname) {return textprovider.gettext (atextname); public string GetText (string atextname, string defaultvalue) {return Textprovider.gettext (Atextname, Defaultval

  UE); public string GetText (string atextname, String defaultvalue, String obj) {return textprovider.gettext atextname

  , DefaultValue, obj);

  ...//the method used to access the Internationalized resource bundle public ResourceBundle gettexts () {return textprovider.gettexts ();

  Public ResourceBundle gettexts (String abundlename) {return textprovider.gettexts (abundlename); ///Add action error message public void Addactionerror (String anerrormessage) {validationaware.addactionerror (Anerrormessa

  GE);

  }//Add general information for action public void Addactionmessage (String amessage) {validationaware.addactionmessage (amessage);

 } public void Addfielderror (string fieldName, String errormessage) {validationaware.addfielderror (FieldName, Errormes

  SAGE); The public void Validate () {} is public Object clone () throws Clonenotsupportedexception {return Super.clo

  NE ();

 }

..........

}

As mentioned earlier, STRUTS2 is not directly coupled to the Servlet API, so how does it access the Servlet API?

The original STRUTS2 provides a Actioncontext class that simulates the Servlet API. The main methods are as follows:

1) object get (Object key): This method simulates the Httpservletrequest.getattribute (String name) method.

2) the map getapplication () returns a map object that simulates the ServletContext instance.

3) Static Actioncontext GetContext (): Gets the Actioncontext instance of the system.

4) Map getsession (): Returns a Map object that simulates the HttpSession instance.

5) Map getparameters (): Gets all request parameters, simulates Httpservletrequest.getparametermap ()

You might wonder why these methods always return to a map? This is mainly to facilitate testing. As for how it converts a map object to an instance of the actual Servlet API, we don't have to worry about it, because Struts2 has built some interceptors to help us with this transformation.

In order to directly use the servlet API,STRUTS2 provides us with the following several interfaces.

1) Servletcontextaware: The action that implements this interface can directly access the ServletContext instance.

2) Servletrequestaware: The action that implements this interface can directly access the HttpServletRequest instance.

3) Servletresponseaware: The action that implements this interface can directly access the HttpServletResponse instance.

The above mentioned action access servlet, let's take a look at how Struts2 's action implements code reuse. Take useraction, how do I rewrite this action if I let this action handle both the user registration (regist) and the login (longin)? The rewritten useraction are as follows:

package example;

public class Useraction extends Actionsupport {

    private String username;

    private String password;

  Public String regist () throws Exception {

       //

    ...... return SUCCESS;

  }

Public String Login () throws Exception {

       //

    ...... return SUCCESS;

  }

  Public String GetUserName () {return

    username;

  }

  public void Setusername (String username) {

    this.username = username;

  }

  Public String GetPassword () {return

    password;

  }

  public void SetPassword (String password) {

    this.password = password;

  }

}

The action configuration in Struts.xml
It's OK to write it, of course not. We must also configure it in the Struts.xml file. There are two types of configuration methods:

1 Specify the method attribute for the action element in a normal way.

<action name= "loginaction" class= "Example". Useraction "method=" Login ">

    <result name=" Success ">/success.jsp</result>

</action>

<action name= "registaction" class= "Example". Useraction "method=" regist ">

    <result name=" Success ">/success.jsp</result>

</action>

2 Specifies the method attribute for the action element by using the wildcard character.

<action name= "*action" class= "Example". Useraction "method=" {1} ">

    <result name=" Success ">/success.jsp</result>

</action>

The use of wildcards is too flexible, and the following is a more complex configuration.

<action name= "*_*" class= "Example". {1} Action ' method= ' {2} ' > ...

</action>

where the placeholder {1} matches the previous * of _, {2} matches the last *.

The

action configuration is based on annotations:
The configuration of the action below is not in Src/struts.xml, but is configured using annotations
if, in addition to the basic six jar packages, Also need a Struts-2.1.8.1\lib\struts2-convention-plugin-2.1.8.1.jar
but struts.xml or want
Specific example
login.jsp
&NBSP

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

 src/struts.xml
 

<span style= "Font-size:large;" ><?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE struts Public "-//apache Software foundation//dtd struts Configuration 2.1.7//en" "http://struts.apache.org/ Dtds/struts-2.1.7.dtd "> <struts> <!--the encoding method of request parameters--> <constant name=" struts.i18n.encoding "value = "UTF-8"/> <!--specifies the type of request suffix that is struts2 processed. Multiple comma-separated--> <constant name= "struts.action.extension" value= "Action,do,go,qqi"/> <!--when the struts.xml changes, whether to again Load. The default value is False (used in the production environment), the development phase is best to open--> <constant name= "Struts.configuration.xml.reload" value= "true"/> <!--make With the development model of struts. Development mode will have more debugging information. The default value is False (used in production environments), the development phase is best to open--> <constant name= "Struts.devmode" value= "false"/> <!--set whether the browser caches static content. The default value is True (used in production environments), the development phase is best to close--> <constant name= "Struts.serve.static.browserCache" value= "false"/> <!-- The creation of the action object is set by spring <constant name= "struts.objectfactory" value= "Spring"/>-->-whether to turn on dynamic method calls--> <constant name= "Struts.enable.DynamicMethodInvocation" value= "false"/> </struts>< 

 /SPAN>

 
 loginaction.java
 

Package com.javacrazyer.web.action; 
Import org.apache.struts2.convention.annotation.Action; 
Import org.apache.struts2.convention.annotation.ExceptionMapping; 
Import org.apache.struts2.convention.annotation.ExceptionMappings; 
Import Org.apache.struts2.convention.annotation.Namespace; 
Import Org.apache.struts2.convention.annotation.ParentPackage; 
Import Org.apache.struts2.convention.annotation.Result; 
 
Import Org.apache.struts2.convention.annotation.Results; 
 
Import Com.opensymphony.xwork2.ActionSupport; /** * Use annotations to configure action * */@ParentPackage ("Struts-default")//Parent Package @Namespace ("/user") @Results ({@Result (name = " Success ", location ="/msg.jsp "), @Result (name =" Error ", location ="/error.jsp ")}) @ExceptionMappings ({@Excepti Onmapping (Exception = "Java.lange.RuntimeException", result = "error")}) public class Loginaction extends Actionsupport 
  {private static final long serialversionuid = -2554018432709689579l; 
  Private String LoginName; Private String pwd; @Action (value = "Login") public String Login () throws Exception {if ("QQ". Equals (LoginName) && "123". EQ 
    Uals (pwd)) {return SUCCESS; 
    else {return ERROR; }} @Action (value = "add", results = {@Result (name = "Success", location = "/index.jsp")}) public String Add ( 
  ) throws Exception {return SUCCESS; 
  Public String Getloginname () {return loginname; 
  } public void Setloginname (String loginname) {this.loginname = LoginName; 
  Public String getpwd () {return pwd; 
  } public void SetPwd (String pwd) {this.pwd = pwd;
 } 
 
}


Success.jsp and error.jsp, I'm not going to post it.

Explanation of annotation Configuration

1) @ParentPackage Specify the parent package
2) @Namespace Specify namespaces
3 @Results A set of arrays of results
4) @Result (name= "Success", location= "/msg.jsp") a mapping of results
5) @Action (value= "login") specifies the request URL of a request processing method. Note that it cannot be added on the action class to add to the method.
6 An array of @ExceptionMappings-level declaration exceptions
7) @ExceptionMapping Mapping a declaration exception

Because this way is not very common, so we can only understand

Related Article

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.