標籤:prot java web array contex dog 屬性 集合 運算式 產生
1.運算式語言簡介
主要為了簡化mvc中 jsp的代碼量,方便進行屬性的輸出。還可以避免進行屬性為空白等的判斷,運算式預設將null設定為""。
2.運算式語言的內建對象
a. 關於屬性的擷取${屬性名稱}, 對於page->request->session->application這四個屬性範圍來講,如果同時設定同名的屬性,那麼將只顯示 屬性範圍最小的那個屬性值。
一般情況下,各屬性範圍設定的屬性名稱應該不一樣,這樣直接用${屬性名稱}調用即可。
b. 關於參數的擷取${param.參數名稱} 或者如果是多選框參數時需要${param.屬性名稱[0]}
c. 通過pageContext內建對象來擷取其他內建對象
${pageContext.request.remoteAddr}、${pageContext.session.id}、${pageContext.session.new}
3.運算式語言-集合的操作
a. 對於List類型的集合對象,可以直接${對象名稱[下標數字]} 調用
b. 對於Map類型的集合對象,可以用${對象名稱[key名稱]}調用
例子
============================================
a.
<%
List addr = new ArrayList();
addr.add("德國");
addr.add("英國");
addr.add("法國");
request.setAttribute("info",addr);
%>
<h1>${info[0]}</h1>
<h1>${info[1]}</h1>
<h1>${info[2]}</h1>
b.
<%
Map map = new HashMap();
map.put("notebook","暗夜之光17寸");
map.put("iphone","iphoneX");
map.put("kindle","kindle");
request.setAttribute("info",map);
%>
<h1>${info["notebook"]}</h1>
<h1>${info["iphone"]}</h1>
<h1>${info["kindle"]}</h1>
4.在MVC中應用運算式語言
a. 定義vo , servlet,在servlet中產生vo 對象設定vo 對象的屬性
最重要的一點要通過doGet的request參數將vo對象設定成一個屬性info。
這樣在之後的jsp中,就可以通過${info.成員變數}的方式來訪問了
b. 對於servlet產生一個vo的對象集合的情況,還是在doGet中用request參數將vo對象集合 all設定為屬性info
jsp中需要先通過request.getAttribute("info")擷取到List集合對象 all。
然後通過iterator來對List集合對象進行迭代。 Iterator itr = all.iterator();
在while(itr.hasNext()){}迴圈中,需要先通過pageContext.setAttribure("dept",itr.next());
然後在通過${dept.成員變數}訪問。
=====================================================================================================a
Servlet
public class ServletPeople extends HttpServlet{
private People pl = null;
List<People> all = null;
protected void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
all = new ArrayList<People>();
pl = new People();
pl.setName("李永盛");
pl.setSex("男");
pl.setSalary(60000);
all.add(pl);
pl = new People();
pl.setName("李宇揚");
pl.setSex("男");
pl.setSalary(80000);
all.add(pl);
req.setAttribute("info",all);
req.getRequestDispatcher("/people/people.jsp").forward(req,resp);
}
jsp
。。。
<%
List all = (List) request.getAttribute("info");
Iterator itr = all.iterator();
while(itr.hasNext()){
pageContext.setAttribute("dept",itr.next()) ;
%>
<h1>${dept.name}</h1>
<h1>${dept.sex}</h1>
<h1>${dept.salary}</h1>
<%}%>
。。。
java web 學習筆記 - 運算式語言