本文主要是介绍Java实现Web操作界面以及返回数据的翻译,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Java实现Web系统翻译
本文章为通过百度API实现Web项目的界面以及返回数据的翻译
Spring项目下通过Filter实现翻译:
前端请求头:
requestHeader:{System-System-Language:en,Data-Language:en
}
拦截器注册(springmvc版)
<!--设置语言--><filter><filter-name>Set Language</filter-name><filter-class>myProgram.filter.TranslateFilter</filter-class><async-supported>true</async-supported><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>Set Language</filter-name><url-pattern>/*</url-pattern></filter-mapping><!----><!-- 设置servlet编码开始 --><filter><filter-name>Set Character Encoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><async-supported>true</async-supported><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>Set Character Encoding</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 设置servlet编码结束 -->
过滤器具体实现(来自西门吹水_)
package myProgram.filter;import com.alibaba.druid.util.StringUtils;
import myProgram.utils.TranslateUtil;
import org.springframework.web.filter.OncePerRequestFilter;import java.io.IOException;
import java.nio.charset.StandardCharsets;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class TranslateFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {ResponseWrapper wrapperResponse = new ResponseWrapper(response);filterChain.doFilter(request, wrapperResponse);byte[] content = wrapperResponse.getContent();//获取返回值//判断是否有值if (content.length > 0) {String systemLanguage = request.getHeader("System-Language");String dataLanguage = request.getHeader("Data-Language");String str = new String(content, StandardCharsets.UTF_8);String ciphertext = null;try {StringBuffer stringBuffer = null;if (!StringUtils.isEmpty(dataLanguage)) {
// 异步请求数据翻译stringBuffer = new StringBuffer(str);TranslateUtil.translateJsonValues(stringBuffer, str, dataLanguage);} else if (!StringUtils.isEmpty(systemLanguage)) {
// 页面翻译stringBuffer = new StringBuffer(TranslateUtil.translateWebFile(str, systemLanguage));}ciphertext = String.valueOf(stringBuffer);if(StringUtils.isEmpty(ciphertext)) ciphertext=str;//......根据需要处理返回值} catch (Exception e) {e.printStackTrace();ciphertext=str;}//把返回值输出到客户端ServletOutputStream out = response.getOutputStream();
// assert ciphertext != null;out.write(ciphertext.getBytes(StandardCharsets.UTF_8));out.flush();}}}
ResponseWrapper
package myProgram.filter;import java.io.ByteArrayOutputStream;
import java.io.IOException;import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;public class ResponseWrapper extends HttpServletResponseWrapper
{private ByteArrayOutputStream buffer;private ServletOutputStream out;public ResponseWrapper(HttpServletResponse httpServletResponse){super(httpServletResponse);buffer = new ByteArrayOutputStream();out = new WrapperOutputStream(buffer);}@Overridepublic ServletOutputStream getOutputStream()throws IOException{return out;}@Overridepublic void flushBuffer()throws IOException{if (out != null){out.flush();}}public byte[] getContent()throws IOException{flushBuffer();return buffer.toByteArray();}class WrapperOutputStream extends ServletOutputStream{private ByteArrayOutputStream bos;public WrapperOutputStream(ByteArrayOutputStream bos){this.bos = bos;}@Overridepublic void write(int b)throws IOException{bos.write(b);}@Overridepublic boolean isReady(){// TODO Auto-generated method stubreturn false;}@Overridepublic void setWriteListener(WriteListener arg0){// TODO Auto-generated method stub}}}
百度API实现翻译
package myProgram.utils;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import myProgram.util.TransApi;import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class TranslateUtil {static final String APP_ID = "";static final String SECURITY_KEY = "";
/*** @author:沧海一粟* @method transByBaiDu* @param query 翻译语句* @param to 目标语言* @return * @date: 2018/12/17 12:27* @description 通过百度API实现语句翻译*/private static String transByBaiDu(String query, String to) {TransApi api = new TransApi(APP_ID, SECURITY_KEY);String tranResultStr = (api.getTransResult(query, "auto", to));JSONObject tranResult = (JSONObject) JSON.parse(((JSONArray) ((JSONObject) JSON.parse(tranResultStr)).get("trans_result")).getString(0));return String.valueOf((tranResult.get("dst")));}
/*** @author:沧海一粟* @method translateJsonValues* @param result StringBuffer类型对象 new StringBuffer(jsons);* @param jsons JSON类型字符串* @param targetLanguage 目标语言类型* @return * @date: 2018/12/17 12:29* @description 翻译JSON字符串的值* @QQ:*/public static void translateJsonValues(StringBuffer result, String jsons, String targetLanguage){if (jsons.startsWith("[")) {
// json数组JSONArray jsonArray = JSON.parseArray(jsons);for (Object aJsonArray : jsonArray) {String str = String.valueOf(aJsonArray);translateJsonValues(result, str, targetLanguage);}} elseif (jsons.startsWith("{")) {
// json对象JSONObject jsonObject = JSON.parseObject(jsons);for (Object o : jsonObject.entrySet()) {String str = String.valueOf((o));str = (str.substring(str.indexOf("=") + 1));translateJsonValues(result, str, targetLanguage);}} else {
// 基本类型开始翻译if(hasChinese(jsons)) {String resultStr = transByBaiDu(jsons, targetLanguage);String str=result.toString();result.delete(0,result.length());result.append(str.replaceAll(jsons, resultStr));}}}
/*** @author:沧海一粟* @method translateWebFile* @param fileContent web文件内容* @param targetLanguage 目标语言* @return* @date: 2018/12/17 13:06* @description 翻译前端文件**/public static String translateWebFile(String fileContent,String targetLanguage) {
// 匹配HTML以及JS文件中的中文Pattern p=Pattern.compile(">(.*?)<|\"(.*?)\"");Matcher m=p.matcher(fileContent);while(m.find()){String str = m.group().trim();if (!str.equals("")) {if(hasChinese(str)) {str=str.substring(1,str.length()-1).trim();fileContent=fileContent.replaceFirst(str,transByBaiDu(str,targetLanguage));}}}return (fileContent);}/*** @author:沧海一粟* @method hasChinese* @param str* @return* @date: 2018/12/17 12:31* @description 判断字符串中是否包含中文* @*/private static boolean hasChinese(String str) {Pattern p = Pattern.compile("[\u4e00-\u9fa5]");Matcher m = p.matcher(str);if (m.find()) {return true;}return false;}}
TranApi
package myProgram.util;import java.util.HashMap;
import java.util.Map;public class TransApi {private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";private String appid;private String securityKey;public TransApi(String appid, String securityKey) {this.appid = appid;this.securityKey = securityKey;}public String getTransResult(String query, String from, String to) {Map<String, String> params = buildParams(query, from, to);return HttpGet.get(TRANS_API_HOST, params);}private Map<String, String> buildParams(String query, String from, String to) {Map<String, String> params = new HashMap<String, String>();params.put("q", query);params.put("from", from);params.put("to", to);params.put("appid", appid);// 随机数String salt = String.valueOf(System.currentTimeMillis());params.put("salt", salt);// 签名String src = appid + query + salt + securityKey; // 加密前的原文params.put("sign", MD5.md5(src));return params;}}
以上内容便可以实现前端的翻译了,但是数量比较大时轮流请求百度API会有点慢,可以改为多线程去请求。
这篇关于Java实现Web操作界面以及返回数据的翻译的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!