How to Convert Html files into .vm(velocity template) files using spring mvc

2.8k Views Asked by At

Need to convert the UI pages in .html to .vm(velocity template) files using spring mvc.I tried searching on other sites but did not got any nice information.

Any useful site/help will be appreciated. Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

First of all, you need to be clear that when you are using MVC, you can serve the pages in any way you want. Here is one possible solution to your problem which is the actual code from my own application.

You might want to serve the *.html requests like this.

web.xml

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        PATH/TO/YOUR/SERVLET-CONTEXT.xml
    </param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>appServlet</servlet-name>
  <url-pattern>*.html</url-pattern>
</servlet-mapping>

Then in your servlet-context.xml, you can configure the VelocityViewResolver like this.

<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
    <property name="cache" value="true"/>
    <property name="prefix" value="PATH/TO/YOUR/VIEWS/FOLDER"/>
    <property name="suffix" value=".vm"/>
</bean>

Then from your controller, return the name of the view you want to render, this should not include the extension.

return "template";    //Return the name of view to be found in the views folder.
                      //The template.vm should be present in your views folder.

This would solve your problem.

Please be clear that in MVC, the view is returned based on the type of your request, no actual conversion of file-types takes place.

0
On

This html to .vm conversion thing in your question seems a bit misleading as whatever it may be- .vm(velocity template), .jsp , .ftl(freemarker template) ,etc , When rendered on the front end it is just html.

I believe, you want to know how can you configure spring mvc to use velocity as your view layer.

For this, you need to configure your view resolver as VelocityViewResolver.

Go to your 'mvc-dispatcher-servlet.xml' or '-servlet.xml' which by default contains spring's InternalResourceViewResolver configuraion used for jsp files. You need to add velocity specific configuration like this:

<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
    <property name="cache" value="true"/>
    <property name="prefix" value=""/>
    <property name="suffix" value=".vm"/>
</bean>

This link might be of good help.