Action development is completed by inheriting the ActionSupport class. The ActionSupport class not only simply implements the Action interface, but also adds support for verification and localization. Custom Actions in real development need to inherit this class. Add form verification function to user login
The role of ActionSupport class:
struts2 does not require the action class we designed to inherit any struts base class or struts interface, but in order to facilitate the implementation of our own actions, we will inherit the com.opensymphony.xwork2.ActionSupport class in most cases, and override the public String execute() throws Exception method in this class. Because there are many practical excuses in this class, many default methods are provided, including international information methods, default methods for processing user requests, etc., which can greatly simplify the development of Acion. In Struts2, Action is usually used directly to encapsulate HTTP request parameters. Therefore, the Action class should also include attributes corresponding to the request parameters, and provide corresponding getter and setter methods for the attributes.
So what is the difference between the Action interface and the ActionSupport class?
The Action interface has:
public static final String SUCCESS = "success";public static final String NONE = "none";public static final String ERROR = "error";public static final String LOGIN = "login";public String execute() throws Exception;
You can see that there are five static constants and execute() with return type String
On the basis of implementing the Action interface, the Actionsupport tool class also defines a validate() method. If the method is overridden, it will be executed before the execute() method. If the verification fails, it will be transferred to the input. The input attribute must be configured when configuring the Action.
In addition, Actionsupport also provides a getText(String key) method and realizes internationalization, which obtains internationalization information from resource files.
In this way, when customizing the tag, you can define a variable as a new actionsupport object to achieve internationalization.
The Actionsupport class has (source code):
public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {protected static Logger LOG = LoggerFactory.getLogger(ActionSupport.class);private final ValidationAwareSupport validationAware = new ValidationAwareSupport();private transient TextProvider textProvider;private Container container;public void setActionErrors(Collection<String> errorMessages) {validationAware.setActionErrors(errorMessages);}public Collection<String> getActionErrors() {return validationAware.getActionErrors();}public void setActionMessages(Collection<String> messages) {validationAware.setActionMessages(messages);}public Collection<String> getActionMessages() {return validationAware.getActionMessages();}@Deprecatedpublic Collection<String> getErrorMessages() {return getActionErrors();}@Deprecatedpublic Map<String, List<String>> getErrors() {return getFieldErrors();}public void setFieldErrors(Map<String, List<String>> errorMap) {validationAware.setFieldErrors(errorMap);}public Map<String, List<String>> getFieldErrors() {return validationAware.getFieldErrors();}public Locale getLocale() {ActionContext ctx = ActionContext.getContext();if (ctx != null) {return ctx.getLocale();} else {if (LOG.isDebugEnabled()) {LOG.debug("Action context not initialized");}return null;}}public boolean hasKey(String key) {return getTextProvider().hasKey(key);}public String getText(String aTextName) {return getTextProvider().getText(aTextName);}public String getText(String aTextName, String defaultValue) {return getTextProvider().getText(aTextName, defaultValue);}public String getText(String aTextName, String defaultValue, String obj) {return getTextProvider().getText(aTextName, defaultValue, obj);}public String getText(String aTextName, List<?> args) {return getTextProvider().getText(aTextName, args);}public String getText(String key, String[] args) {return getTextProvider().getText(key, args);}public String getText(String aTextName, String defaultValue, List<?> args) {return getTextProvider().getText(aTextName, defaultValue, args);}public String getText(String key, String defaultValue, String[] args) {return getTextProvider().getText(key, defaultValue, args);}public String getText(String key, String defaultValue, List<?> args, ValueStack stack) {return getTextProvider().getText(key, defaultValue, args, stack);}public String getText(String key, String defaultValue, String[] args, ValueStack stack) {return getTextProvider().getText(key, defaultValue, args, stack);}public String getFormatted(String key, String expr) {Map<String, Object> conversionErrors = ActionContext.getContext().getConversionErrors();if (conversionErrors.containsKey(expr)) {String[] vals = (String[]) conversionErrors.get(expr);return vals[0];} else {final ValueStack valueStack = ActionContext.getContext().getValueStack();final Object val = valueStack.findValue(expr);return getText(key, Arrays.asList(val));}}public ResourceBundle getTexts() {return getTextProvider().getTexts();}public ResourceBundle getTexts(String aBundleName) {return getTextProvider().getTexts(aBundleName);}public void addActionError(String anErrorMessage) {validationAware.addActionError(anErrorMessage);}public void addActionMessage(String aMessage) {validationAware.addActionMessage(aMessage);}public void addFieldError(String fieldName, String errorMessage) {validationAware.addFieldError(fieldName, errorMessage);}public String input() throws Exception {return INPUT;}public String doDefault() throws Exception {return SUCCESS;}public String execute() throws Exception {return SUCCESS;}public boolean hasActionErrors() {return validationAware.hasActionErrors();}public boolean hasActionMessages() {return validationAware.hasActionMessages();}public boolean hasErrors() {return validationAware.hasErrors();}public boolean hasFieldErrors() {return validationAware.hasFieldErrors();}public void clearFieldErrors() {validationAware.clearFieldErrors();}public void clearActionErrors() {validationAware.clearActionErrors();}public void clearMessages() {validationAware.clearMessages();}public void clearErrors() {validationAware.clearErrors();}public void clearErrorsAndMessages() {validationAware.clearErrorsAndMessages();}public void validate() {}@Overridepublic Object clone() throws CloneNotSupportedException {return super.clone();}public void pause(String result) {}private TextProvider getTextProvider() {if (textProvider == null) {TextProviderFactory tpf = new TextProviderFactory();if (container != null) {container.inject(tpf);}textProvider = tpf.createInstance(getClass(), this);}return textProvider;}@Injectpublic void setContainer(Container container) {this.container = container;} You can see that there are many methods in it, but we obviously see that there is a method that we know very well, validate(), and data verification. Through this method, we can prompt when logging in, the username and password are empty, or other...
Now give a simple example: when the username and password are empty, give the customer a friendly prompt.
The following are two ways to explain the data verification function of Struts 2.
1. Coding method verification
1) Action must be inherited from ActionSupport
2) Write a public void validateXxx() method for a request processing method to be checked, and perform form data verification inside the method.
3) You can also write the public void validate() method for all request processing methods.
4) In the verification method, you can add field verification error message through the addFieldError() method.
5) When the verification fails, the Struts framework will automatically jump to the Result page with name input. In the verification failure page, you can use <s:fielderror/> to display error messages
6) Simple and flexible. But it's not very reusable
Rewrite the validate method
1. The Action we wrote generally inherits and ActionSupport, and ActionSupport not only implements the Action interface, but also implements the Validatable interface, providing data verification function. Define a validate method in the Validatable interface, override the method, if an error occurs in the verification form input field, add the error to the fieldError field of the ActionSupport class, and then output it through the OGNL expression.
The following is the user login verification interface:
<body><%--Output verification information--%><%--If you want a single prompt<s:fielderror fieldName="uname"/>--%><%--<s:property value=""/>--%><div style="color:red"><s:fielderror/></div> <s:form name="form1" namespace="/" method="post" action="LoginValidateAction"><s:div>Please enter username:<s:textfield name="user.uname"></s:textfield></s:div><s:div>Please enter password: <s:password name="user.upwd" >/s:password></s:div><s:submit value="Login"></s:submit></s:form><%--debug --%><s:debug></s:debug></body>
After the user enters the data, submit it to LoginValidateAction:
public class LoginValidateAction extends ActionSupport implements Action {public User user;public Map<String, Object> map;//The verification method will work on all Actions @Override public void validate() {if(user.getUname().length()==0){addFieldError("uname", "The user name cannot be empty!");} if(user.getUpwd().length()==0){addFieldError("upwd", "Password cannot be empty!");} } //Methods for handling business public String execute() throws Exception {System.out.println(user.getUname());if(user.getUname().equals("admin")&&user.getUpwd().equals("admin")){//Let Struts2 inject map collection map.put("uname", user.getUname());//If the login is successful, return "success" return SUCCESS;}else{//Login failed, return errorreturn INPUT; //This must be input}}/*** @return the user*/public User getUser() {return user;}/*** @param user the user to set*/public void setUser(User user) {this.user = user;} The above LoginValidateAction class overrides the validate method, which will be executed before executing the excute method. If after executing the method, the filedError of the Action class contains a data verification error, the request will be forwarded to the input logical view.
Struts.xml is configured as follows:
<!-- Data verification--><action name="LoginValidateAction"><!-- When the result is "success", jump to the success.jsp page--><result name="success">success.jsp</result><!-- When the result is "error", jump to the fail.jsp page or is still login.jsp--><result name="input">LoginValidateAction.jsp</result><result name="login">fail.jsp</result> <result name="error">fail.jsp</result> </action>
Effects on the client:
But have you noticed that when the error is prompted, it is not the effect we want.
This is not what we want, so how can we change it? In fact, this mainly shows the struts2 theme style,
Let's take a look again:
It automatically adds styles to us. struts2 provides three themes, ajax, simple, xhtml. It defaults to xhtml theme. Of course, you can write any of your own themes, which we call custom themes. The above problems can be solved by setting them
There are two ways to solve it:
1. Simple method (also practical, for all struts2 tags), add the next line of code in Struts.xml.
<constant name="struts.ui.theme" value="simple" />
It means that all pages use the simple theme. At this time, the page it outputs does not add any unnecessary code, such as table tr td, etc., and we can edit the style of the page like other editing pages.
Let's take a look at the error prompt format
We can set a tag like this:
<s:property value="errors.uname[0]"/>
Comment out this tag:
<div style="color:red"><s:fielderror/></div>
But when we set it like this, this effect will occur.
This effect is a bit like the prompt when we usually enter errors, and there are other attribute values, so we don’t need to list them one by one.
Verification Framework with Struts2
XML configuration verification.
Executes before encoding.
1) For the Action class to be verified, write a verification rule file named: Action class name-validation.xml under the same package.
2) Add verification rules to the verification rule file: For specific verification device names, please refer to the reference of Struts2 or the API of Struts2.
a) Field verification: Rules for verifying each non-custom type Field in the Action class.
<field name="Field name to be verified"><field-validator type="check ruler name" short-circuit="Whether to be short path verification (default is false)"><param name="parameter name to be used by the verifier">value</param><message> Prompt message when the verification fails</message></field-validator><!-- You can also add other verification rules--></field>
b) Non-Field verification: Use OGNL expression for combinatorial verification for certain Fields in the Action class.
<validator type="fieldexpression"><param name="fieldName">pwd</param><param name="fieldName">pwd2</param><param name="expression"><![CDATA[pwd==pwd2]]></param><!-- OGNL expression--><message>Confirm that password and password input are inconsistent</message></validator>
c) Visitor verification: It is mainly used to verify the custom type Field in the Action class. (For use of model-driven mode)
i) Use visitor verification rules for custom type Field in the verification rules file of the Action class.
<!-- Use visitor verification for custom Field--><field name="user"><field-validator type="required" short-circuit="true"><message>Ussage information required</message><!-- Message prefix--></field-validator><field-validator type="visitor"><!-- Specify as visitor verification rule--><param name="context">userContext</param><!-- Specify the context name for this visitor verification--><param name="appendPrefix">true</param><!-- Whether to add the prefix of the verification failure message--><message>Ussage</message><!-- Message prefix --></field-validator></field>
ii) Write a verification rule file for the field of the visitor. The file name is: visitor field type name [-visitor verification context name]-validation.xml. For example: The file name in this example is User-userContext-validation.xml
Note: This file should be stored in the package where the visitor field type is located.
iii) Add verification rules for the Field to be verified in the visitor's Field verification rule file.
We can also perform data verification by adding a verification configuration file without rewriting the validate method. This verification configuration file completes the verification of the form field by using the existing verification device in Struts2. Here, take the requiredstring verification device as an example. This verification device is a required verification device that specifies that a certain form field must be entered.
The following is the way to write the LoginValidateAction-validation.xml of this verification configuration file:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"><validators><field name="uname"><field-validator type="requiredstring"><message>Username cannot be empty</message></field-validator></field><field name="upwd"><field-validator type="requiredstring"><message>Passage cannot be empty</message></field-validator><field-validator type="stringlength"><param name="maxLength">18</param><param name="minLength">6</param><message>Passage length should be between ${minLength}--${maxLength} bits</message></field-validator></field></validators> Note: This verification configuration file must comply with the following two rules:
1. The fate format of the file must be the Action class name -validation.xml. For example, in this example, the file name is: LoginValidateAction-validation.xml
2. The file must be in the same path as the class file of the Action class. In this example, the file is in
The code of the LoginValidateAction class is still the same:
public class LoginValidateAction extends ActionSupport implements Action {public User user;public Map<String, Object> map;//The verification method will work on all Actions @Override public void validate() {if(user.getUname().length()==0){addFieldError("uname", "The user name cannot be empty!");} if(user.getUpwd().length()==0){addFieldError("upwd", "Password cannot be empty!");} } //Methods for handling business public String execute() throws Exception {System.out.println(user.getUname());if(user.getUname().equals("admin")&&user.getUpwd().equals("admin")){//Let Struts2 inject map collection map.put("uname", user.getUname());//If the login is successful, return "success" return SUCCESS;}else{//Login failed, return errorreturn INPUT; //This must be input}}/*** @return the user*/public User getUser() {return user;}/*** @param user the user to set*/public void setUser(User user) {this.user = user;}The above is the Struts 2 data verification function and solution to the verification problem introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!