Question

Can anyone tell me how to pass value from JSP file to velocity template.

Was it helpful?

Solution

Maybe you should try to get someting simple to work. Consider a simple dynamic web project with a jsp like the following:

<%@page import="java.io.File"%>
<%@page import="org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"%>
<%@page import="org.apache.velocity.runtime.RuntimeConstants"%>
<%@page import="java.io.StringWriter"%>
<%@page import="org.apache.velocity.VelocityContext"%>
<%@page import="org.apache.velocity.Template"%>
<%@page import="org.apache.velocity.app.VelocityEngine"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
     String s = request.getParameter("test");
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "/");

    velocityEngine.init();
    Template t = velocityEngine.getTemplate("/template.vm");
    VelocityContext context = new VelocityContext();
    context.put("example",
            s);
    StringWriter w = new StringWriter();
    t.merge(context, w); 


%>
<p><%out.println(w.getBuffer().toString());  %> </p>
 </body>
</html>

It just loads a template from the root of your server and prints it out in the current site with a GET/POST parameter.

In the WEB-INF/lib folder of your project you put the velocity.jar, the common-collections.jar and the common-lang.jar. Important: In your server root directory you put a simple textfile template.vm with the following template

 <b>Test $example<b> 

You can also have a template directory or something similar but I tell you when you wanna deploy your templates with the webapp(loading vm-files from WEB-INF directory for example)-> that's a challenge!

Load it with yourproject/example.jsp?test=getparamh and I'm sure it work

But if you try this - admitdettly - simple example, it should work and you can maybe derive your targets from it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top