Make your own dictionary using Baidu translate api

First of all, this is a java web project. So we are going to create a web project and use the tool eclipse.

write picture description here

After the project is created, create css and js folders under WebContent to store static resource files, and create a new jsp page under WebContent for translation.
write picture description here

The front desk is very scumbag, so I won't be ugly. One thing to remember is that in general, use the link tag to import css files, and use script to import js files. This is my front page page, copied from Baidu translation (abbreviated version), After all, I'm not trying to be a Baidu

write picture description here

  1. This is the jsp source code

    index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>百度翻译</title>

<script type="text/javascript" src="js/jquery-3.2.1.js"></script>

<link rel="icon" type="image/png"
    href="//fanyi.bdstatic.com/static/translation/img/favicon/favicon-32x32_ca689c3.png"
    sizes="32x32" />
<link rel="icon" type="image/png"
    href="//fanyi.bdstatic.com/static/translation/img/favicon/favicon-16x16_e1883cf.png"
    sizes="16x16" />
<link rel="shortcut icon" type="image/x-icon"
    href="//fanyi.bdstatic.com/static/translation/img/favicon/favicon_d87cd2a.ico" />
<link rel="bookmark" type="image/x-icon"
    href="//fanyi.bdstatic.com/static/translation/img/favicon/favicon_d87cd2a.ico" />

<link rel="stylesheet" type="text/css" href="./css/main.css">   

</head>
<body>
    <img class="img_baidu"
        src="//fanyi.bdstatic.com/static/translation/img/header/logo_cbfea26.png"
        alt="" />
    <br />
    <div class="div_body"></div>
    <br />
    <div class="div_from">
        <select id="from">
            <option value="auto">   自动检测    </option>
            <option value="zh"> 中文  </option>
            <option value="en"> 英语  </option>
            <option value="yue">    粤语  </option>
            <option value=" wyw">   文言文 </option>
            <option value=" jp  ">  日语  </option>
            <option value=" kor ">  韩语  </option>
            <option value=" fra ">  法语  </option>
            <option value=" spa ">  西班牙语    </option>
            <option value=" th  ">  泰语  </option>
            <option value=" ara ">  阿拉伯语    </option>
            <option value=" ru  ">  俄语  </option>
            <option value=" pt  ">  葡萄牙语    </option>
            <option value=" de  ">  德语  </option>
            <option value=" it  ">  意大利语    </option>
            <option value=" el  ">  希腊语 </option>
            <option value=" nl  ">  荷兰语 </option>
            <option value=" pl  ">  波兰语 </option>
            <option value=" bul ">  保加利亚语   </option>
            <option value=" est ">  爱沙尼亚语   </option>
            <option value=" dan ">  丹麦语 </option>
            <option value=" fin ">  芬兰语 </option>
            <option value=" cs  ">  捷克语 </option>
            <option value=" rom ">  罗马尼亚语   </option>
            <option value=" slo ">  斯洛文尼亚语  </option>
            <option value=" swe ">  瑞典语 </option>
            <option value=" hu  ">  匈牙利语    </option>
            <option value=" cht ">  繁体中文    </option>
            <option value=" vie ">  越南语 </option>
        </select>
    </div>
    <div class="div_to">
        <select id="to">
            <option value=" zh  ">  中文  </option>
            <option value=" en  ">  英语  </option>
            <option value=" yue ">  粤语  </option>
            <option value=" wyw ">  文言文 </option>
            <option value=" jp  ">  日语  </option>
            <option value=" kor ">  韩语  </option>
            <option value=" fra ">  法语  </option>
            <option value=" spa ">  西班牙语    </option>
            <option value=" th  ">  泰语  </option>
            <option value=" ara ">  阿拉伯语    </option>
            <option value=" ru  ">  俄语  </option>
            <option value=" pt  ">  葡萄牙语    </option>
            <option value=" de  ">  德语  </option>
            <option value=" it  ">  意大利语    </option>
            <option value=" el  ">  希腊语 </option>
            <option value=" nl  ">  荷兰语 </option>
            <option value=" pl  ">  波兰语 </option>
            <option value=" bul ">  保加利亚语   </option>
            <option value=" est ">  爱沙尼亚语   </option>
            <option value=" dan ">  丹麦语 </option>
            <option value=" fin ">  芬兰语 </option>
            <option value=" cs  ">  捷克语 </option>
            <option value=" rom ">  罗马尼亚语   </option>
            <option value=" slo ">  斯洛文尼亚语  </option>
            <option value=" swe ">  瑞典语 </option>
            <option value=" hu  ">  匈牙利语    </option>
            <option value=" cht ">  繁体中文    </option>
            <option value=" vie ">  越南语 </option>
        </select> &nbsp; &nbsp; &nbsp; 
        <input type="button" value="翻译" id="but_Trans"><br />
    </div><br />

    <textarea id="query" onclick="this.value='';focus()">此处为输入翻译的内容</textarea>
    <textarea id="result" readonly="readonly"></textarea>
    </div>
</body>
<script type="text/javascript">
        $(function(){
            $("#but_Trans").click(function(){
                var query = $("#query").val();
                var from = $("#from").val();
                var to = $("#to").val();
                $.ajax({
                    url:"/Trans/trans",
                    type:"POST",
                    data:{query:query,from:from,to:to},
                    success:function(result){
                        var json = $.parseJSON(result);
                        var dst = "";
                        for (var i = 0; i < json.trans_result.length; i++) {
                            dst += json.trans_result[i].dst; + "<br/>"
                        }
                        $("#result").html(dst);
                    }
                }); 
            });
        });
    </script>
</html>

Use ajax to make front and back calls. The main parameters are from (automatic recognition area), to (language you want to translate into), query (sentence you want to translate), here is a little trick, there are many options in select, All I used the quickness of excel to copy, and then the font and language were copied in the Baidu translation api document. If you want to use the Baidu translation function, you must also register in the api before you can use it. This is the path ( http:// api.fanyi.baidu.com/api/trans/product/apidoc ), the specific effect is as follows: write picture description here
is it very simple! ^_^

Next is the specific java code. First of all, download the apiDEMO provided by Baidu, the download address is still the above path, at first I thought it would be something similar to a jar package, BUT, it is actually the java source code, hahaha, no Wrong, it's the java file ....

write picture description here

For me, for the module and layering of the project (actually just a translation), my project structure is like this, add the downloaded java file to the project, at the same time the controller transmits data, and util translates (equivalent to a dao, but it is not an interface, its function is to return the result, the specific translation implementation is implemented by the file under the api), and then in the config directory, I use it to store my appid and key.

write picture description here

TransUtil.java

import java.util.ResourceBundle;

import songyu.li.api.TransApi;

public class TransUtil {

    public final static  String APP_ID ;
    public final static  String SECRET_KEY;

    static {
        ResourceBundle rb = ResourceBundle.getBundle("api_config");
        APP_ID = rb.getString("APP_ID");
        SECRET_KEY = rb.getString("SECRET_KEY");
    }

    public static String getResult(String query , String from , String to) {
        TransApi api = new TransApi(APP_ID, SECRET_KEY);
        return api.getTransResult(query, from, to);
    }


}

ps: Read the configuration file api_config.properties under config through ResourceBundle, and then statically load it into the constant. (The config file will not be displayed, after all, the appid and key are still private)

TransController.java



import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xxxx.xxxx.utils.TransUtil;

/**
 * 翻译Controller 前台ajax传过来的值通过@webservlet("/trans")进入Controller
 *
 * @ClassName : TransController
 * @Description : TODO(这里是对当前类的描述)
 * @author : 
 * @date : 2018年3月23日下午3:11:04
 *
 */
@WebServlet("/trans")
public class TransController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String query = req.getParameter("query");
        String from = req.getParameter("from");
        String to = req.getParameter("to");
        String result = TransUtil.getResult(query, from.trim(), to.trim());
        resp.getWriter().println(result);
    }

}

ps: controller inherits HttpServlet, rewrites the dopost method, and obtains the value of the parameter through req.getParameter("name") (note: when getting the name, since I copied it from excel, all the data There are \t before and after the data, and the received values ​​have spaces. At this time, the trim() method of String is used, which is used to remove the spaces before and after the data.), through resp.getWriter().println( result) to return to ajax, a string is returned by default, you need to parse the string into json in the foreground and then take out the data. The following is the data in String format returned by default.
write picture description here

Specific source code: https://github.com/LeeSongYu/Trans (go to the config directory version)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325482959&siteId=291194637