-3

I'm building a website based on HTML, CSS & JS front-end and JAVA servlet Back-end.

The problem I am facing is that while sending a web page as a response to some request from the client, that web page is not completely static. I need to modify some parts of HTML according to data from the database and then I want to send that web page to the HTTP response either by redirecting to that HTML page or send it to the client line by line using getWriter() function of HttpRequest object.

For both ways I need to take care of some parts of HTML code that need to changed. One way I could think of is that create another HTML file, read first static part of our HTML and write it to the new HTML. Then process dynamic HTML code and write it to the new HTML file. Again read static HTML and write it to new HTML file and so on.

But in this way, I don't what to do with JS & CSS files and other files like images that are being used by our HTML page that we want to send in response.

enter image description here

1 Answers1

2

When you're using JSP, the web pages are rendered once-per-request on server and returned to client as "static" HTML documents. If I understand you correctly, you want somehow 'inject' dynamic code to existing static .html file. That is not impossible but useless. Instead make a .JSP file with hardcoded "static" content and render "dynamic" context using scriptlets or JSTL tag library.

Reaction to comment:

If you want to display dynamic images, there are two ways that come to my mind right now:

  1. If your images are stored directly inside database as blobs: Simply decode the image in your scriplet and render the image with base64 encoding directly to src attribute of img.

  2. If your images are stored locally in your server root directory (the one containing .jsp files). You can address them directly like in static web applications.

Your JSP file could look like:

    <%
        //between these tags you can write Java code
        //client wont see this code
        Product product = ...; // pull from database somehow
    %>

    <!--outside these tags you're writing HTML code-->
    <html>
       ...
       <p><b>Product name:</b> <%=product.getName()%></p>
       <img src="/img/products/image_<%=product.getId()=>.jpg"/>
    </html>
t4dohx
  • 675
  • 4
  • 24
  • Thank you so much for this information. Please tell me one more thing. If I make a hardcore static JSP page then what about images that need to be included on the page from the database. For example, If want to show a post with ID 123 and that post has some images in database, then how do I show that image on JSP page – Zeeshan Dhillon Jan 03 '20 at 18:25
  • Modified my answer. – t4dohx Jan 03 '20 at 18:40
  • Thank you. That is helpful. – Zeeshan Dhillon Jan 03 '20 at 22:51