Search code examples
javajspscriptlet

How to assign values to HTML fields (e.g. img src="" with scriptlets


What I'm trying to do is to assign the value of a Scriptlet variable as the source for an image.

Here is the HTML in question:

    <div class="row">
    <div class="tab-content">
            <div class="tab-pane active" id="material">
        <h2>Material</h2>

          <ul class="thumbnails" id="hover-cap-3col">     

          <div id="myCarousel" class="carousel slide" data-interval="false">
              <!-- Carousel items -->
              <div class="carousel-inner">
                  <div class="active item">
                    <%



                    rs = stmt.executeQuery("SELECT IMG_NAME FROM IMAGES WHERE IMG_NAME LIKE 'Material%'");

                    ResultSetMetaData rsmd = rs.getMetaData();

                    int columnCount = rsmd.getColumnCount();

                    if (rs.next()) {

                        for (int i = 1; i < columnCount + 1; i++) {
                            names.add(rs.getString(i));
                        }

                    }

                    for (String name : names) {

                        String url = "http://localhost:8085/assignment/GetImage?name=" + name;

                    %>

                      <a href="http://localhost:8085/assignment/GetImage">
                      <div class="thumbnail">
                        <div class="caption"><h4>1</h4></div>
// RIGHT HERE ------>   <img src=<%url %> alt="ALT NAME">
                        <div class="caption-btm"><p>Material A</p></div>
                      </div></a>
                      <% } %>

                  </div>

              </div>

At the place where I specify the source for the image (shown by the comment), it gives me the following errors:

  • Syntax error, insert "AssignmentOperator Expression" to complete Assignment
  • Syntax error, insert ";" to complete Statement

Obviously, I can't assign the value to img src="" in that way. Is there any way for me to use the Scriptlet value or should I just scrap it and move on?


Solution

  • If you want to write the value of an expression to the served page, you must use <%= expr %> construct instead:

    <%=url %> 
    

    This is called a JSP expression.