Sankar R.K
Sankar R.K

Reputation: 77

Access ApplicationResource.properties file from Action Class in Struts 2

can i access ApplicationResource.properties file keys from Action Class in Struts 2 and update the values of the key ?

Upvotes: 2

Views: 9738

Answers (2)

Pieter
Pieter

Reputation: 17705

I don't think you can update the values of those keys directly, that would kind of defeat the purpose of it being (static) resources.
You can however use placeholders.

ApplicationResources.properties

property.key=Hi {0}, there's a problem with {1}

MyAction.java

public ActionForward execute(ActionMapping mapping,
                             ActionForm form,
                             javax.servlet.ServletRequest request,
                             javax.servlet.ServletResponse response)
                      throws java.lang.Exception {
MessageResources msgResource = getResources(request);
String msg = msgResource.getMessage("property.key", "Sankar", "updating values in the resources.");
}

Upvotes: 4

sumitknath
sumitknath

Reputation: 11

Yes its possible. Lets say if you have a property error.login in applicationResources.properties file. eg : error.login= Invalid Username/Password. Please try again.

then in the Action class you can access it like this : getText("error.login")

Complete example:

applicationResources.properties

error.login= Invalid Username/Password

LoginAction.java

package net.sumitknath.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

    private String username;

    private String password;

    public String execute() {
        if (this.username.equals("admin") && this.password.equals("admin123")) {
            return "success";
        } else {
            addActionError(getText("error.login"));
            return "error";
        }
    }

    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;
    }
}

Upvotes: 1

Related Questions