自己写的一个繁体到简体的转换程序
编程技术  /  houtizong 发布于 3年前   71
今天调研一个任务,基于java的filter实现繁体到简体的转换,于是写了一个demo,给各位博友奉上,欢迎批评指正。
实现的思路是重载request的调取参数的几个方法,然后做下转换。
转换类用的是网上的ZHConverter,就不多讲了,看一个例子就好:
public class Test {public static void main(String[] args) throws Exception {// Instantiation will fetch the property file which load the Chinese character mappingsZHConverter 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);}@Overridepublic 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); }}
由于时间有限,写的比较仓促,如有考虑不周情况,请大家批评指正。
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接