For an example below message can be put in a properties file to be used in different places.
message=The user is not authorized for this operation.
Then you can use this in various places.
But what happens if you need to include the "username" of the user in to this message?
For an example if the username is "john", the message should be
"The user john is not authorized for this operation."
If the username is "tom", the message should be
"The user tom is not authorized for this operation."
In this kind of situations you can use a parametrized messages in your property file as below.
message = The user {0} is not authorized for this operation.
In the places where you use this message you can use java.text.MessageFormat class to replace the parameter with the proper value as below.
String message = properties.getProperty("message");
String formattedMessage = MessageFormat.format(message, "john");
String formattedMessage = MessageFormat.format(message, "john");
This will print
The user john is not authorized for this operation.
Similarly if you want you can have multiple parameters in the string.
String message = "The user {0} is not authorized for {1} operation.";
String formattedMessage = MessageFormat.format(message, "john", "billing");
System.out.println(formattedMessage);
String formattedMessage = MessageFormat.format(message, "john", "billing");
System.out.println(formattedMessage);
This will print
The user john is not authorized for billing operation.
No comments:
Post a Comment