Filtering page to UTF-8 : Filter « Servlets « Java






Filtering page to UTF-8

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

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

public class UTF8 extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    try {
      BufferedReader reader = req.getReader();

      res.setContentType("text/html; charset=UTF-8");
      PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);

      // Read and write 4K chars at a time
      // (Far more efficient than reading and writing a line at a time)
      char[] buf = new char[4 * 1024]; // 4Kchar buffer
      int len;
      while ((len = reader.read(buf, 0, buf.length)) != -1) {
        out.write(buf, 0, len);
      }
      out.flush();
    } catch (Exception e) {
      getServletContext().log(e, "Problem filtering page to UTF-8");
    }
  }
}

           
         
  








Related examples in the same category

1.Response Filter
2.Servlets Post Filter Demo
3.Servlets Logging Filter Demo
4.Another Filter Demo
5.Servlets CSV Filter Demo
6.Servlets SortFilter Demo
7.Filter Using Parameter
8.Jsp Using Chained Filter
9.Logging Filter
10.Restricting Filter
11.Filter that performs filtering based on comparing the appropriate request
12.JNDI Filter
13.Email JNDI Filter
14.Send filter
15.Log Filter
16.IP Filter
17.Block Filter
18.Checker Filter
19.Servlet : session filter
20.Parameter Filter
21.HTML filter utility
22.Compression Filter
23.Request Filter
24.Filter message string for characters that are sensitive in HTML
25.Filter that wraps an HttpServletRequest to override "isUserInRole".
26.Filter the specified message string for characters that are sensitive in HTML
27.Cache Filter