Servlet與JSP的通信
發(fā)表時間:2023-08-08 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]以下的代碼片段演示了一個servlet,它例示(instantiates)一個bean并且用由瀏覽器發(fā)送的Form數(shù)據(jù)將它初始化。此后bean被加入request,而這一要求被送到JSP頁面(Bea...
以下的代碼片段演示了一個servlet,它例示(instantiates)一個bean并且用由瀏覽器發(fā)送的Form數(shù)據(jù)將它初始化。此后bean被加入request,而這一要求被送到JSP頁面(Bean1.jsp),JSP通過request取得并做進(jìn)一步處理。
public void doPost (HttpServletRequest request,
HttpServletResponse response) {
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
. . .
}
}
在將它從通過useBean操作中的缺省的請求范圍,即scope首次執(zhí)行后,即可在JSP文件的Bean1.jsp處理fBean。
<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>
<jsp:getProperty name="fBean" property="name" />
<jsp:getProperty name="fBean" property="addr" />
<jsp:getProperty name="fBean" property="age" />
<jsp:getProperty name="fBean" property="personalizationInfo" />