STRUCTS framework (1)

xiaoxiao2021-03-19  186

table of Contents

Order ...................................................................................................

Catalog ........................................................................................................................ 2

Struts framework

1. Struts compressed package content. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2.Struts architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3. Components in the Struts framework. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3.1 Struts profile. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ... 53.2 ActionServlet class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

3.3 ActionMapping class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

3.4 Action class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.5 Actionform class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3.6 ActionForWard class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

3.7 Error handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.Struts tag library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4.1 bean tag. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4.1.1 Bean replication tag. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.1.2 Define the tag of the script variable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

4.1.3 Displaying the bean property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

4.1.4 Message markers and internationalization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

4.2 Logical tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164.2.1 Conditional logic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . In one

4.2.2 Repeat markers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

4.2.3 Forwarding and redirect markers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194.3 HTML tag. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

4.3.1 Displays the form element and input controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

4.3.2 Display the mark of the error message. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . twenty four

4.3.3 Other HTML tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Struts framework

The Struts framework has the advantages of module, flexibility, and reuse of the components, and simplifies the development of MVC-based web applications.

This chapter discusses the Struts architecture in detail. We will see how Struts clearly define control, transaction logic, and appearance, simplifying the development of application processes. We will also introduce how the class provided by Struts makes development work more simple, including:

Control the program process

Class implementing and executing program transaction logic

Custom marker makes it easier to create and verify the HTML form easier

1.Struts compressed package content

Folder Jakarta-Struts-1.0.2 contains two directories, libs, and webapps. There are files needed to create an application using Struts in the lib directory:

File Description

JDBC2_0-stdext.jar contains a JDBC2.0 Optional Package API class. If we want to use the data resources provided by Struts, you need to copy this file to web-inf / lib.

Struts.jar contains all Java classes in Struts. Also need to copy to Web-INF / LIB

* .tld tag library descriptor file describes a custom tag in multiple Struts tag libraries. Also copy to Web-Inf / Lib

There is a file under the WebApps directory:

Web application description

Struts-Blank.war A simple web application

Struts-Documentation.war contains all Struts documents on the Struts site

Struts-Example.war struts Demonstration

Struts-EXERCISETAGLIB.WAR is primarily used to increase the test page used by the custom label library, but it can also demonstrate how to use Struts tags.

Struts-template.war contains introductions and examples of Struts template tags

Struts-upload.war A simple example of how to use the Struts framework upload file

2.Struts architecture

Let us observe the components in the Struts frame from the angle of the MVC

Three parts of the frame: model, window and controller.

model

In the Struts framework, the model is divided into two parts:

Internal state of the system

Can change the status of the status (transaction logic)

The internal state is usually represented by a set of ActInform JavaBean. These beans may be self-contained and have a continuous state depending on the design or application complexity, or data (from a database) is only available when needed.

Large applications are typically encapsulated transaction logic (operation) in method, which can be called the bean call. For example, shopping cart bean, it has information about purchasing goods, there may be a checkout () method to check the user's credit card, and send information to the warehouse.

In a small program, the operation may be embedded in the Action class, which is part of the controller role in the Struts framework. This method is very suitable when logic is simple. It is recommended that users separate transaction logic (what to do) with the role (decision to do) played by the Action class.

Windows

Established by JSP, Struts contains extended custom label libraries to simplify the process of created a fully international user interface.

Controller

In Struts, the basic controller component is an instance servert in the ActionServlet class, and the actually used servlet is defined by a set of mappings (described by the ActionMApping class) in the configuration file.

3. Components in the Struts framework

(Because the ROSE tool has not been downloaded, only this picture can be found, it illustrates a certain problem, especially ActionerRors, but it does not contain ActionMapping, JSP, and Tag Library, there is time to replace it.)

The components used in the frame:

ActionServlet controller

ActionClass contains transaction logic

ActionForm Display Module Data

ActionMapping Help Controller Maps the request to the action

ActionForWard is used to indicate an object that is transferred

ActionError is used to store and recycle errors

The Struts tag library can alleviate the development of the development display level

Let's take a look at the roles and responsibilities they play in the framework.

3.1 Struts Profile

This is the strew-config.xml that combines the Struts component: struts-config.xml. Defaults

/Web-inf/struts-config.xml. Profiles can be defined:

Global forwarding

ActionMApping class

Actionform Bean

JDBC data source

Configure global forwarding

Global forwarding is used to create logical name mappings between JSP pages. Forwarding can be obtained by an instance that calls an operation map, for example:

ActionMappingInstace.FindForward ("LogicalName");

Example of global forwarding: (All example I have not explained, one is that the combination table can be understood, the second is that most of the examples come from the series four, you should have a time after the experiment, then look again)

Property description

Name global forwarded name

Path with the relative path of the target URL

Configuring actionmapping

The ActionMapping object helps process control within the framework, which can map the request URI to the Action class and associate the Action class with the ActionForm bean. ActionServlet uses these mappings internally and transfers control to an instance of a specific Action class. All Action classes use the Perform () method to implement a specific application code, return an ActionForward object, including the target resource name of the response forwarding. E.g:

TYPE = "BOOKACTION"

Name = "BOOKFORM"

Scope = "request"

INPUT = "/ createbook.jsp">

Property description

Path Action class relative path

Name of Action Bean associated with this operation

TYPE Connect to the full name of the ACTION class of this map (available)

Scope of Scope Actionform Bean (request or session)

Prefix is ​​used to match the prefix of request parameters and bean properties

SUFFIX is used to match the suffix of request parameters and bean properties

Attribute scope.

The fully qualified name of the class of the classname actionmapping object is org.apache.struts.Action.ActionMapping

Input Enter the path to the form, pointing to the control of the input error that the bean must return.

Unknown is set to TRUE, the operation will be operated as a default operation as all the URIs that are not defined an actionMApping

Validate is set to TRUE, before calling the Perform () method on the Action object, the ActionServlet will call the ActionForm Bean's validate () method for input check.

With elements, the logical name of the resource can be defined, which is the target of the Action class's response to be forwarded.

Property description

ID ID

The fully qualified name of the ClassName ActionForward class, the default is org.apache.struts.Action.ActionForward

The logical name used when the Name operation class accesses the ActionForward

Path responding to the path of forwarded target resources

REDIRECT If set to true, ActionServlet uses the sendredirect () method to forward resources.

Configuring an actionform bean

The ActionServlet uses ActionForm to save the request parameters, these beans correspond to the name in the HTTP request parameter, the controller passes the request parameters to the ActionForm bean instance, and then transfer this instance to the Action class. example:

Property description

ID ID

The fully qualified name of the classname actionform bean, the default value is org.apache.struts.Action.ActionFormbean

Name form bean in the name of the related scope, this property is used to associate bean with actionmapping

The fully qualified name of the TYPE class

Configure JDBC data sources

Use the elements to define multiple data sources.

Property description

ID ID

KEY Action class uses this name to find a connection

TYPE realizes the name of the class of JDBC interface

The following property requires the element definition, is not used in the framework 1.1 version, but you can use the element. example:

Key = "contool"

TYPE = "org.apache.struts.util.GenericDataSource"

AutoCommit = "True" description = "Example Data Source Configuration"

Driverclass = "org.test.mm.mysql.driver"

Maxcount = "4"

MinCount = "2"

URL = "JDBC: mysql: // localhost / test"

User = "struts"

Password = "wrox" />

Property description

Desciption Data Source Description

AutoCommit Data Source created by default automatic update database mode

The class used by the DRIVERCLASS source used to display the JDBC driver interface

Logintimeout database login time limit, in seconds

Maxcount can be established by maximum connection

MinCount to create the minimum number of connections

Password database Access password

Readonly Create a read-only connection

User's username

URL JDBC URL

By specifying the keyword name, the Action class can access the data source, such as:

Javax.sql.datasource DS = servlet.finddataSource ("contool");

Javax.sql.connection con = ds.getConnection ();

3.2 ActionServlet class

The controller component in the frame is an org.apache.struts.Action.ActionServlet class implementation, this class is an extension of the javax.servlet.http.httpservlet class.

The Struts Controller's basic feature is:

1. Intercept user HTTP request

2. Map this request to the corresponding Action class, if this is the first request received by this class, will initialize the instance and

Cache.

3. Create or discover an ActionForm bean instance (see if the configuration file is defined), then transplant the request process to

BEAN.

4. Call the perform () method of the action instance and use the Actioform Bean, Action Mapping object, Request

Pass with the Response object.

Such as: Public ActionForWord Perform (ActionMapping Mapping,

Actionform Form,

HTTPSERVLETREQUEST REQUEST,

Httpservletresponse response

5.PerForm Returns an ActionForWord object that is connected to the appropriate JSP page.

ActionServlet configuration

We need to declare an actionServlet in Web.xml and configure it to be loaded. The following is an initialization parameter that can be configured:

Parameter default value description

A class of resources for Application Null Applications

Buffer size uploaded by buffersize 4096

CONFIG /WEB-INF /STRUTS-CONFIG.XML position and name

Content text / html default content type

Debug 0 level of program debugging

Detail 0 Level of Debugging Details

Factory NULL Message Resource Factory, used in internationalization interpretation of message resources

FormBean Org.Apache.Struts.Action.ActionFormBean package Actionform bean information class name forward org.apache.struts.Action.ActionForward package ActionForward object information class name

Locale True is True, which will store a local object in the user session

Mapping org.apache.struts.Action.ActionForward name of the class of the ActionMapping information

MaxFileSize 250M upload file maximum size

MultipartClass Org.Apache.struts.Action.ActionForward's name of the class for multi-part requests

Does the NOCACHE FALSE HTTP header to be set to disable cache

Null True is set to True, and NULL will be returned for invalid information keywords

Tempdir is provided as a servlet parameter to the program's work directory processing download file is a temporary work directory for use

Validate True uses a new format profile

Validating True Validity analysis of profiles

In most cases, the standard servlet can meet the needs of users.

When the URI of the first received a specific request, the ActionServlet instantiates the appropriate Action class, and the ActionServlet stores a reference in servlet in the Action class instance. When instantiated, the Action class will be temporarily stored.

ActionServlet also provides some methods that use the Action class to access resources such as data sources and forwarding targets.

ACTIONSERVLET method

ActinServlets provide a group of methods that can be used by Action objects.

All information for the Struts API can be found in Struts-Documentation.war. Dynamic add or delete, these methods only affect the current instance of the application:

Public Void AddFormbean (ActionformBean Formbean)

Public Void RemoveFormBean (ActionformBean Formbean)

Public Void Addforward (ActionForward ActionForward)

Public Void RemoveForward (ActionForward ActionForward)

Public void addmapping (actionMapping actionmapping)

Public void removemapping (actionMapping actionmapping)

Find objects according to the name:

Public ActionFormBean FindFormbean (String Name)

Public ActionForward FindForward (String Name)

Public anctionMAPPING FINDMAPPING (String Name)

Used to process data sources:

Public Void AddDataSource (String Key, DataSource DS)

Public DataSource FindataSource (String Key)

We can also:

End ActionServlet using the destroy () method

Use the Reload () method to reload the information from the Struts profile.

3.3 ActionMApping class

The relevant information mapped to a specific Action is stored in an actionMApping. ActionServelt transmits actionMApping to the Perform () method of the ActionMApping, Action will use an actionMApping's FindForward () method, this method returns an actionforward that specifies the name, so that ACTION Completed local forwarding. If you don't find the specific ACTIONFORWARD, return a null.public actionforward findForward (String Name)

You can dynamically add ACTIONFORWARD in the mapping:

Public Void Addforward (ActionForward Forward)

You can return to form beans associated with mapping:

Public string getName ()

Remove the mapping attribute domain (session or request)

Public string getscope ()

3.4 Action class

The Action class truly implements the application's transaction logic, which is responsible for processing the request. After receiving the request, the ActionServlet will:

Select the appropriate action for this request

Create an instance of an action if needed

Call an action perform () method

If an ActionServlet does not find a valid map, it calls the default Action class (defined in the configuration file). If you find the ActionServlet forward to the appropriate actionMApping class, this action uses actionMapping to find local forwarding, then get an actionMApping property. The ActionServlet also transmits the ServletRequest object or HTTPServletRequest object according to the signature of the servlet environment and the overform () method.

All Action classes expand the org.apache.struts.Action.Action class, and override a perform () method defined in the class. There are two perform () methods:

Handling non-HTTP (general) request:

Public ActionForward Perform (ActionMapping Action,

ACIONFORM FORM,

ServletRequest Request,

ServletResponse response)

THROWS IOEXCEPTION, ServletException

Handle HTTP request:

Public ActionForward Perform (ActionMapping Action,

ACIONFORM FORM,

HTTPSERVLETREQUEST REQUEST,

Httpservletresponse response

THROWS IOEXCEPTION, ServletException

The Action class must program as "thread security" because the controller will share the plural simultaneous request to share the same instance, according to the design of the Action class, you need to pay attention to the following points:

You cannot use instances or static variables to store status information for specific requests, which share global resources across the request in the same operation.

If you want to access resources (such as JavaBean and Session Variables) need to be protected during parallel access, then access to work

Method of Action class

In addition to the perform () method, there is also the following methods:

You can get or set the area associated with the request:

Public Locale getLocale (httpservletRequest request)

Public Void SetLocale (HTTPSERVLETREQUEST REQUEST, LOCALE LOCALE) Gets Message Resources for the application:

Public MessageResources getResources ()

Check if the user clicks on the "Cancel" button on the form, if yes, True will be returned:

Public Boolean ISCANCELED (HTTPSERVLETREQUEST REQUEST)

When an application error occurs, the Action class can store error messages using the following method:

Public Void SaveErrors (HttpservletRequest Request, ActionerRors Error)

The ActionError instance is used to store an error message, which stores the ActionError object in the request attribute list under the error key. The JSP page can display these error messages by using the custom tag defined in the Struts tag library. We will introduce later.

3.5 Actionform class

The framery assumes that the user creates an actionform bean for each form in the application, and the framework will do the following before the bean defined in the Struts-Config.xml file is called before the action class:

Under the associated keyword, it checks the user session for a Bean instance for the appropriate class. If there is no Bean available in the session, it will automatically create a new bean and add it to the user's session.

For each parameter corresponding to the bean property name, the Action calls the corresponding setup method.

When Action Perform () is called, the latest ActionForm bean is delivered to it, and the parameter value can be used immediately.

ActionForm class extension org.apache.struts.Action.Actionform class, the BEAN created by program developers can include additional properties, and ActionServlet may use reflection (allowing recycling information from loaded objects) to access it.

The ActionForm class provides another means of handling errors, providing two methods:

Public ActionerRors Validate (ActionMappin Mapping,

ServletRequest request)

Public ActionerRors Validate (ActionMappin Mapping,

HttpservletRequest Request)

You should override the validate () method in your own bean, and set the validate of the element in the configuration file to True. Before the ActionServlet calls the Action class, it calls validate (), if the ActionerRors returned is not null, ActinForm will store ActionerRors in the request attribute list based on the error keyword.

If the returned is not NULL, and the length is greater than 0, the instance is stored in the requested attribute list according to the error key, and then the ActionServlet will be forwarded to the target pointing to the INPUT property of the configuration file element.

If you need to perform a specific data validity check, it is best to do this in the Action class, not in the ActionForm class.

Method RESET () can restore the properties of the bean to the default value:

Public void reset (actionMapping mapping, httpservletRequest request)

Public void reset (ActionMApping Mapping, ServletRequest Request) Typical ActionFrom Bean is only available for the settings and reading methods (Getxxx) without implementing transaction logic. Only simple input check logic, the purpose of use is to store the latest data entered in the relevant form so that the same web page can be regenerated while providing a set of error messages so that the user can modify the incorrect input data. It is really checking data validity to check the Action class or the appropriate transaction logic bean.

3.6 ActionForward class

The purpose is to forward the processing results of the Action class to the destination.

The Action class gets the handle of the ActionForward instance, and then use three methods to return to the ActionServlet, so we can use Findforward ():

ActionServlet obtains a global forwarding according to the name

ActionMapping instance is transmitted to the Perform () method, and found a local forwarding according to the name

The other is to call the following constructor to create an example of themselves:

Public anctionforward ()

Public ActionForward (String Path)

Public ActionForward (String Path, Boolean Redirect)

3.7 Error handling

Struts provides two classes to handle errors: ActionerRRORS and ActionError, they all expand org.apache.struts.Action. ActionerRORS saves a collection of ActionError objects, each represents an independent error message. Each ActionError contains a keyword, which is mapped to the error message stored in the resource file, and this resource file is specified in the ActionServlet initialization parameter.

ActionError class

The ActionError class defines a set of overloaded constructors to create an error message, the first constructor method uses a string as a parameter, for example:

Actionerror Error = New Actionerror ("Error.INvalid");

Example Error maps an error message in the application resource file:

Error.INValid = invalid number

If you use , users will see the bold invalid number.

Another Java.Text.MessageFormat class can specify a replacement string in the message, for example:

Error.invalid = invalid number {0}

Create an error message:

ActionError Error = New Actionerror ('Error.invalid', New Double (-1));

JSP page display: Invalild Number -1

There is also a wrong keyword for a specific message:

Public string getKey ()

There is also an array of replacement strings:

Public String [] getValues ​​()

ActionError class

The ActionError class is not independently errors, which are always stored in the ActionerRors object. The ActionerRors object saves a collection of ActionError classes and their specific attribute values, we can use your own defined attribute value, or use ActionerRors.global_ERROR.

Below is an error handling in Perform () of the typical Action class:

MyForm Form = (myform) form; if (Number == -1) {

ActionerroS Errors = new actionerrors ();

ActionError Error = New ActionError ("Error.INvalid", New Double (-1));

Errors.Add (ActionerRors.global_Error, Error);

SaveerRors (Req, Errors);

String infut = mapping.getinput ();

Return New ActionForward (Input);

}

ActionerRors have the following useful methods:

Method description

Clear () Clear all error messages

Empty () If the ActionerRors object is empty, it returns true

Get () returns an error message. If there is no parameters, all information will be returned as an Iterator object.

Properties () Returns the Iterator containing the name of the property, these attributes have at least one error

Size () Returns the number of errors (integer)

Struts tag library

4.Struts Tag Library

The Struts tag library used by JSP window components consists of four types of tags:

Bean marking: Manage Bean in JSP page

Logic log: Used to control flow in JSP page

HTML mark: Used to generate an HTML mark, display data in the form, program the URL using the session ID

Template standard: Use dynamic template to construct a page of normal format

4.1 bean tag

This tag library contains tags for defining new beans, accessing beans, and its properties. The STRUTS framework provides a variety of custom tags to process JavaBean in the JSP page. These tags are packaged in a normal tag library, define its tag library descriptor in file struts-bean.tld. The bean tag library will define the tag in four subcategories:

Creating and reseeding the BEAN

Script variable definition mark

BEAN translation log

News Internationalization

4.1.1 Bean Copy Mark

You can define a new bean, you can copy the existing bean, you can also replicate properties from the existing bean.

tag is used:

Define new string constants

Reparse existing Beans to new defined bean objects

Repair existing bean properties to create new beans

Tag properties:

Property description

ID new defined bean script variable name, must be set

TYPE defines the class that introduces script variables

Value assigns a new object for script variables defined by id attributes

Name target bean name. If the value of the value is not set, this property must be set.

Property Name Attribute Defined Bean's property name, used to define new beans

Scope of the Scope source bean. If there is no setting, the search range is from the page scope to the application scope

Scope of Toscope target bean. If there is no setting, the default value is a page scope

For example: Define a bean:

Source bean is copied in the page scope to a request to request another bean in the domain:

Scope = "Page" Toscope = "request" />

4.1.2 Defining the tag of scripting variables

Define and generate script variables from multiple resources, including cookies, request parameters, HTTP headers, and more. The attribute is as follows: Property Description

ID script variable and name of page scope attribute to be defined

Name cookie / header / parameter name

Multiple If this property sets any value, all matching cookies are accumulated and stored into a cookie [] (an array) type bean. If there is no setting, specifying the first value of the cookie will be used as the value of the cookie type.

Value If there is no matching cookie or value, returns the default value specified by this property.

E.g:

The script variable name is MyCookie, the name of the cookie for creating this property is UserName.

The script variable name is MyHeader, the name of the request header is accept-language.

The script variable name is MyPatameter, and the name of the request parameter it saves is also myParameter.

tag will retrieve a resource response and introduce a script variable and a string type page scope. This resource can be a page, an ActionForward or an external URL. Unlike , the resource response is stored in the bean of a page scope, not written to the output stream. The property is as follows:

Property description

ID script variable and name of page scope attribute to be defined

Page An internal resource

Forward an ActionForward

HREF's full URL of resources

E.g:

The name of the script variable is MyInClude, and the response to retrieve is from the resource myjsp? X = 1.

Tag will retrieve resources in the web application and introduce a script variable and page scope attribute of the InputStream or string type. If a problem occurs while retrieving resources, an exception is generated. The property is as follows:

Property description

ID script variable and name of page scope attribute to be defined

The relative path of the Name resource

Input If this property does not exist, the type of resource is a string

E.g:

The name of the script variable is MyResource, the name of the resource to retrieve is MyResource.xml.

4.1.3 Displaying Bean Attributes

The tag is defined in the tag library to deliver the properties of the bean to the packaged JSP page write. This tag is similar to , the properties are as follows:

Property description

Name To perform the name of the bean displayed by the property

The name of the properties to display. If this attribute class has java.beans.propertyEditor, getastext () or TOSTRING method is called

Scope bean's scope, if no settings, search range is from page to application scope

Filter If you set true, all special HTML characters in the properties will be converted to the corresponding entity reference

IGNORE If false is set, a request time is abnormal when discovered attributes, otherwise returns NULL, for example:

FILTER = "true" />

MyBean's property MyProperty will be displayed, the scope is a request, and if any HTML special characters are found, it will be converted to the corresponding entity reference.

4.1.4 Message markers and internationalization

The STRTUS framework supports internationalization and localization. Users define their own area in their computer, when the web application needs to output a message, it will reference a resource file, all messages in this file use the appropriate language. An application may provide a lot of resource files, each file provides messages written in different languages. If you do not find the resource file of the selected language, you will use the default resource file.

The Struts Framework supports internationalization uses the tag, and the support of these tasks to implement the Java2 platform using the Locale and ResourceBundle classes defined in the Java.util packet. Java.Text.MessageFormat class definitions can support messages. With this feature, developers do not need to understand the details of these classes to internationalize and set messages.

Internationalization and localization with STRTUS:

The first step To define the name of the resource file, this file will contain all messages that will appear in the program with the default language. These messages are stored in the form of "keyword-value" as follows:

Error.validation.Location = The Entered Location Is Invalid

This file needs to be stored under the path of the class, and its path is to transmit to the ActionServlet as a parameter as a parameter, and the path format should comply with the standard naming specification for the full Java class. For example, if the resource file is stored in the web-inf / class directory, the file name is ApplicationResources.properties, then the parameter value that needs to be passed is ApplicationResources. If the file is in web-inf / classs / com / test, the parameter value should be com.test. ApplicationResources.

In order to achieve internationalization, all resource files must be stored in the directory where basic resource files are located. The basic resource file contains messages written in the local language in the default regional language - local language. If the name of the basic resource file is ApplicationResources.Properties, the name of the resource file written in other specific languages ​​should be ApplicationResources_xx.properties (xx is ISO code, such as English is en). So these files should contain the same keyword, but the value of the keyword is written in a particular language.

The area initialization parameters of the ActionServlet must be transmitted with a TRUE value so that ActionServlet stores a region object of a particular user computer under an action.locale_key keyword in the user session. You can now run an international Web site that automatically displays in accordance with the area on the user's computer.

We can also use a specific string to replace some messages, just like Java.Text.MessageFormat:

Error.invalid.number = the number {0} is valid

We can replace the string {0} to any number we need. Tag properties are as follows:

Property description

KEY resource file defines a message key

The property name of the area object stored in the local user session. If there is no setting, the default is an action.locale_keybundle in the application context, and store the name of the properties of the resource object. If this property is not set, the default value is action.Message_Key

Arg0 first replacement parameter value

ARG1 second replacement parameter value

ARG2 third replacement parameter value

ARG3 fourth replacement parameter value

For example: a message defined in the resource file:

Info.mykey = the number in {0}, {1}, {2}, {3}

We can use the following message tag:

This information mark output to the JSP page will be displayed as: The NumBers Entered Area 5, 6, 7, 8

4.2 Logical Tag

The mark of the logical library can be used to process appearance logic without the need to use the Scriptlet. The Struts Logic Tag library contains tags that can be conditionally generated, looped in an object collection, repeatedly generating output text, and application process control. It also provides a set of tags that handle flow control in the JSP page. These tags are encapsulated in the file named Struts-Logic.TLD. The mark defined by the logical tag library can perform the following three functions:

Conditional logic

repeat

Forward / Redirect Response

4.2.1 Conditional Logic

Struts has three types of conditional logic. The first category can compare the size of the following entities and a constant:

cookie

Request parameters

Parameters of beans or beans

Request header

This type of tag is listed below:

Mark function

Returns True if the constant is equal to the defined entity

Returns True if the constant is not equal to the defined entity

Returns true if the constant is greater than or equal to the defined entity

Returns true if the constant is less than or equal to the defined entity

Returns true if the constant is less than the defined entity

Returns true if the constant is greater than the defined entity

All markers of this class have the same properties

Property description

Value wants to compare constant values

Cookies to compare the name of HTTP cookie

HEADER wants to compare the name of the HTTP request header

PARAMETER wants to compare the name of the HTTP request parameter

Name If you want to compare the properties of bean or beans, this property represents the name of the bean

Property's name of the BEAN property to be compared

Scope BEAN's scope, if no scope is specified, its search range is from page to the application

E.g:

The entered name is someamename

The value of the request parameter named "Name" is "Somename".

The value of bean.prop is Greater Than 7

It is determined whether there is a bean named "bean" in the scope of the page, which has a PROP attribute, whether the value of this property is greater than 7. If this property can be converted to a value, the numerical comparison is performed, otherwise the string is compared. The second type of condition tag defines two tags:

Their function is to determine if a specific item is present before calculating the marker. The attributes and attribute values ​​of the tag determine the item to be checked.

Property description

Cookie The cookie specified by this property will be checked.

The request header specified by this property will be checked.

Parameter is the request parameter specified by this property to be checked.

Name If there is no Property property set, then the bean specified by this property will be checked. If set, the bean and bean properties will be checked.

Property checks if there is a specified property in the bean specified by the Name property

Scope If the name of the bean is specified, this is the scope of the bean. If you do not specify a scope, the search range is from the page to the application scope.

Role Checks whether the user currently confirmed is a special role

User checks if the user has a specific name

E.g:

The Bean Property Bean.prop is present

The tag determines whether there is a bean named "bean" in the page scope, this bean has a PROP property.

The third type of condition mark is more complicated, and these markers check the contents of the mark according to the results of the template match. In other words, these tags determine if the value of a specified item is a substring of a particular constant:

These tags allow the JSP engine to calculate the marker main body when the matching or no discovery is found. The property is as follows:

Property description

Cookies to compare the name of HTTP cookie

HEADER wants to compare the name of the HTTP header

The name of the HTTP request parameters to be compared

Name To compare the properties of the bean or bean, this property is the name of the user specified bean

Location If the value of this property is set, it will match this specified location (index value).

Scope If a BEAN is compared, this property specifies the scope of the bean. If this parameter is not set, the search range is from the page to the application scope

Property's property name to be compared

Value wants to compare constant values

E.g:

The parameter name is a sub-string of the string xyz from index 1

The mark checks if the request parameter named "name" is a sub-string of "XYZ", but the sub-string must start from the "XYZ" index position 1 (that is, the sub-string must be "y" or "yz" ).

4.2.2 Repeat marker

The tag is defined in the logical tag library, which can repeat the content of the marker according to the number of elements in a particular set. The type of collection can be java.util.ITerator, java.util.collection, java.util.map, or an array. There are three ways to define this collection:

Returns a collection of a collection of attributes to be used as beans using runtime expressions, and use the Name property to tell the name of the store.

Use the Name property to define a bean and use the Property property to define a BEAN property that returns a collection.

The collection of current elements is defined as a bean of a page scope. The attributes are as follows, all of these properties use runtime expressions.

Property description

Collection If there is no NAME property set, it specifies a collection of repetitions.

ID page Scope bean and script variable name, it saves the handle of current elements in the collection

The name of the indexed page scope JSP bean, which contains the current index of the collection after each repeated completion

The maximum number of repetitions of Length

Name as the name of the collection, or a bean name, it is a collection of properties, which is defined by the Property property is a collection.

OFFSET Repeat the index of the start position

Property as the name of the set of bean properties

Scope If the bean name is specified, this property sets the scope of the bean. If there is no setting, search range from page to application scope

Type is the type of bean for the currently defined page scope

E.g:

Collection = "<% = myList%>"

TYPE = "java.lang.integer"

OFFSET = "1"

Length = "2">

<% = currentint%>

The code will use the first element in the list to repeat two elements and allow the current element to use the script variable of the page scope and the Java.lang.integer type. That is, if MYLIST contains elements 1, 2, 3, 4, etc., the code will print 1 and 2.

4.2.3 Forwarding and Redirecting Tags

Forward mark

tag can forward the response to the redirect to a specific global ActionForward. The type of ActionForward determines whether to use the pageContext forward response or use SendRedirect to redirect the response. This marker has only one "name" property to specify the name of the global ActionForward, for example:

Redirect tag

tag is a powerful tool that can perform HTTP redirection. According to the specified different properties, it can achieve redirection in different ways. It also allows developers to specify query parameters for redirect URLs. The property is as follows:

Property description

Forward mapping the ActionForward for the resource relative path

HREF resource complete URL

Page Resources Relative Path

The name, request, session, or program property of the Name Map type, which contains the Name-Value parameter to which you want to add redirect URLs (if the Property property is not set). Or a bean name with the MAP type attribute, which contain the same information (no provosty attribute)

The name of the Bean property of the Property Map type. The name of the bean is specified by the Name property.

Scope If the name of the bean is specified, this property specifies the range of search beans. If there is no setting, search range from page to application scope

Paramid defines the name of a specific query parameter

The name of the paramname string type, which contains the value of the query parameter (if the paramproperty property is not set); or a bean name, its properties (specified in the paramproperty property) contains the query parameter value paramproperty string bean property Name, which contains values ​​for query parameters

Sear search range for paramscope paramname

At least one property in Forward, HREF, or PAGE is to be specified when using this tag to indicate which resource will be redirected.

4.3 HTML tag

The Struts HTML tag can be roughly divided into the following functions:

Display form elements and input controls

Display error message

Show other HTML elements

4.3.1 Display Form Elements and Input Controls

Struts is closely linked with the HTML form with the ActionForm Bean defined for formal operations. The name of the form input field is corresponding to the attribute name defined in the ActionForm Bean. When the form is first displayed, the input field of the form is transplanted from the ActionForm Bean. When the form is submitted, the request parameter will be transplanted to the Actionform Bean instance.

All the following properties can be used to define the JavaScript event processor using the following properties.

Property description

The onblur field lost the focus

The ONCHANGE field lost the focus and the value was changed.

The onclick field is clicked by the mouse

The onDblclick field is double-click the mouse.

Onfocus field receives input focus

OnkeyDown fields have focus and key presses

OnkeyPress fields have focus and key press and release

The onkeyup field has focus and has a button released

OnMouseDown Mouse Pointer pointing to fields and click

OnMousemove Mouse Pointer pointing to fields and moves within the field

OnMouseout Mouse pointer points to the control, but the pointer moves periphery

The ONMOUSEOVER mouse pointer does not point to the field, but the pointer moves inside the element

OnMouseup mouse pointer points to fields and releases mouse buttons

Other general properties that can be defined in

elements are:

Property description

AccessKey Defines the shortcut to access the input field

Style Defines the style of the input field

StyleClass Defines Style Table Classes for Enter Fields

TabINDEX input field Tab sequence

Form mark

tag is used to display HTML tags, you can specify the name of the AcitonForm Bean and its class name. If these properties are not set, you need to have a configuration file to specify an actionMApping to indicate which JSP page currently entered, and the Bean name and class retrieved from the map. If you do not find the specified name in the scope specified by ActionMapping, you will create and store a new bean, otherwise the found bean will be used.

The tag can include a sub-tag corresponding to various HTML input fields.

tag properties are as follows:

Property description

Action related to forms. In the configuration, this operation is also used to identify an actionform bean associated with a form.

Enctype form HTTP method encoding type

Fields that need to initialize focus in the FOCUS form

Method form HTTP method used

Name The name of the Actionform Bean associated with the form. If this property is not set, the name of the bean will get from the configuration information.

JavaScript event handle when the onreset form is reset

JavaScript event handle when the onSubmit form is submitted

Scope search for the range of Actionform Bean. If there is no setting, it will be obtained from the configuration file.

STYLE use format

StyleClass's format form

The full name of Type Actionform Bean. If there is no setting, it will be obtained from the configuration file.

E.g:

The operation path associated with the form is ValidateEmployee, and the form data is passed through POST. For this form, additional information, such as the bean name type, the scope of the scope, is retrieved from the form specified by the form:

TYPE = "com.example.validateexample"

Name = "Empform"

Scope = "request"

Input = "/ employeeinput.jsp">

If the configuration file contains the above information, and requesting the URI * .do is mapped to the ActionServlet, the name, type, and scope of action-related Actionform Beans are Empform, Com.example.employeform, request. These properties can also be used. Tag properties are defined.

The following tags must be nested in the tag

Button and cancellation

tag Displays a button control; tag Displays a cancel button. The property is as follows:

Property description

Property defines the name of the request parameter that returns to the server when the form is submitted

Tag on the Value button

Reset and submission tag

and tags can display HTML reset buttons and submitting buttons.

Text and text zone tag

and Tags are HTML text boxes and text spaces, respectively, with the following:

Property description

Property Defines the name of the request parameter that is sent back to the server when the form is submitted, or the attribute name of the bean used to determine the current value of the text element

The name of the name attribute is queried, which determines the value of the text box and the text area. If there is no setting, the name of the ActionForm associated with this embedded form is used.

Tag also has the following properties:

Property description

MaxLength's maximum number of characters

Size text box size (number of characters)

Mark a unique property is as follows:

Property description

Row number of ROWS text

Column number of cols text

Check box and check box tag

Tags can display check box controls. Tags You can display the HTML checkbox control, request the object to get the getParameterValues ​​() call used when passing the check box name will return a string array. The property is as follows:

Property description

The name of the Name bean, its property is used to determine if the check is displayed in the selected status display. If there is no setting, the name of the ActionFrom Bean associated with this embedded form will be used. The name of the Property check box is also the bean property name that determines if the check box is displayed in the selected status. In the case of the check box, this property must be an array.

Value When the check box is selected to return to the server's request parameter

E.g:

A checkbox called Married, returns a "y" when the form is submitted.

File tag

tag can display HTML file controls. The property is as follows:

Property description

The name of the name bean, its properties will determine the content displayed in the file control. If not set, the name of the ACTIONFORM BEAN associated with the embedded form will be used.

Property This property defines the name of the request parameter that is sent back to the server when the form is submitted, and the name of the bean property name used to determine the content displayed in the file control.

The Content Type Set of the Accept server can process. It will also filter the optional file type in the Customer Browser dialog.

The tag on the Value button, this button can browse the file in the local file system

Single button tag

tag is used to display the HTML radical button control, the property is as follows:

Property description

The name of the Name bean, its property is used to determine if the radio button is displayed in the selected state. If there is no setting, the name of the ActionFrom Bean associated with this embedded form will be used.

Property When the form is submitted back to the name of the request parameter of the server, and the name of the bean property used to determine if the radio button is displayed in the selected state.

Value Returns the value of the server when the radio button is selected

Hidden tag

Property description

The name of the Name bean, its property is used to determine the current value of the hidden element. If there is no setting, the name of the ActionFrom Bean associated with this embedded form will be used.

Property defines the name of the request parameter sent back to the server when the form is submitted, and the name of the bean property used to determine the current value of the hidden element

Value is used to initialize the value of hidden input elements

Password mark

tag can display the HTML password control, the properties are as follows:

Property description

MaxLength's maximum number of characters

The name of the Name bean, its property will be used to determine the current value of the password element. If there is no setting, the name of the ActionFrom Bean associated with this embedded form will be used.

Property defines the name of the request parameter sent back to the server when the form is submitted, and the name of the bean property used to determine the current value of the password element

Redisplay When the field is displayed, if the corresponding bean property has been set, this property determines whether the content is displayed.

Size field size

Select tag

tag can display HTML selection controls, the properties are as follows:

Property description

MultiPle indicates whether this selection control allows multiple selection

Name bean's name, its property determines which one. If there is no setting, the name of the ActionFrom Bean associated with this embedded form will be used.

Property defines the name of the request parameter that is sent back to the server when the form is submitted, and the name of the bean property used to determine which option needs to be selected.

SIZE can display the number of options

Value is used to indicate the options that need to be selected.

Option tag (this element needs to be nested in tag)

Tag Use to display the HTML option element collection, the properties are as follows:

Property description

The name of the Collection bean collection is stored in the properties of a scope. The number of options is the same as the number of elements in the collection. The Property property can define the bean properties used by the option value, and the LabelProperty property defines the properties of the bean used by the option mark.

LabelName is used to specify bean stored in a scope, this bean is a collection of strings, which can define the mark of element (if the flag is different)

When LabelProperty is used together with the Collection property, it is used to define the bean stored in a scope. This bean will return a string set that can be used to write the value attribute of element.

Name If this is the only specified property, it defines the bean stored in a scope. This bean will return a string collection that can be used to write the value attribute of element.

Property This property defines the Name property of each independent bean to display the option value when using the Collection property. If it is not used together with the Collection property, this property defines the property name (if there is a Name property) specified by the Name property, or defines an actionform bean, this bean will return a collection to write an option value.

Let's take a look at some examples of this tag:

Labelproperty = "optionLabel" />

The tag assumes that there is a collection of optioncollection in a scope that contains some independent beans with optionValue properties, each with the value of an option. The flag of each option is defined by the BEAN's OptionLabel property property.

OptionValues ​​represents a bean stored in a scope, it is a string collection that can be used to write an option value, while OptionLabels represents a bean stored in a scope, it is also a string A collection that can be used to write an option sign.

4.3.2 Display the mark of the error message

tag can be combined with ActionerRORS to display the error message. This tag first reads the message key ERRORS.HEADER from the resource file of the current area, and then displays the text of the message. Next it will cycle in the ActionerRRORS object (usually as a request parameter in the action.error_key keyword), read the message keyword of a single ActionError object, read and format the corresponding message from the resource file of the current area. And display them. It then reads the message corresponding to the ErrorS.footer keyword and is displayed.

By defining the Property property to filter the message to display, the value of this attribute should correspond to the keyword of the ActionError object in the ActionerRROR object. The property is as follows:

Property description

Bundle represents the name of the application scope attribute, which contains message resources, its default value ACIion.Message_Key

Locale represents the name of the session scope attribute, which stores the area information of the user's current login. Its default is Action.Error_Key

Name represents the name of the request attribute, which stores an ActionerRors object. Its default is the action.Error_KeyProperty this property specifies the keywords for storing each individual ActionError object in the ActionerRors object, which can be filtered

example:

Display all errors in the collection.

Shows errors stored in miss.name keywords.

4.3.3 Other HTML tags

The Struts HTML tag also defines the following tags to display other HTML elements:

: Show HTML elements

: Display Image Sign

: Display HTML link or anchor

: Create a URL without anchor marking

For details of these tags, please refer to the Struts documentation.

エ エ ー! Index project が つか つか せ ん. The dynamic template is a powerful means of modular web page layout design. The Struts Template Tag Library defines custom tags to implement dynamic templates.

Insert tag

Tags can insert a dynamic template in the application's JSP page. This tag has only one template property that defines a template JSP page. To insert a page of the template, there are multiple tags to specify, and these tags are defined as the main content of the tag.

Placement mark

tag is the tag internal use to specify the resource inserted into the template. The property is as follows:

Property description

Content defines the content to be inserted, such as a JSP file or an HTML file.

Direct If this is set to true, the content specified by the Content property will be displayed directly on JSP instead of being included.

Name of content to be inserted

Role If this property is set, the content can only be inserted when the current legitimate user has a specific role.

Get marker

Use the tag to retrieve the resources to the JSP page by the tag in the template JSP page. The property is as follows:

Property description

Name is inserted by tag

Role If this property is set, only the contents of content can only be performed when the current legitimate user has a specific role.

Use template tag

First write a template JSP page, it will be used by all web pages:

<% @ Taglib Uri = "/ Template" prefix = "template"%>

</ title></p> <p></ hEAD></p> <p><body></p> <p><Table Width = "100%" Height = "100%"></p> <p><tr height = "10%"></p> <p><TD></p> <p><Template: get name = "header" /></p> <p></ td></p> <p></ TR></p> <p><tr height = "80%"></p> <p><TD></p> <p><Template: get name = "content" /></p> <p></ td></p> <p></ TR></p> <p><tr height = "10%"></p> <p><TD></p> <p><Template: get name = "footer" /></p> <p></ td></p> <p></ TR></p> <p></ TABLE> </ body></p> <p></ html></p> <p>We name this file template.jsp. This file uses the <template: Get> tag to get the content provided by the JSP page using the <template: Put> tag, and display the content in an HTML table. These three contents are headings, contents and footers. Typical content JSP will be like this:</p> <p><% @ Taglib Uri = "/ Template" prefix = "/ template"%></p> <p><template: INSERT TEMPLATE = "Template.JSP"></p> <p><Template: put name = "header" content = "header.html" /></p> <p><template: put name = "content" Content = "Employeelist.jsp" /></p> <p><template: put name = "footer" Content = "footer.html" /></p> <p></ template: insert></p> <p>This application JSP page uses the <template: INSERT tag to define templates, then use the <template: PUT> tag to place the resource specified by the specific content name into the template JSP page. If we have the same page of hundreds of layout, but suddenly want to change this template, we only need to change the template.jsp file.</p> <p>to be continued</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-130170.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="130170" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.036</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'YWznJ88StCV_2B8wI3FkGZ1JFFAhCqXbqE_2FTBjODN6x2SpOsTorjVugm7J9r9ZNV1xwP3hSkQW3QBZ1Ty6'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>