tags:

views:

37

answers:

3

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.
A: 

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.

Bozho
I don't understand in which way tags solve my problem. When defining a tag, the code goes into a Java class (TagSupport). One function in a util.php becomes a Java class with a public int doStartTag() throws JspException { glue strings here and print } not cool at all :(
Ionut
@lonut - see my update. There is an easier way to define tags, which fits your case.
Bozho
thanks, this looks nicer, I'll look into it
Ionut
A: 

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.

Pablo Santa Cruz
+1  A: 

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 ;-)

djechelon