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")
Related
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
I want to send a query string from one jsp page to jsp page but I want to hide the name-value pairs(attributes) at address bar when I send the query string.
First.jsp
<%# 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>First Page</title>
</head>
<body>
Click Here
</body>
</html>
Second.jsp
<%# 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>Second Page</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
Username : <%=username %><br/>
Password : <%=password %><br/>
</body>
</html>
Here, I pass a query string "Second.jsp?username=aditya123&password=abc12345" from First.jsp page to Second.jsp page but I want to send this without showing username and password attribute and their value at address bar.How can it possible?
Try this code
<form action="some.jsp" method="post">
<input type="text" name="uid" >
<input type="password" name="pass">
<input type="submit" name="login" >
</form>
Adding method ="post" hides the query stringThat is ,if i remove ' method="post" ' the processed url on pressing submit button would be having
Following as query string
uid="whatever i wrote in text field"&pass=""&login="Submit"
But after writing ' method="post" ' the new url will be free of query string...!
it is not possible with link.
alternate solution of not showing attribute is encode that name value pair and send it with url and decode at another page.
use either url encoder given by java or make use of your own encrypt-decrypt method.
The easiest thing to do is <form action="some.jsp" method="post">
Do this formatting in the html code.
And contents of url will be hidden...
You can store all the objects/information you want to pass to the second jsp file by storing the objects in the 'session' implicit object using session.setAttribute() method. In the second page you can retrieve those objects from the 'session' object using session.getAttribute(). My assumption here is that both the jsp pages are being executed in the same HttpSession, hence the same 'session' object will be available to both the jsp pages.
I'm not understanding how to set up an href to redirect to another jsp. This is what I have so far.
JSP with a href in it:
<%# 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>
<div align="center">
<h1>${gradebook.gradeBookName} was created.</h1>
<br> Home Page <br>
Add grades to GradeBook
</div>
</body>
</html>
The href "/createGradeBook3" is the link I want to re-direct to.
Controller:
#RequestMapping(value = "/viewGradeBook3", method = RequestMethod.GET)
public String viewGradeBook3(Locale locale, Model model)
{
return "viewGradeBook3";
}
Try to use the following code snippet in your controller -
return "redirect:/path/to/jsp";
Or you may use another URL that has been mapped with a controller's handler method. In this case the redirected request will be handled by the controller's handler method.
Hope it will help.
Thanks a lot.
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...
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.