How to provide multi language support through JSP/Servlet? How to include static data of different languages at run time on basis of language selected?
Released in 1999 by Sun Microsystems, JSP is similar to PHP and ASP, but uses the Java programming language.
The Model 2 architecture, as shown in Figure 3, integrates the use of both servlets and JSP pages. In this mode, JSP pages are used for the presentation layer, and servlets for processing tasks. The servlet acts as a controller responsible for processing requests and creating any beans needed by the JSP page.
Servlets are written in the Java language. JSPs on the other hand use a combination of HTML and Java. Eventually JSPs are converted into a pure Java servlet.
The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format.
In a "plain vanilla" JSP/Servlet application, the best solution is the JSTL fmt taglib. (just drop jstl-1.2.jar
in /WEB-INF/lib
) How to use it is covered in Oracle Java EE 5 tutorial part II chapter 7 and in this answer: How to internationalize a Java web application?.
If you're using a MVC framework such as Oracle JSF or Apache Struts, then you need to consult its specific documentation using keywords "internationalization" (i18n) or "localization" (l10n). In most cases they also provides specific tags for that, such as <f:loadBundle>
in case of JSF, which in turn is covered in Oracle Java EE 5 tutorial part II chapter 15.
Those i18n tags already checks the default language/locale by ServletRequest#getLocale()
(you don't need to do it "low-level" by checking the header as one suggested before --which would involve more work parsing the header as per the HTTP spec). You can let the user choose the language itself (dropdown?) and store it in the session scope and instruct those taglibs to use it. Here's an example with JSTL fmt taglib:
<fmt:setLocale value="${someSessionBean.locale}" />
..where ${someSessionBean.locale}
can return en
, en_US
, en_UK
, etc. Those are in turn used by the java.util.ResourceBundle
API to load the localized text (you don't need to create/load the ResourceBundle
itself, the taglibs already do that, just read the linked javadoc to learn a bit more about how it works).
If you want the language available as first pathinfo part of URL (such as http://example.com/en/
, which is best for SEO), then you can best use a Filter
for this which listens on /*
, checks the pathinfo, splits the language part from it, stores/compares it as/with session value and forwards the request without language part in pathinfo further to the desired front controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With