jsp EL表达式详解(3)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> name=${initParam.name } </body> </html>

客户浏览器显示结果

这里写图片描述

四、EL访问Bean的属性 1、什么是java Bean

JavaBean是公共Java类,但是为了编辑工具识别

需要满足至少三个条件

有一个public默认构造器(例如无参构造器)

属性使用public 的get,set方法访问,也就是说设置成private同时get,set方法与属性名的大小也需要对应。例如属性name,get方法就要写成,public String getName(){},N大写。

需要序列化。这个是框架,工具跨平台反映状态必须的

2、EL访问Bean属性

EL可以通过${key.属性}的方式获取到指定值,其底层实际调用的是该对象的相应属性的get方法

Demo.java

package linjie.com; /* *Bean */ public class Demo { private String name; private int age; public Demo(String name,int age){ this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return super.toString(); } }

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" import="linjie.com.Demo" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% Demo test=new Demo("linjie",12); request.setAttribute("ELttt", test); %> name=${requestScope.ELttt.name }<br> age=${requestScope.ELttt.age }<br> <!-- 若访问为null的对象的属性,EL是不会抛出空指针异常的,只是不显示而已 --> names=${requestScope.ELtttxx.name }<br> </body> </html>

客户浏览器显示结果

这里写图片描述

五、EL访问数组中的数据

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% String[] names={"xlj","lucy","king"}; pageContext.setAttribute("names", names); %> name[1]=${names[1] }<br> <!-- 若访问的数组元素下标超出了数组下标上限,EL不会抛出越界异常,只是不显示 --> names[5]=${names[5] }<br> </body> </html>

下面是访问类的数组

Stu.java

package linjie.com; /* *Bean */ public class Stu { private String sname; private String address; public Stu() { super(); } public Stu(String sname, String address) { super(); this.sname = sname; this.address = address; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return super.toString(); } }

index.jsp

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsgyyp.html