web項目中一般會使用MVC模型。即Model——View——Control
Model——javabean建立模型
View——jsp界面展示
Control——servlet邏輯控制(一般涉及與數(shù)據(jù)庫交互)
web的數(shù)據(jù)傳遞流程:
1、從jsp到servlet
jsp層一般是通過form表單的提交,將form表單的內(nèi)容傳遞到servlet
serlvet通過在doPost或者doGet方法中,request.getParamter()方法獲取表單信息。
2、從serlvet到數(shù)據(jù)庫
(1)獲得數(shù)據(jù)
配置數(shù)據(jù)庫連接池
數(shù)據(jù)庫驅(qū)動
jdbc,執(zhí)行sql,得到一個ResultSet數(shù)據(jù)集
(2)處理數(shù)據(jù)
建一個JavaBean類,定義屬性,set和get方法
ResultSet查詢數(shù)據(jù)庫結(jié)果集
在servlet實例化一個javabean對象,通過resultSet.getString()方法,給javabean對象賦值,則得到一個javabean。
(3)從servlet到j(luò)sp
發(fā)數(shù)據(jù):在servlet中可以應(yīng)用轉(zhuǎn)發(fā)的方法:
//將數(shù)據(jù)發(fā)到JSP RequestDispatcher rd = request.getRequestDispatcher("index_search.jsp"); request.setAttribute("test",collection);//存值 rd.forward(request,response);//開始跳轉(zhuǎn)接受數(shù)據(jù):在JSP中,可以直接用EL來取值對象,也可以直接:<%=request.getAttribute("name")%><% String str = request.getAttribute("name");%>
注意這里不能使用redirect(重定向)的方法,因為forward方法跳轉(zhuǎn)之后還是在同一個web下面,request和response的值都保存著。
redirect重定向之后,請求到一個全新的jsp,request和response方法都是全新的,沒有值的。
參考博客:
http://java--hhf.iteye.com/blog/1973375
http://zzqrj.iteye.com/blog/806909
http://zhulin902.iteye.com/blog/939049
新聞熱點
疑難解答