in php I do this:
<?php
function displaySomething($list) {
foreach ($list as $item) {
?>
<html code here><?php echo $item["field"] ?><html code again etc>
<?php }
}
?>
And then I use it to display different lists in different places in my page.
Is there a way to achieve this with jsp? Create methods with parameters in which I can combine html with java?
<%! %> admits only java code, can't cut in with html code.
In order to do this you have to create a tag library.
There are two ways to define such:
via a TagLib
class and a taglib descriptor - tedious process, and an overkill for your case
tag files - see here for how to do it. In short - you specify a code fragment (with the jsp syntax) that will be executed when the tag is found. The difference would be that you will have <c:forEach>
, and inside - the reference to the tag.
You can't include HTML code in a <%! %>
tag.
I know it's know exactly what you are looking for, but a similar way of doing that in JSP is using JSP CUSTOM TAGs.
There is not. PHP is parsed, Java is compiled into bytecode. PHP has more freedom because the executer always sees the source code.
However, you can define the HTML code as a string literal and print it together with your item.getField().ToString()
in the for-each loop. Obviously remember that for-each loop in Java have little different syntax, but you should know already ;-)
Create a .tag-file in your /WEB-INF/tags directory, say myfunction.tag, with the following content:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="list" required="true" type="java.util.Collection" %>
<c:forEach var="item" items="${list}" varStatus="rowCounter">
<html code here>${item.field}<html code again etc>
</c:forEach>
or uglier:
<% Collection list = (Collection)pageContext.getAttribute("list");%>
<% for(Object o: list) { %>
<html code here><%=((MyType)o).getField()%><html code again etc>
<% } %>
then you can use it on any .jsp-page using the following code:
<%@ taglib prefix="x" tagdir="/WEB-INF/tags" %>
...
<x:myfunction list="${someCollection}"/>