smallRainFetch.jsp
html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>fetch</title>
</head>
<body>
</body>
</html>
<input type="text" id="inputone" name="inputNameOne"
value="fetchGet服务" />
<button onclick="getFromServer()">fetch和服务器交互</button>
<div id="smallRainShow" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
function getFromServer() {
const valueTo = document.getElementById('inputone').value;
fetch('<%=request.getContextPath()%>/smallRainFetchServlet?inputNameOne=' + valueTo)
.then(smallRainRes => {
return smallRainRes.text();
})
.then(smallRainData => {
document.getElementById("smallRainShow").innerHTML = smallRainData;
})
.catch(error => {
alert("error");
});
}
</script>
SmallRainFetchServlet.java java文件
java
package org.rain.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/smallRainFetchServlet")
public class SmallRainFetchServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest smallrainReq, HttpServletResponse smallRainRes) throws ServletException, IOException {
doGet(smallrainReq, smallRainRes);
}
@Override
public void doGet(HttpServletRequest smallrainReq, HttpServletResponse smallRainRes) throws ServletException, IOException {
smallRainRes.setCharacterEncoding("UTF-8");
PrintWriter smallrainOut = smallRainRes.getWriter();
String smallRainWeb=smallrainReq.getParameter("inputNameOne");
smallrainOut.print("得到服务器返回:"+smallRainWeb);
}
}