Developing I18N Applications in JSF

Ratings:
(4.2)
Views: 782
Banner-Img
Share this blog:

Screenshot_17   

Abc-en-us.properties:

welcome.message=Welcome to the English US version.

Abc-it-IT.properties:

welcome.message=Benvenuti alla versione italiana.

Abc-it-IN.properties:

welcome.message=Benvenuti alla versione indiana.

FORM.HTML:

<html>
  <body>
    <form method="post" action="/i18n">
      <table>
        <tr>
          <td>Select language:</td>
          <td>Select country:</td>
        </tr>
        <tr>
          <td>
            <select name="language">
              <option value="en">English</option>
              <option value="it">Italian</option>
              <option value="hi">Hindi</option>
            </select>
          </td>
          <td>
            <select name="country">
              <option value="us">United States</option>
              <option value="it">Italy</option>
              <option value="in">India</option>
            </select>
          </td>
        </tr>
        <tr>
          <td>
            <input type="submit" value="Submit">
          </td>
        </tr>
      </table>
    </form>
  </body>
</html>

I18NServlet.java:

package com.soft;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/i18n")
public class I18NServlet extends HttpServlet {

  private static final String BUNDLE_NAME = "Abc";
  private static final String WELCOME_MESSAGE_KEY = "welcome.message";
  private static final String HTML_START = "<html><body><h1>";
  private static final String HTML_END = "</h1></body></html>";

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
      String language = request.getParameter("language");
      String country = request.getParameter("country");
      Locale locale = new Locale(language, country);

      NumberFormat numberFormat = NumberFormat.getInstance(locale);
      DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
      ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME, locale);

      String welcomeMessage = bundle.getString(WELCOME_MESSAGE_KEY);

      PrintWriter out = response.getWriter();
      out.println(HTML_START);
      out.println("Number: " + numberFormat.format(1345.2345) + "<br>");
      out.println("Date: " + dateFormat.format(new Date()) + "<br>");
      out.println("Message: " + welcomeMessage);
      out.println(HTML_END);
    } catch (Exception e) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
    }
  }
}
  • If we use the above approach to provid II8N Support then every time user has to specify lang country, it is not suggestible in web applications.
  • To overcome the above problems, we have to provide I18N Support with out depending on the user, by getting client browser provided language setup
  • When we submit a request from a client browser then browser provided lang will be send to server in the from at “accept lang” request header, here it we get “accept-language” request header value then it is possible to identify from which local the request is coming, with this, we are able to provide I18N Support without specifying lang & country by the user
  • To get a particular request header value, we have to use the following method from servlet request, public string get header (String header-name)
  • Public class I18N Servlet extends Http servlet{ = IL; Protected void do Get(Http Servlet Request request, Http Servlef Response response) Throws servlet Exception, Ioexception{

Try{ String locate=request. get header(“accept-language”);

String Tokenizer st= new string tokenizer(local, “-”);

Int count= st. count tokens();

Local i=null;

If (count==1){ String long=st.next token();

I=new locale (c lang);

{ If(count==2){ String lang=st. next token();

String country=st. next token();

I=new locale (c lang, country); }

If(count==3){ String lang=st. next token();

String country=st.

next token();

String sys-var=st.

next token();

I=new locale (lang, country), sys-var); }

Number Format

nt=number formal,

get Insurance(l);

  Screenshot_18  

Abc-en. properties

# English language properties file
# Header
Header1 = Durga Software Solutions
Header2 = Registration Form

# Form fields
Sid = Student ID
Sname = Student Name
Semail = Email ID
Smobile = Contact No.

# Button
Button = Register

# Success and failure messages
Success = Student registration successful
Failure = Student registration failed

 Abc-it. Properties

Header1=Durga software solutions Header2=Registration Form Sid=student Id Sname=student Name Semail=email id Smobile=contact no Button=registration Success=student registration success Failure=student registration failure  

Abc-te. Properties

Header1=software solutions
Header2=Darakstu patram
Sid=vidyardu Gurdimpu snkya
Sname=vidyardi peru
Semail=vidyuth samachara Gurthimlu
Smobile=sampradimpu sankya
Button=Darakasthu
Success=Vidyardi Darakastu safalamayinadhi
Failure=Vidyardi Darakastu cifalamayinadhi

Index.html 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Refresh" content="2;URL=http://localhost:1010/I18napp/registrationform.dss">
        <title>Insert title here</title>
    </head>
    <body>
        <h1>Application is loading…</h1>
    </body>
</html>

Registrationform.JSP

  

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
  </head>
  <body>
    <f:view>
      <h:form>
        <h:panelGrid columns="2">
          <h:outputText value="#{msg.sid}" />
          <h:inputText id="sid" value="#{regBean.sid}" />
          <h:outputText value="#{msg.sname}" />
          <h:inputText id="sname" value="#{regBean.sname}" />
          <h:outputText value="#{msg.semail}" />
          <h:inputText id="semail" value="#{regBean.semail}" />
          <h:outputText value="#{msg.smobile}" />
          <h:inputText id="smobile" value="#{regBean.smobile}" />
          <h:commandButton value="#{msg.button}" action="#{regBean.registration}" />
        </h:panelGrid>
      </h:form>
    </f:view>
  </body>
</html>

Success. Jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <f:view>
         <h1><h:outputText value="#{msg.success}" /></h1>
      </f:view>
   </body>
</html>

Failure.jsp

<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Failure Page</title>
</head>
<body>
    <f:view>
        <h1><h:outputText value="#{msg.failure}" /></h1>
    </f:view>
</body>
</html>

Registration Bean.java

package com.soft;

import java.util.Locale;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

public class RegistrationBean {
    private String sid;
    private String sname;
    private String semail;
    private String smobile;

    // getters and setters

    public String registration() {
        String status = "";
        if (sid.startsWith("DSS-")) {
            status = "success";
        } else {
            status = "failure";
        }
        return status;
    }

    public String getRegistrationForm() {
        return "Registration form";
    }
}

Faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<Faces-config xmlns="http://Java.sun.com/xml/ns/java" version="1.2">
    <managed-bean>
        <managed-bean-name>regBean</managed-bean-name>
        <managed-bean-class>com.DurgaSoft.RegistrationBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/registrationform.jsp</from-view-id>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/success.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-outcome>failure</from-outcome>
            <to-view-id>/failure.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/menu.jsp</from-view-id>
        <navigation-case>
            <from-outcome>registration form</from-outcome>
            <to-view-id>/registrationform.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
    <application>
        <locale-config>
            <default-locale>en</default-locale>
            <supported-locale>it</supported-locale>
            <supported-locale>te</supported-locale>
        </locale-config>
        <resource-bundle>
            <base-name>abc</base-name>
            <var>msg</var>
        </resource-bundle>
    </application>
</Faces-config>

Web.xml

Same as prev. applications.      

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox