Passing value from JSP to velocity template [duplicate] - java

This question already has answers here:
How do I pass get request parameters to my Velocity Template to send mails
(2 answers)
Closed 9 years ago.
Can anyone tell me how to pass value from JSP file to velocity template.

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.

Related

What is the difference between <html> and <html:html> element in JSP?

I am developing a simple Struts 1.x web application and there's a file named success.jsp and this is the sample code:
<%# taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%# taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%# taglib uri="http://struts.apache.org/tags-nested" prefix="nested"%>
<%# 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:html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>success.jsp</title>
<html:base/>
</head>
<body>
Go to myStart
</body>
</html:html>
By default, <html>was used instead of <html:html>, may I know what is the major difference between these two elements? Is it necessary to specify the uses of them? Besides, what is the major function for <html:base/> element?
Btw I found some definitions for these elements but I need clarification:
<html:html> Renders an HTML <html> element with language attributes extracted from the user's current Locale object, if there is one.
<html:base> Renders an HTML element with an href attribute pointing to the absolute location of the enclosing JSP page. This tag is valid only when nested inside an HTML <head> element. This tag is useful because it allows you to use relative URL references in the page that are calculated based on the URL of the page itself, rather than the URL to which the most recent submit took place (which is where the browser would normally resolve relative references against).
The <html:html> tag is a Struts 1.x JSP Taglib directive, declared in this line on your JSP Page:
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
These custom tag(s) are typically of the form <prefix:tagname>. The prefix declared on taglib is what binds your taglib container to the list of markups available in the taglib.
In essence <html:html> tells the taglib, prefixed html to render a html element when JSP is rendered.
So to answer your question <html> is a HTML directive while <html:html> is a Struts JSP taglib tag to generate a HTML <html> directive.

jsp - whats wrong with my import of a jar file?

I am trying to integrate Simplify Commerce payment system into my project
but I can't seem to get it right.
This is one of the problems:
<%# page import="com.simplify.package"%>
and I got this error after mousing over the red wavy line:
Syntax error on token "package", * expected
I then added a `*` like this `com.simplify.package.*`
And I got this:
`Syntax error on token "package", Identifier expected`
I already added all the .jar files to the `WEB-INF/lib` folder.
What seems to be the problem?
The jsp that I am trying to import the jar file:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="com.simplify.package.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pay Now!</title>
</head>
<body>
<%
PaymentsApi.PUBLIC_KEY = "";
PaymentsApi.PRIVATE_KEY = "";
CardToken cardToken = CardToken.create(new PaymentsMap()
.set("card.addressCity", "OFallon")
.set("card.addressState", "MO")
.set("card.cvc", "123")
.set("card.expMonth", 11)
.set("card.expYear", 19)
.set("card.number", "5105105105105100")
);
System.out.println(cardToken);
%>
There are red way lines under PaymentsApi and CardToken
Unpacking the jar file to look at the package structure solved it.

null request response in simple jsp file

I am trying to just set up a very basic jsp file that takes in a query from a url and displays it. I have the following test.jsp file that I run on the server:
<%# 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>Test jsp</title>
</head>
<body>
<% String firstName = (String) request.getAttribute("firstName");
out.println("Hello :" + firstName);%>
</body>
</html>
However, when I type in the following URL, I still get a "null" result (even after refreshing): see Picture.
Note: my ultimate goal is to do have an event at some point that sends a POST request from a java file and display its result in the jsp page. If I understood well from my research, I would have to do it via a Servlet with a DispacherRequest forwarding method. But I first want to understand why the simple aforementioned code isnt working).
Thank you for your help !
You mention that you're trying to display a query parameter from the URL. A query or request parameter is not the same as a request attribute.
To get a query parameter, you would have to use the getParameter() method:
String firstName = request.getParameter("firstName")

Null pointer exception on runReportToPdf - when trying to get report in JSP

I am trying to integrate my report in JSP page. Report created using jaspersoft studio. But i am getting null pointer exception on runReportToPdf line. I am totally new to this report and web application. So please someone help to resolve this and get excepted result. Quick support will be very much appreciated. Thanks.
<%# page import="java.io.*"%>
<%# page import="java.sql.Connection"%>
<%# page import="java.sql.DriverManager"%>
<%# page import="java.util.HashMap"%>
<%# page import="java.util.Map"%>
<%# page import="net.sf.jasperreports.engine.*"%>
<%# page trimDirectiveWhitespaces="true" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Report!</h2>
<%
Connection con = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#192.168.0.248:1521:incomingqc", "inqc", "megaWIN123$");
System.out.println("i AM IN CONNECTION");
}catch (Exception ex) {
System.out.println("i AM ex para");
ex.printStackTrace();
}
File reportFile = new File(application.getRealPath("Blank_A4_Landscape.jasper"));//your report_name.jasper file
Map parameters = new HashMap();
byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), parameters, con);
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
ServletOutputStream outStream = response.getOutputStream();
outStream.write(bytes, 0, bytes.length);
outStream.flush();
outStream.close();
%>
</body>
</html>
PDF and HTML content cannot be mixed. When the JSF page generates the HTML, it writes to a temporary buffer. That temporary buffer is sent to the browser once JSF is told that the response is complete.
In the given code, here is a rough idea of what the web browser will receive:
<html><head></head><body><h2>Report!</h2>%PDFNΘs​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s...</body></html>
For the browser to display the report there are a few options:
Generate an HTML version of the report and use <h:outputFormat> to inject the report content into the existing web page.
Generate a PDF version of the report and use <h:commandLink> or <h:commandButton> with an action that writes the PDF to the browser, much as you've already done.
Mixing both approaches as shown in the question, however, will not produce the desired result.
See also:
How to provide a file download from a JSF backing bean?
Send a PDF to browser via JSF
http://www.jroller.com/hakan/entry/jasperreports_and_jsf_integration

How to link different URLs to different items in forEach loop in JSP page? [duplicate]

This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 7 years ago.
I have a facultylist.jsp page which displays List<Faculty> as a request attribute parameter in forEach loop and I want every item in this loop to be a link to specified faculty facultyview.jsp. How can I achieve that ?
facultylist.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculties</title>
</head>
<body>
<h1>Faculties list</h1>
<ul>
<c:forEach var="faculty" items="${faculties}">
<li>${faculty.name}</li>
</c:forEach>
</ul>
</body>
</html>
facultyview.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculty</title>
</head>
<body>
<h1>${faculty.name}</h1>
<ul>
<li>Faculty name: <c:out value="${requestScope.name}"></c:out></li>
<li>Total seats: <c:out value="${requestScope.total_seats}"></c:out></li>
<li>Budget seats: <c:out value="${requestScope.budget_seats}"></c:out></li>
</ul>
apply for this faculty
</body>
</html>
I don't know if its may help, but I'm using following technologies: tomcat, jsp, servlets and log4j.In my project I have one FrontController, which is a servlet that interacts with Command pattern - each Command returns a path to resource and action type: forward or redirect.
You can solve your issue by adding a query params to the link, edit with respect to the comment. Note that you cannot access directly the JSP pages that reside under WEB-INF folder. Also, to encode properly the paramters, better construct url like
<c:url value="facultyview.jsp" var="url">
<c:param name="name" value="${faculty.name}"/>
<c:param name="total_seats" value="${faculty.total_seats}"/>
<c:param name="budget_seats" value="${faculty.budget_seats}"/>
</c:url>
<li>${faculty.name}</li>
and than than in your facultyview.jsp read from the query params
<li>Faculty name: ${param.name}</li>
<li>Total seats: ${param.total_seats}</li>
<li>Budget seats:${param.budget_seats}</li>
This direct JSP communication should solve your immediate issue, but a truly proper way would be to pass an id of a faculty to servlet, fetch the faculty instance, place in the model and pass to the view.
in other way is just take the selected value from the drop down with a name and forward it to front controller servlet ,there use if else conditions and depends on the value you could forward the request to corresponding jsp or servlet
<select name="value"> in jsp
String value=req.getParameter("value"); in servlet
if()
else if()
If you have a field in Faculty entity simply:
${faculty.name}
#Mark: faculty represents an entity from database, i'm not sure if I want to change it adding another field, or you mean some other way ?
Add a field does not means you must change database, you can have a Helper entity that inherits from Faculty and have more fields you can need,
public class FacultyFormHelper extends Faculty implements Serializable {
private String URL;
and in your view:
${facultyHelper.name}
But, If you don't want to modify your database, either create a helper class, you may add onclick event to the <a>
<a onclick="goToURL(${faculty.id})">
Then retrieve the data... i'm not sure how you get the urls... from a variable in the view, ajax call or wherever you have this URL...

Categories