Accept Language and Accept Char set in Servlets

This section illustrates you the use of Accept Language and Accept Char set.

Accept Language and Accept Char set in Servlets

Accept Language and Accept Char set in Servlets

     

This section illustrates you the use of Accept Language and Accept Char set.

Accept Language and Accept Char set provides a servlets to determine the language in which it will speak to the clients. A browser sends the user's language to the server using the Accept Language HTTP header. The value of the header specifies the language that the client will receive. The value of an Accept Language Header will be like: en, ja, de, etc. These indicates the languages English, Japanese, German respectively. And the client understands the language.

Each Language consists of q-value. It is an estimate of the user preference for the language. Default value of q-value is 1.0 which is (maximum). Now the Accept Language Header with q-value will be: en:q-0.5, ja:q-0.3, de:q-0.7, etc. 

With the Accept Language header, the browser sends Accept Char set header which tells the server which char set it understands. Its header value will be given like: ISO-8859-1, utf-8. The browser understands it. If its value hasn't sent or it contains *, it means client accepts all char sets. Now this can be explained with an example.

Here is the code of AcceptCharset.java

import java.io.IOException;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AcceptCharset extends HttpServlet {

  public void doGet(HttpServletRequest request,
 HttpServletResponse response)
  throws ServletException,IOException {
  response.setContentType("text/html");
  PrintWriter out= response.getWriter();
  String acceptLanguage = request.getHeader("Accept-Language");
  String acceptCharset = request.getHeader("Accept-Charset");
  out.println("<html><head><title>Accept Language and 
  Accept Charset</title>
  </head></html>");
  out.println("<h2>Accept Language and Accept Charset</h2>");
  out.println("AcceptLanguage: " + acceptLanguage+"<br>");
  out.println("AcceptCharset" + acceptCharset);
  }
}

In web.xml, do the servlet mapping.

<servlet>
<servlet-name>
AcceptCharset</servlet-name>
<servlet-class>AcceptCharset</servlet-class>
</servlet>


<servlet-mapping>
<servlet-name>
AcceptCharset</servlet-name>
<url-pattern>/AcceptCharset</url-pattern>
</servlet-mapping>

In the above example, acceptLanguage and acceptCharset are declared as a variable of string type and passed them to the HTTP header. The browser sends the language and charset using request.getHeader("Accept-Language"), request.getHeader("Accept-Charset"). After compilation, run the tomcat. This will display the language and charset on the browser.

Here is the output.

Download code of the example