开发者

Custom list + JSP + java.lang.NumberFormatException

I want to implement custom JSP list tag, but have problem with accessing properties of custom list object. With example like below accessing a name property of List2 on test.jsp page give an error org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "name". How to solve this ?

public class List2 extends ArrayList<String> {开发者_运维百科

    public String getName() {
        return "name";
    }
}

test.jsp

<%-- java.lang.NumberFormatException --%>
${list.name}

<%-- this works ok --%>
<c:forEach  items="${list}" var="item">
   ${item}  
</c:forEach>

EDIT

Whole test.jsp working

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach  items="${list}" var="item">
   ${item}
</c:forEach>

Whole test.jsp NOT working

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
${list.name} 

TestController.java:

@Controller
public class TestController {

    @ModelAttribute("list")
    public List2 testList() {
        List2 l = new List2();
        l.add("foo");
        l.add("bar");
        return l;
    }

    /* test.jsp */
    @RequestMapping("/test")
    public String test() {
        return "test";
    }
}


I think it's due to the fact that the JSP EL allows using . or [] to access object properties. But both have a special meaning for List instances: it means access to the nth element. You may thus write ${list[2]} or ${list.2}. Since EL detects that your object is an instance of a collection, it tries to transform name into a number, and you get this exception.

Note that this is only an explanation of the exception you get. I haven't checked the specification to see if it's a bug of Tomcat or if it's expected behavior.

You should very very rarely extend ArrayList. Most of the time, it's better to use delegation, and thus wrap the list inside another object. Couldn't you just have something like the following?

public class List2 {

    private List list;

    public String getName() {
        return "name";
    }

    public List getList() {
        return list;
    }
}


Creating an extra class would be redundant, try using the following:

<c:set var="listName"><jsp:getProperty name="list" property="name"/></c:set>
<c:out value="${listName}"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜