Java-web:使用Axios代替JSP
使用Servlet注解代替配置web.xml文件
在servlet3.0版本支持使用注解
1.創(chuàng)建一個Servlet響應(yīng)axios發(fā)送的請求
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//獲取請求Reader對象
BufferedReader br = req.getReader();
//讀取axios發(fā)送的data:字符串
String params = br.readLine();
//{"str":"hello world!"}
System.out.println(params);
//返回一個響應(yīng)response
//其中響應(yīng)體里面的data對象有個"success"字符串
resp.getWriter().write("success");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
JSP代替:
還原JSP到HTML:
Axios:將ajax進行封裝,簡化JS發(fā)送異步請求的代碼
Axios官網(wǎng):https://www.axios-http.cn/
下載axios.js文件到本地然后再HTML頭文件引入或者直接引用網(wǎng)址的JS頭文件兩種方式
2.創(chuàng)建一個main.html文件,設(shè)置一個div用于顯示axios使用回調(diào)函數(shù)時從響應(yīng)體里獲得的JSON數(shù)據(jù)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../static/js/axios.js"></script>
</head>
<body>
<div id="main"></div>
</body>
</html>
3.編寫JS代碼
設(shè)置窗口onload函數(shù):里面直接調(diào)用axios封裝好的ajax函數(shù)發(fā)送異步請求
axios發(fā)送POST請求跳轉(zhuǎn)前面設(shè)置好的路徑"/hello",設(shè)置data
回調(diào)函數(shù)向div里插入servlet響應(yīng)的JSON字符串
window.onload = function (){
axios({
method: 'post',
url:'http://localhost:8080/test/hello',
data:{
str:'hello world!'
}
})
.then(function (response){
document.getElementById("main").innerText = response.data
console.log(response);
})
}
4.maven打包(package)并運行http://localhost:8080/test/main.html
運行順序如下:
main.html打開應(yīng)該是空白頁面,但是axios發(fā)送了一個POST請求
按下F12打開瀏覽器開發(fā)者工具NetWork查看捕獲的請求和響應(yīng):
后端Servlet響應(yīng)請求并且使用print打印傳送的JSON字符串,Tomcat的console可以查看:
之后servlet也給予response響應(yīng)體JSON字符串
html頁面里對應(yīng)axios的回調(diào)函數(shù)進行頁面顯示(innerText)和瀏覽器console顯示(console.log)
打開f12瀏覽器的開發(fā)者工具查看控制臺console:
TIPS:使用alibaba的FastJSON.jar可以幫助快速處理字符串
心得:
項目的一些實際的部署會安排到服務(wù)器上面html頁面對于css/js/images等靜態(tài)資源最好放在static文件夾里,引用時候最好直接是以完整的路徑http://localhost:8080/demo/static/…,避免路徑的誤解,而不是使用…/static/…這樣
一個完整的過程描述:文章來源:http://www.zghlxwxcb.cn/news/detail-461127.html
HTML頁面→使用axios函數(shù)封裝ajax發(fā)送異步請求(request)→servlert后端對request處理(獲取發(fā)送的JSON字符串作為數(shù)據(jù)),然后也能對response也能進行處理(response.getWirter().write(“xxxxxxx”))→axios的回調(diào)函數(shù)對servlet后端發(fā)送的resopnse也能進行處理(response.data)文章來源地址http://www.zghlxwxcb.cn/news/detail-461127.html
到了這里,關(guān)于Java-web:使用Axios代替JSP進行前后端分離與數(shù)據(jù)交互的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!