前后臺數(shù)據(jù)交互

1.利用session對象

session對象表示特定會話session的用戶數(shù)據(jù)??蛻舻谝淮卧L問支持session的JSP網(wǎng)頁,服務(wù)器會創(chuàng)建一個session對象記錄客戶的信息。當(dāng)客戶訪問同一網(wǎng)站的不同網(wǎng)頁時,仍處于同一個session中。

(1)后臺代碼

request.getSession().setAttribute("name", name);?

request.getSession().setMaxInactiveInterval(2);?

response.sendRedirect("welcome.jsp");?

(2)前臺代碼(jsp頁面)

1Object user=request.getSession().getAttribute("name");

2.利用request重定向,設(shè)置setAttribute

(1)后臺代碼

request.setAttribute("name",?"cute");?

request.getRequestDispatcher("welcome.jsp").forward(request, response);?//網(wǎng)址不會改變

PS:如果后臺使用的轉(zhuǎn)發(fā)代碼為?response.sendRedirect("welcome.jsp"); ?//網(wǎng)址變?yōu)閣elcome.jsp

則request設(shè)置的參數(shù)無效,因?yàn)橐呀?jīng)切換到另一個請求了,request參數(shù)的有效期為本次請求。

(2)前臺代碼

1String name=request.getAttribute("name").toString();?

3.利用Ajax進(jìn)行異步數(shù)據(jù)請求(得到的數(shù)據(jù)可以以json或xml格式返回,便于處理)

public?class?TestServlet?extends?HttpServlet {?


????/**

?????* Constructor of the object.

?????*/

????public?TestServlet() {?

????????super();?

????}?


????public?void?doGet(HttpServletRequest request, HttpServletResponse response)?

????????????throws?ServletException, IOException {?

????????doPost(request, response);?

????}?


????public?void?doPost(HttpServletRequest request, HttpServletResponse response)?

????????????throws?ServletException, IOException {?


????????response.setContentType("text/html");?

????????PrintWriter out = response.getWriter();?

????????String data="[{\"name\":\"apple\",\"price\":23},{\"name\":\"banana\",\"price\":12},{\"name\":\"orange\",\"price\":8}]";?

????????out.write(data);?

????????out.flush();?

????????out.close();?

????}?


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容