1 package com.tonbeller.wcf.charset; 2 3 import java.io.IOException ; 4 import java.io.UnsupportedEncodingException ; 5 import java.net.URLEncoder ; 6 7 import javax.servlet.Filter ; 8 import javax.servlet.FilterChain ; 9 import javax.servlet.FilterConfig ; 10 import javax.servlet.ServletException ; 11 import javax.servlet.ServletRequest ; 12 import javax.servlet.ServletResponse ; 13 import javax.servlet.http.HttpServletResponse ; 14 15 import org.apache.log4j.Logger; 16 17 import com.tonbeller.tbutils.res.Resources; 18 19 25 public class CharsetFilter implements Filter { 26 27 private static final Logger logger = Logger.getLogger(CharsetFilter.class); 28 private static final String ISO88591 = "iso-8859-1"; 29 private static final String UTF8 = "utf-8"; 30 31 private static String encoding = ISO88591; 32 private String contentType = null; 33 34 public void init(FilterConfig fc) throws ServletException { 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 55 public static String getEncoding() { 56 return encoding; 57 } 58 59 62 public static String urlEncode(String s) { 63 try { 64 return URLEncoder.encode(s, encoding); 65 } catch (UnsupportedEncodingException e) { 66 logger.error(null, e); 67 return s; 68 } 69 } 70 71 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 72 throws IOException , ServletException { 73 if (req.getCharacterEncoding() == null) 75 req.setCharacterEncoding(encoding); 76 res = new CharsetResponse((HttpServletResponse ) res, contentType, encoding); 77 chain.doFilter(req, res); 78 } 79 80 } 81 | Popular Tags |