学习内容:学习JavaWeb(Day45)
1、有道翻译API使用json格式数据
2、JSONP
3、Ajax提交form表单
4、Web Uploader
1、有道翻译API使用json格式数据
(1)根据昨天学习的Ajax跨域操作,继续使用有道翻译API,用json数据格式传输数据。
使用的工具类不变
public class HttpReqUtil {
public static String getReq(String url) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);//url是传输来的有道翻译API
CloseableHttpResponse response1 = httpclient.execute(httpGet);
System.out.println(response1);
try {
HttpEntity entity1 = response1.getEntity();
//getContent()方法获得entity1的内容并返回一个输入流,
//IOUtils类属于commons.io.jar包,IOUtils的toString方法将输入流转化为字符串
String result = IOUtils.toString(entity1.getContent(),"UTF-8");
return result;
} finally {
response1.close();
}
}
}
创建servlet
String q = request.getParameter("q");
//url编码格式中不允许出现空格,需要把空格替换为20%
q = q.replace(" ","%20");
//使用的有道翻译API的数据格式doctype=json
String result = HttpReqUtil.getReq("http://fanyi.youdao.com/openapi.do?keyfrom=neverland&key=969918857&type=data&doctype=json&version=1.1&q=" + q);
//设置contentType为application/json,传输之后进行json解析
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(result);
out.flush();
out.close();
创建jsp页面
<body>
请输入要翻译的内容:<input type="text" id="cont"> <input type="button" value="翻译" id="btn">
<div id="result"></div>
<script type="text/javascript">
$(function(){
$("#btn").click(function (){
//获取输入的内容
let cont = $("#cont").val();
//Ajax请求
$.getJSON("/transjson",{q:cont},function (json){
//translation是一个json数据的键
let result = json.translation;
$("#result").text(result[0]);
})
});
});
</script>
</body>
2、JSONP
(1)JSONP(JSON with Padding),用来解决跨域问题的另一种解决方案,需要服务器端的支持。
<body>
请输入要翻译的内容:<input type="text" id="cont"> <input type="button" value="翻译" id="btn">
<div id="result"></div>
<div class="sc"></div>
<script type="text/javascript">
//定义回调函数show(),data是服务端传来的参数
function show(data){
document.querySelector("#result").innerHTML = data.translation;
}
document.querySelector("#btn").onclick = function(){
let cont = document.querySelector("#cont").value;
//使用的有道翻译API的数据格式doctype=jsonp,参数callback=show
let url = "http://fanyi.youdao.com/openapi.do?keyfrom=neverland&key=969918857&type=data&doctype=jsonp&callback=show&version=1.1&q="+cont;
let script = document.createElement("script");
//通过给script元素添加属性src=url,来发送请求,并调用回调函数show()
script.setAttribute("src",url);
document.querySelector(".sc").appendChild(script);
}
</script>
此时服务器端(有道翻译API)代码如下
//此时参数callback值为show
String func = request.getParameter("callback");
PrintWriter out = response.getWriter();
response.setContentType("text/plain;charset=utf-8");
//发出show(data),即执行show方法,并传递服务端数据
out.print(func + "(" + data + ")");
out.flush();
out.close();
(2)jQuery ajax方式以jsonp类型发起跨域请求,其原理跟<script>脚本请求一样。跨域请求需要服务端配合,设置callback,才能完成跨域请求。
<body>
请输入要翻译的内容:<input type="text" id="cont"> <input type="button" value="翻译" id="btn">
<div id="result"></div>
<div class="sc"></div>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
let cont = document.querySelector("#cont").value;
//此时参数callback=?不给定回调函数名
let url = "http://fanyi.youdao.com/openapi.do?keyfrom=neverland&key=969918857&type=data&doctype=jsonp&callback=?&version=1.1&q="+cont;
//跨域请求时必须设置doctype=jsonp,jsonp指定服务器返回的数据类型为jsonp格式
$.getJSON(url, function (data) {
$(".sc").text(data.translation);
});
});
});
</script>
3、Ajax提交form表单
(1)创建jsp页面
<body>
<form action="" id="myForm">
<input type="text" name="userName"/>
<input type="text" name="password"/>
<input type="file" name="myFile" />
<div id = "btn"> 登录</div>
</form>
<script type = "text/javascript">
$(function(){
$("#btn").click(function(){
//使用FormData()方法将表单数据序列化,
//序列化的表单的不能设置enctype="multipart/form-data",也可以提交文件
let data = new FormData($("#myForm")[0]);
$.ajax({
url:"/ajaxform",
type:"POST",
data:data,
cache:false,
processData:false,
contentType:false
});
});
});
</script>
</body>
(2)后端代码
@WebServlet("/ajaxform")
@MultipartConfig
public class FormServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String userName = req.getParameter("userName");
String pwd = req.getParameter("password");
Part myFile = req.getPart("myFile");
System.out.println(userName + "\t" + pwd);
}
}
4、Web Uploader
(1)WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。采用大文件分片并发上传,极大的提高了文件上传效率。
需要的文件:
webuploader.js
webuploader.css
Uploader.swf
(2)使用Web Uploader上传文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="js/webuploader/webuploader.js"></script>
<link href="js/webuploader/webuploader.css" type="text/css" rel="stylesheet"></link>
</head>
<body>
<div class="container">
<div id="uploader" class="wu-example" style="margin-top: 50px">
<div class="btns">
<div id="picker" class="pull-left">选择文件</div>
<button id="ctlBtn" class="btn btn-default pull-left">开始上传</button>
<div class="clearfix"></div>
</div>
</div>
<div id="fileList" class="clearfix"></div>
</div>
<script type="text/javascript">
$(function () {
var uploader = WebUploader.create({
//自动上传
//auto:true,
// swf文件路径
swf: 'js/webuploader/Uploader.swf',
// 文件接收服务端。
server: '/webuploader',
// 选择文件的按钮。可选。
// 内部根据当前运行时创建,可能是input元素,也可能是flash.
pick: '#picker',
// 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
resize: false,
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
uploader.on('fileQueued', function (file) {
$("#fileList").append('<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name + '</h4>' +
'<p class="state">等待上传...</p>' +
'</div>');
/* <div class = "progress">
<div class="progress-bar" role="progressbar" style="width: 40%;">60%</div>
</div>
*/
let perage = "<div class = \"progress\"><div class=\"progress-bar\" role=\"progressbar\">0%</div></div>";
$("#" + file.id).append(perage);
});
uploader.on( 'uploadSuccess', function( file ) {
alert("恭喜上传成功!");
});
uploader.on('uploadProgress', function (file, percentage) {
//$("#"+file.id + " .progress-bar").css('width', percentage * 100 + '%');
//$("#"+file.id + " .progress-bar").text(Math.floor(percentage * 100) + '%');
$("#"+file.id).find(".progress-bar" ).css('width', percentage * 100 + '%');
$("#"+file.id).find(".progress-bar").text(Math.floor(percentage * 100) + '%');
});
uploader.on( 'uploadComplete', function( file ) {
$( '#fileList' ).fadeOut(5000);
});
$("#ctlBtn").click(function () {
uploader.upload();
});
})
</script>
</body>
</html>