Java實現Web操作介面以及返回資料的翻譯

滄海一粟i°發表於2018-12-17

Java實現Web系統翻譯

本文章為通過百度API實現Web專案的介面以及返回資料的翻譯

Spring專案下通過Filter實現翻譯:

Alt
前端請求頭:

 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 {


    @Override
    protected 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);
    }

    @Override
    public ServletOutputStream getOutputStream()
            throws IOException
    {
        return out;
    }

    @Override
    public 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;
        }

        @Override
        public void write(int b)
                throws IOException
        {
            bos.write(b);
        }

        @Override
        public boolean isReady()
        {

            // TODO Auto-generated method stub
            return false;

        }

        @Override
        public 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);
            }
        } else
        if (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會有點慢,可以改為多執行緒去請求。

相關文章