Passing parameter in Bundle

1

My application uses internationalization of messages, etc. I would like to know how to pass parameters when passing a key that will fetch a value from the .properties file. Ex:

My crud screens will always display a success message when a new one is made. The default message would be: Successful product successfully! . The word Product may vary as the rest can be fixed. So in my .properties file it looks like this:

pruduto=Produto
cadastro.sucesso= {0} cadastrado(a) com sucesso!

That is, some value will always come before the cadastro.sucesso key. Currently my code looks like this:

package br.com.pokemax.util;

import java.util.Locale;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

public class MensagensUtil {

    private final static ResourceBundle BUNDLE = ResourceBundle.getBundle("properties.mensagens", new Locale("pt"));;

    public static String recupera(String chave) {
        return BUNDLE.getString(chave);
    }

    public static void sucesso(String mensagem) {

        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, recupera(mensagem), "");
        FacesContext.getCurrentInstance().addMessage("messagePanel", msg);
    }

    public static void erro(String mensagem) {

        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, recupera(mensagem), "");
        FacesContext.getCurrentInstance().addMessage("messagePanel", msg);
    }

    public static void alerta(String mensagem) {

        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, recupera(mensagem), "");
        FacesContext.getCurrentInstance().addMessage("messagePanel", msg);
    }

}

In this situation I need to pass a key only, etc. How can I do to accept pass parameters?

    
asked by anonymous 04.10.2016 / 23:38

1 answer

1

You will use the String.format for this. For example instead of using:

public static void sucesso(String mensagem) {

        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, recupera(mensagem), "");
        FacesContext.getCurrentInstance().addMessage("messagePanel", msg);
    }

You will write like this:

public static void sucesso(String mensagem, Object... parametros) {

        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, String.format(recupera(mensagem), parametros), "");
        FacesContext.getCurrentInstance().addMessage("messagePanel", msg);
    }

Just one more tip, you're repeating a lot of code in this class, see that success, error, and alert methods do almost the same thing, only by changing the severity level. You could have a private method that these methods would call, going beyond just the level.

    
05.10.2016 / 01:25