EL

来源:互联网 发布:沈阳关键词优化排名 编辑:程序博客网 时间:2024/06/09 19:52

准备工作:

新建一个index.jsp,DateServlet.java,result.jsp

index.jsp→请求DateServlet.java→跳转result.jsp

跳转:(request.getRequestDispatcher("result.jsp").forward(request,response);)

向页面传递数据:

1. 请求转发:可以通过request.setAttribute()方法向目标页面传递数据

       request.setAttribute("userName","dan");

       request.getRequestDispatcher("result.jsp").forward(request,response);

2. 重定向:这种方式不能通过request.setAttribute()方法向目标页面传递数据

       request.setAttribute("userName","dan");

       response.sendRedirect("result.jsp");

在result.jsp接收数据

一、通过Java代码

<body>              <%=request.getAttribute("userName")%></body>
二、EL表达式

<body>              ${userName}  (setAttribute中的key)</body>
重定向依然不能传递数据

(1)    EL表达式简单

(2)    避免代码的沾染

(3)    Java代码写在Java文件里,jsp中慎用Java代码

1.    request.setAttribute(  String(key) , Object( value)   );

       value可以是:基本数据类型与String类型

2.    自定义类型

a、  在页面中要显示的自定义类成员变量必须要有getter;

b、  如何显示:${key(setAttribute中的key).成员变量名}

public class Student {int age;   //年龄String address; //地址String userName; //用户名public Student(int age, String address, String userName) {this.age = age;this.address = address;this.userName = userName;}public int getAge() {return age;}public String getAddress() {return address;}public String getUserName() {return userName;}}
request.setAttribute("student", new Student(22,"嗯哼","dan"));request.getRequestDispatcher("result.jsp").forward(request, response);

${student.userName }<br/>${student.age }<br/>${student.address }<br/>

3.    数组

Student [] studentArray = {new Student(22,"北京","嗯哼"),new Student(22,"上海","阿哼")};request.setAttribute("studentArray",studentArray);request.getRequestDispatcher("result.jsp").forward(request, response);
<body>${studentArray[0].userName }<br/>${studentArray[0].age }<br/>${studentArray[0].address }<br/></body>
4. List

List<Student> arrayList = new ArrayList<Student>();arrayList.add(new Student(22,"北京","嗯哼"));arrayList.add(new Student(22,"山东","阿哼"));request.setAttribute("arrayList",arrayList);request.getRequestDispatcher("result.jsp").forward(request, response);
${arrayList }<br/>   //输出学生对象${arrayList[1].userName }<br/>${arrayList[1].age }<br/>${arrayList[1].address }<br/>

5.    Map集合(Key必须是合法的标识符

注意: Map集合的key最好符合Java标识符规范,否则在EL表达式中不能使用.的方式获取到Map集合相应的value,只能通过[]的方式获取到相应的内容;;;;;Map集合Key的泛型不能是Java基本数据类型的包装类,否则EL表达式无论使用哪种方式都无法获取到相应的value值。

Map<String,Student> studentMap = new HashMap<String,Student>();studentMap.put("a",new Student(22,"北京","嗯哼"));studentMap.put("b",new Student(22,"山东","阿哼"));request.setAttribute("studentMap",studentMap);request.getRequestDispatcher("result.jsp").forward(request, response);

${studentMap}<br/>${studentMap.a.userName }<br/>${studentMap['b'].age }<br/>${studentMap["b"].address }<br/>






 

 

 

 


0 0
原创粉丝点击