? ? ? ? ? 今天调研一个任务,基于java的filter实现繁体到简体的转换,于是写了一个demo,给各位博友奉上,欢迎批评指正。
? ? ? ? ?实现的思路是重载request的调取参数的几个方法,然后做下转换。
? ? ? ? ? 转换类用的是网上的ZHConverter,就不多讲了,看一个例子就好:
? ? ? ? ??
class="java">public class Test { public static void main(String[] args) throws Exception { // Instantiation will fetch the property file which load the Chinese character mappings ZHConverter converter = ZHConverter.getInstance(ZHConverter.SIMPLIFIED); String traditionalSrc = "有背光的機械式鍵盤"; String simplified = converter.convert(traditionalSrc); System.out.println(simplified); // Or String simplifiedSrc = "简体字"; String traditional = ZHConverter.convert(simplifiedSrc, ZHConverter.TRADITIONAL); System.out.println(traditional); } }
?
? ? ? ? ? ? 1. 首先实现一个filter
? ? ? ? ? ?
/** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // perform request filtering HttpServletRequest httpServletRequest = (HttpServletRequest) request; CharChangeHttpRequest requestWrapper = new CharChangeHttpRequest(httpServletRequest); // continue the filter chain chain.doFilter(requestWrapper, response); // perform response filtering }
?? ? ? ? ?
? ?2. 由于自己封装了HttpServletRequest, 下面是自己写的实现
? ? ? ?
public class CharChangeHttpRequest extends HttpServletRequestWrapper { public CharChangeHttpRequest(HttpServletRequest request) { super(request); } @Override public String[] getParameterValues(String name) { String[] value = super.getParameterValues(name); if(value == null){ return null; } else { String[] rValues = new String[value.length]; for(int i = 0; i < rValues.length; i++){ rValues[i] = convert(value[i]); } return rValues; } } @Override public String getParameter(String name) { String value = super.getParameter(name); if(value == null || value.length() == 0){ return value; } return convert(value); } private String convert(String value){ ZHConverter converter = ZHConverter.getInstance(ZHConverter.SIMPLIFIED); try { return converter.convert(new String(value.getBytes("iso-8859-1"),"utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } private String[] convert(String[] values){ String[] rValues = new String[values.length]; for(int i = 0; i < rValues.length; i++){ rValues[i] = convert(values[i]); } return rValues; } @Override public Map getParameterMap() { Map originMap = super.getParameterMap(); Map<String,String[]> newMap = new HashMap<String,String[]>(originMap); for (Iterator it = newMap.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); entry.setValue(convert((String[])entry.getValue())); } return Collections.unmodifiableMap(newMap); } }
? ? ??
? ? 由于时间有限,写的比较仓促,如有考虑不周情况,请大家批评指正。
?
? ? ? ?