KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > charset > CharsetFilter


1 package com.tonbeller.wcf.charset;
2
3 import java.io.IOException JavaDoc;
4 import java.io.UnsupportedEncodingException JavaDoc;
5 import java.net.URLEncoder JavaDoc;
6
7 import javax.servlet.Filter JavaDoc;
8 import javax.servlet.FilterChain JavaDoc;
9 import javax.servlet.FilterConfig JavaDoc;
10 import javax.servlet.ServletException JavaDoc;
11 import javax.servlet.ServletRequest JavaDoc;
12 import javax.servlet.ServletResponse JavaDoc;
13 import javax.servlet.http.HttpServletResponse JavaDoc;
14
15 import org.apache.log4j.Logger;
16
17 import com.tonbeller.tbutils.res.Resources;
18
19 /**
20  * sets the ServletRequest.setCharacterEncoding to UTF-8.
21  *
22  * @author av
23  * @since 18.05.2005
24  */

25 public class CharsetFilter implements Filter JavaDoc {
26
27   private static final Logger logger = Logger.getLogger(CharsetFilter.class);
28   private static final String JavaDoc ISO88591 = "iso-8859-1";
29   private static final String JavaDoc UTF8 = "utf-8";
30
31   private static String JavaDoc encoding = ISO88591;
32   private String JavaDoc contentType = null;
33
34   public void init(FilterConfig JavaDoc fc) throws ServletException JavaDoc {
35     Resources res = Resources.instance();
36     encoding = res.getOptionalString("tbeller.charset", null);
37     if (encoding == null)
38       encoding = fc.getInitParameter("encoding");
39     if (encoding == null)
40       encoding = UTF8;
41     logger.info("setting encoding to " + encoding);
42     
43     contentType = fc.getInitParameter("contentType");
44   }
45
46   public void destroy() {
47     logger.info("setting encoding back to ISO-8859-1");
48     encoding = ISO88591;
49   }
50
51   /**
52    * returns the encoding for the URLEncoder.
53    * @return "utf-8" when the filter was installed in web.xml, "iso8859-1" otherwise.
54    */

55   public static String JavaDoc getEncoding() {
56     return encoding;
57   }
58   
59   /**
60    * encodes s into utf-8 if the filter is installed, into iso-8859-1 else
61    */

62   public static String JavaDoc urlEncode(String JavaDoc s) {
63     try {
64       return URLEncoder.encode(s, encoding);
65     } catch (UnsupportedEncodingException JavaDoc e) {
66       logger.error(null, e);
67       return s;
68     }
69   }
70
71   public void doFilter(ServletRequest JavaDoc req, ServletResponse JavaDoc res, FilterChain JavaDoc chain)
72       throws IOException JavaDoc, ServletException JavaDoc {
73     // if no "content-type" header was sent, we assume utf-8
74
if (req.getCharacterEncoding() == null)
75       req.setCharacterEncoding(encoding);
76     res = new CharsetResponse((HttpServletResponse JavaDoc) res, contentType, encoding);
77     chain.doFilter(req, res);
78   }
79
80 }
81
Popular Tags