[ Team LiB ] |
![]() ![]() |
Recipe 24.5 Using the ResourceBundle in a ServletProblemYou want a servlet to dynamically display a "Welcome" message to visitors depending on their locale. SolutionUse the servlet to access the translated text dynamically from a ResourceBundle. DiscussionOnce you have added ResourceBundles to the web application, then servlets can use them to dynamically display text based on the user's locale.
Example 24-6 uses a ResourceBundle with a basename of "WelcomeBundle." It is stored in WEB-INF/i18n, so its fully qualified name is i18n.WelcomeBundle. Example 24-6. A servlet uses a to dynamically display translated textpackage com.jspservletcookbook; import java.util.Locale; import java.util.ResourceBundle; import javax.servlet.*; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { //Get the client's Locale Locale locale = request.getLocale( ); ResourceBundle bundle = ResourceBundle.getBundle( "i18n.WelcomeBundle",locale); String welcome = bundle.getString("Welcome"); //Display the locale response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter( ); out.println("<html><head><title>"+welcome+"</title></head><body>"); out.println("<h2>"+welcome+"</h2>"); out.println("Locale: "); out.println( locale.getLanguage( )+"_"+locale.getCountry( ) ); out.println("</body></html>"); } //end doGet // doPost method ... }//WelcomeServlet Here is how the application uses this resource in response to a visitor from a Spanish locale ("es_ES"):
Figure 24-3 shows the servlet's output in response to a request from a Spanish locale. Figure 24-3. A Spanish client requests the LocaleServlet![]() Figure 24-4 shows the servlet's response when it deals with a locale for which the application has not provided a resource. In this case, the browser is set for the Japanese language, but the application has not yet provided a resource for this locale. Figure 24-4. A browser set for Japanese visits receives the default message![]() The text that the browser displays derives from the default properties file: WelcomeBundle.properties (notice the absence of any locale-related suffix in the filename). See AlsoRecipe 24.6 on using the ResourceBundle in a JSP; The Javadoc for ResourceBundle: http://java.sun.com/j2se/1.4.1/docs/api/java/util/ResourceBundle.html. |
[ Team LiB ] |
![]() ![]() |