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>

<%}%>

。。。