現(xiàn)在很多公司網(wǎng)站需要簡(jiǎn)體版、繁體版和英文版,英文版需要特別翻譯,而繁體版一般采用JS翻譯或者程序替換來(lái)翻譯,因?yàn)榉斌w和簡(jiǎn)體不一樣的大概有2300多個(gè),字體大小一樣,完全可以通過(guò)程序替換。
JS繁體和程序替換翻譯,兩者對(duì)比,程序翻譯體驗(yàn)度更好,JS翻譯,會(huì)有個(gè)翻譯的動(dòng)作,影響用戶體驗(yàn)。下面方維網(wǎng)絡(luò)介紹JAVA開(kāi)發(fā)的程序如何實(shí)現(xiàn)一段代碼來(lái)替換簡(jiǎn)繁體。
主要采用Filter來(lái)實(shí)現(xiàn),在頁(yè)面輸出結(jié)果前對(duì)輸出內(nèi)容進(jìn)行攔截,然后替換文字,替換相關(guān)URL,然后再輸出。代碼如下:
@WebFilter(urlPatterns = "/zh/*",filterName = "ResponseFilter")
public class ResponseFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String url = req.getRequestURI();
if(url.startsWith("/zh/")) {//只攔截繁體版
UrlResponseWrapper wrapperResponse = new UrlResponseWrapper((HttpServletResponse) response);//轉(zhuǎn)換成代理類
// 這里只攔截返回,直接讓請(qǐng)求過(guò)去,如果在請(qǐng)求前有處理,可以在這里處理
filterChain.doFilter(request, wrapperResponse);
String content_type = wrapperResponse.getContentType();
byte[] content = wrapperResponse.getResponseData();
if(content_type != null && content_type.equals("text/html;charset=UTF-8")) {
String str = new String(content);
//替換繁體
String str_zh = ChineseUtils.toZh(str);
str_zh = str_zh.replace("href=\"/news/", "href=\"/zh/news/");
str_zh = str_zh.replace("href=\"/about/", "href=\"/zh/about/");
str_zh = str_zh.replace("href=\"/investor/", "href=\"/zh/investor/");
str_zh = str_zh.replace("href=\"/responsibility/", "href=\"/zh/responsibility/");
str_zh = str_zh.replace("href=\"/product/", "href=\"/zh/product/");
content = str_zh.getBytes();
ServletOutputStream out = response.getOutputStream();
out.write(content);
out.flush();
} else {
filterChain.doFilter(request, response);
}
} else {
filterChain.doFilter(request, response);
}
}
}