Open In App

Struts 2 requiredstring Validation Example

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Struts 2 is a strong framework for creating Java web applications. Its strong validation system, which enables developers to verify user input easily, is one of its primary strengths. Specifically, we’ll cover Struts 2 needed string validation in this post, showing you how to make sure particular fields aren’t null or empty. This is an essential component of web development to improve user experience and data integrity.

Validation XML files are the main tool used to do Struts 2 validation. These files provide guidelines that specify how input validation should be done. We will pay close attention to making sure that certain fields are not empty for necessary string validation. The essential element for this job is the required string validator.

Prerequisites

Before doing the string validation needed by Struts 2, confirm that you have the following setup:

XML file for Validation

To begin, build an XML file for your action’s validation. The name pattern for this file is usually “ActionClassName-validation.xml” The validation file might be called UserAction-validation.xml, for instance, if your action class is UserAction.

XML




<!-- UserAction-validation.xml -->
<!DOCTYPE validators PUBLIC "-//OpenSymphony//XWork Validator 1.0//EN" 
<validators>
    <field name="username">
        <field-validator type="requiredstring">
            <message>Your username is required.</message>
        </field-validator>
    </field>
    <!-- Add more fields as needed -->
</validators>


We are making sure that the username field is a mandatory string in this case.

Struts Configuration Validation File

Ensure that the validation file is referenced in your struts.xml settings.

XML




<!-- struts.xml -->
<package name="default" extends="struts-default">
    <action name="userAction" class="com.example.UserAction">
        <result>/user.jsp</result>
        <result name="input">/login.jsp</result>
        <!-- Reference the validation file -->
        <interceptor-ref name="defaultStack"/>
        <interceptor-ref name="validation">
            <param name="excludeMethods">input,back,cancel,browse</param>
        </interceptor-ref>
        <interceptor-ref name="workflow"/>
    </action>
</package>


Make that the “validation” interceptor’s <interceptor-ref> is included.

Handling Validation Errors in Action Class

Provide the required getters and setters for the fields you are verifying in your action class. Use the validate function to handle validation problems as well.

Java




// UserAction.java
public class UserAction extends ActionSupport {
    private String username;
  
    // Getter and Setter for username
    public String getUsername() {
        return username;
    }
  
    public void setUsername(String username) {
        this.username = username;
    }
  
    @Override
    public void validate() {
        if (username == null || username.trim().isEmpty()) {
            addFieldError("username", "Username is required.");
        }
        // Add more validation logic as needed
        // Example: Validate if the username contains only alphanumeric characters
        if (!username.matches("^[a-zA-Z0-9]+$")) {
            addFieldError("username", "Username should contain only letters and numbers.");
        }
    }
  
    // Action method for handling the form submission
    public String submitForm() {
        if (hasErrors()) {
            // If there are validation errors, return INPUT to display the form again
            return INPUT;
        }
  
        // Business logic: Perform actions based on the user input
        // Example: Save the username to a database
        // userService.saveUsername(username);
  
        // Return a success result
        return SUCCESS;
    }
  
    // Other action methods
  
    // Action method to display a welcome message
    public String welcomeMessage() {
        // Business logic: Generate a welcome message based on the username
        // Example: Fetch additional user information and display a personalized welcome
        // String welcomeMessage = userService.generateWelcomeMessage(username);
        // addActionMessage(welcomeMessage);
  
        addActionMessage("Welcome, " + getUsername() + "!");
        return SUCCESS;
    }
}


Explanation of the above Program:

  • To access and change the value of the username field, getter and setter methods are provided.
  • The necessary string validation for the username field is carried out using the validate method. This approach may be expanded to include more validation logic as required.
  • One example of an action method that manages form submission is the submitForm method. It executes business logic and delivers the SUCCESS result if there are no validation issues, otherwise it returns the INPUT result to show the form once again.
  • To show you how to have more than one action method in the same class, below is an extra action method called welcomeMessage.

These examples demonstrate fundamental business logic in the action methods (submitForm and welcomeMessage) and additional validation logic in the validate function. Adapt the code to the requirements of your application and include any service or database interfaces that are required.

Example of Struts 2 requiredstring Validation

Let’s look at a simple login form that has a username field. The validation framework will intercept the request, carry out the necessary string validation, and reroute the user back to the form with the relevant error messages when they submit the form without providing a username.

Login form (login.jsp):

<form action="userAction" method="post">
Username: <input type="text" name="username"/>
<input type="submit" value="Submit"/>
</form>

Handling Validation Errors (user.jsp):

<s:fielderror/>
<form action="userAction" method="post">
Username: <input type="text" name="username"/>
<input type="submit" value="Submit"/>
</form>

The <s:fielderror/> tag will display the validation error message.

Conclusion

With the robust and adaptable validation architecture that Struts 2 offers, developers may easily enforce necessary string validation. Your web apps’ dependability and usability may be improved by using the procedures described in this article. Use these methods in your Struts 2 applications to build user input forms that are reliable and verified.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads