displaying a list of entities in jsp file by using java

前端 未结 2 2002
无人共我
无人共我 2021-01-26 08:05

I am trying to display list of entities in a .jsp file, but I this error:

Unable to compile class for JSP: 

An error occurred at line: 28 in the jsp file: /gues         


        
相关标签:
2条回答
  • 2021-01-26 08:46

    You shouldn't be using scriptlets (those oldschool <% %> things with Java code) at all when using servlets and EL. Use taglibs like JSTL instead. It offers the <c:forEach> tag to iterate over a collection.

    For example,

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    ...
    <table border="1">
      <tr>
        <th>Drug Names</th>
        <th>Target Names</th>
      </tr>
      <c:forEach items="${drugtargets}" var="drugtarget">
        <tr>
          <td>${fn:escapeXml(drugtarget.drug)}</td>
          <td>${fn:escapeXml(drugtarget.target)}</td>
        </tr>
      </c:forEach>
    </table>
    

    (note that I also fixed the rendering of table rows by putting the <tr> inside the loop)

    Much simpler, isn't it? You can by the way also just use <c:out value="${drugtarget.drug}"/> instead of those functions.

    If you can, I suggest to add the following to your webapp's web.xml in order to disable scriptlets altogether so that you will be forced to do things the right way.

    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <scripting-invalid>true</scripting-invalid>
        </jsp-property-group>
    </jsp-config>
    

    See also:

    • How to avoid Java code in JSP files?
    0 讨论(0)
  • 2021-01-26 08:46

    In this case "${drugtargets}" is a String, not the list you passed. I would recommend using the looping. It's way cleaner.

    <c:forEach var="drugtarget " items="${drugtargets}"> 
    .... Your code here ...
    </c:forEach>
    
    0 讨论(0)
提交回复
热议问题