Wednesday 13 August 2014

getLocales() : get all acceptable locales of the client

public Enumeration<Locale> getLocales()
Returns all the locales supported by the client in decreasing order starting with the preferred locale based on Accept-Language header. If the client request doesn't provide an Accept-Language header, this method returns an Enumeration containing one Locale, the default locale for the server.

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Enumeration;
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(urlPatterns = {"/GetAllLocales"})
public class GetAllLocales extends HttpServlet {

 @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{
        try(PrintWriter out = res.getWriter()){
            Enumeration<Locale> allLocale = req.getLocales();
            StringBuilder str = new StringBuilder("<br />");
            
            while(allLocale.hasMoreElements()){
                str.append(allLocale.nextElement() +"<br />");
            }
            out.println("<html><head><title>Preferred Locale</title></head>");
            out.println("<body><h1>Locales supported by client are : ");
            out.println(str +"</h1></body></html>");
        }
    }  
}

Sample Output



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment