Creating JSP templates (views) dynamically from a database

I am developing an application using Java and Spring MVC. As usual, one JSP file is stored in / WEB -INF / view / folder, which works as a View for all requests.

Usually we have a hard-coded JSP that also has some codes for processing Models (tags and ELs). Everything is working fine up to this point.

Now, instead of hard-coding JSPs, I want to dynamically populate this JSP file from the database. Thus, the user can download and select different templates / themes / layouts to display their pages.

Here is the code to explain what I'm trying to do (I know this is not the way, but only for illustration).

/WEB-INF/views/index.jsp

<%@ page import="com.example.domain.Template" %> <%@ page import="com.example.dao.TemplateStore" %> <!-- Following code is supposed to return complete JSP template from the database as uploaded by the user. --> <%= TemplateStore.getUserTemplate("userTemplate") %> 

I searched the web for this topic but found nothing.

Any help on how to do this would be greatly appreciated.

Thanks in advance.

IMPORTANT: I ​​asked this question a few days ago, but some members marked it as β€œoff topic”. I still do not understand how this question is disconnected from the topic - https://stackoverflow.com/questions/18026092/creating-content-of-jsp-views-in-web-inf-views-dynamically-from-the-database .

+4
source share
2 answers

If presentation templates should be dynamically retrieved from the database, you should not think about JSPs. JSPs are compiled into servlet classes and there is little support for this other than the standard one (static files somewhere under your webapp root).

Therefore, just consider switching the viewing technology (at least for the dynamic part) to some general-purpose template library, such as Velocity or Freemarker . This is due to the security bonus, as there may be less in this template than from the JSP code.

You can even support multiple viewing technologies (perhaps something that Spring MVC supports off-the-shelf, with the exception of JSP) and allows your users to choose the type of template at boot time.

Then you can write your own custom view, which will be delegated to the corresponding standard recognizers (Velocity, Freemarker, XSLT, independently ...) with the template selected by the user.

However, if JSP is a tough requirement, I think that one ugly workaround for JSP (which should work in any servlet container) could be to extract the contents from the database and create the actual file (e.g. WEB-INF/templates/${primarky-key}.jsp ) under your exploded root webapp, then RequestDispatcher.forward() to it.

+3
source

You could or could not do it with JSP, but you can of course compile the Java code in memory and then call it.

http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm

Of course, moving from JSP to Servlet would be another step.

0
source

Source: https://habr.com/ru/post/1496091/


All Articles