Make JSF access a Map<String, ?> values from an EL instead of a bean fields?

≡放荡痞女 提交于 2019-12-05 07:10:57

You can directly use map by EL.

Holder.java

public class Holder {

    private Map<String, Object> objects = new HashMap<String, Object>();

    public void add(String key, Object value) {
        objects.put(key, value);
    }

    public Map<String, Object> getObjectsMap() {
        return objects;
    }

}

EL

#{exampleBean.holder.objectsMap[your-key]}
Luiggi Mendoza

This problem is not about JSF but EL. As noted in @BalusC comment, you can directly use the notation you already want/need with Map objects. I've prepared a basic example on this (note: this is just an example and should remain as is or improved since it uses scriptlets and we must avoid scriptlets usage but made it for a quick dirty test):

<%@page import="edu.home.model.entity.User"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%
        //Scriptlets usage, sorry. This code must be moved to a Servlet or another controller component
        //defining the map
        Map<String, User> aMap = new HashMap<String, User>();
        //defining a value for the map
        User user = new User();
        user.setFirstName("Luiggi");
        user.setLastName("Mendoza");
        //adding the value in the map 
        aMap.put("userLM", user);
        //making the map accesible in EL through PageContext attribute
        pageContext.setAttribute("aMap", aMap);
    %>
    <!-- Accessing directly to the userLM key and its attributes -->
    ${aMap.userLM.firstName} - ${aMap.userLM.lastName}
</body>
</html>

User class code (minimized for test purposes):

public class User {
    private String firstName;
    private String lastName;
    //empty constructor
    //getters and setters
}

This generates a JSP page that prints:

Luiggi - Mendoza

Note that this (except the scriptlet part) will work on a Facelets page as well since this is EL and not JSF.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!