Using One Page for Multiple Locales

Example 14-1 shows the poll.jsp page. That’s where the magic of locale selection happens, and the selection is then used to produce text in the corresponding language throughout the page.

Example 14-1. Language selection and vote page (poll.jsp)
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%-- 
  Set the locale to the selected one, if any. Otherwise, let the
  <fmt:setBundle> action pick the best one based on the Accept-Language
  header.
--%>
<c:if test="${param.language == 'en'}">
  <fmt:setLocale value="en" scope="session" />
</c:if>
<c:if test="${param.language == 'sv'}">
  <fmt:setLocale value="sv" scope="session" />
</c:if>
<c:if test="${param.language == 'de'}">
  <fmt:setLocale value="de" scope="session" />
</c:if>
<fmt:setBundle basename="pages" var="pagesBundle" />
<fmt:setBundle basename="labels" scope="session" />
<html>
  <head>
    <title>
      <fmt:message key="title" />
    </title>
  </head>
  <body bgcolor="white">
    <h1>
      <fmt:message key="title" />
    </h1>
  
    <fmt:message key="select_language" />: <form action="poll.jsp"> <p> <c:set var="currLang" value="${pagesBundle.locale.language}" /> <input type="radio" name="language" value="en" ${currLang == 'en' ? 'checked' : ''}> <fmt:message key="english" /><br> <input type="radio" name="language" value="sv" ${currLang == 'sv' ? 'checked' : ''}> <fmt:message key="swedish" /><br> <input type="radio" ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.