Yosef
Yosef

Reputation: 370

Dynamically put JSP tag on a JSP page

I’m doing with my first steps in Spring MVC and JSP and I’m trying to figure out what’s the best way to do the following:

I need to create a dynamic page that is made from some static HTML and some dynamic widgets that appear on the page per my business logic. Each widget is a div with some content: one widget might show a trend while other widget might show a table, etc. What I actually need to do is decide on run time which widget to put on a specific position in the page and place it there. In other words, I need to dynamically replace some place holder in the JSP file with JSP tag file or anything else that will provide the widget HTML. I can simply do that by wrapping each placeholder with some if or switch statements but I want to know if there is a cleaner way to do that.

Thanks, Yosi

Upvotes: 1

Views: 1234

Answers (3)

Rüdiger Schulz
Rüdiger Schulz

Reputation: 3078

If you want to see what is included when, right away in your code, with IDE code navigation support, then a list of <c:when> is the way to go.

Dynamic includes (e.g. <jsp:include page="${widgetName}" />) would make the code much shorter for sure, but also less easy to understand what's going on.

Upvotes: 2

kryger
kryger

Reputation: 13181

JSP, as a server-side technology, can't take part in runtime events (i.e. after user loaded the page); once the rendered response (i.e. HTML) leaves the server and embarks on a journey to user's browser, JSP's role is over. If you want to change the content, you can only get it by making another request.

There are several technologies that can help you with assembling the HTML response from smaller building blocks (e.g. JSP includes, Apache Tiles, etc.), but by definition they can only react to request parameters that are known up front, at request time.

If you need runtime flexibility, you can either:

  • always build a "full" page that contains all potential widgets and return it to all users but make some of the elements initially hidden (via CSS), user's request for a widget would simply make it visible
  • request HTML fragments from the server via AJAX and attach them to the page using JavaScript.

Upvotes: 0

learner
learner

Reputation: 625

JSP dynamic includes may solve your problem. Please check the concept once.

Upvotes: 1

Related Questions