Servlet not sending parameter to .jsp file - java

So, I have this Servlet that should send a parameter to a .jsp file:
request.setAttribute("parameter1", new BigDecimal(50));
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB/pages/page1.jsp");
requestDispatcher.forward(request, response);
However, when I try to alert this parameter with some javascript code inside the jsp, I get an empty message. Also, if I print the attribute to the console with Java using JSP Expression, I'm getting null.. So, I think I'm not correctly sending the parameter in this servlet, can someone help me here?

There are two ways you can accomplish this.
Using a JSP expression you would use <%= %> as (notice no ; at the end)
data : [<%= parameter1 %>, Y, Z]
The second and preferred way is to use JSP EL syntax and reference the request attribute directly using ${ } as
data : [${parameter1}, Y, Z]
The first option requires you to pull the attribute out of its scope first. The second doesn't.
BigDecimal parameter1 = (BigDecimal) request.getAttribute("parameter1");

SOLUTION:
I can't really see the difference, but just changing from:
request.setAttribute("parameter1", new BigDecimal(50));
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB/pages/page1.jsp");
requestDispatcher.forward(request, response);
to:
request.setAttribute("parameter1", new BigDecimal(50));
request.getRequestDispatcher("/WEB/pages/page1.jsp").forward(request, response);
allowed the alert(${parameter1}); to display the actual value that I passed, however, I still got null when reading the parameter with java. Also, some javascript code I had to display a chart stopped working.
So, I've tried to pass the parameters by session:
request.getSession().setAttribute("parameter1", new BigDecimal(50));
request.sendRedirect("/WEB/pages/page1.jsp");
This worked fine, now I can get my parameters both with javascript and java in the .jsp file.
It seems that redirecting to a new request using sendRedirect doesn't crash the javascript code in the .jsp file, however, I don't really know why this approach is working face the others, so I apologize for this poor answer, I've never really worked much with servlets and Jsp's but I really appreciate a more conclusive answer than mine, so I get to learn more too.

Related

How to redirect from inside a JSP

I have a JSP page and need to introduce conditional redirect logic. For instance, if a variable is above a certain threshold, then continue rendering the JSP like normal. Otherwise, I need to redirect the browser to, say, http://myapp.example.com/fizz.
if(var > threshold) {
// Render page like normal
} else {
// Redirect to http://myapp.example.com/fizz.
}
Any ideas as to how I could accomplish the redirect portion of this (from inside a JSP page)?
Use
reponse.sendRedirect("http://myapp.example.com/fizz");
Just add this
Try this-
<%
// New location to be redirected
String site = new String("http://myapp.example.com/fizz");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
or you can also use-
<%
response.sendRedirect("http://myapp.example.com/fizz");
%>
You can use any approach from both of them.
#IAmYourFaja
If you want skip scriplet for better practice of code, then try like this by JSTL tag.
<c:if test="${var gt threshold}">
<c:redirect url="http://myapp.example.com/fizz"/> // Redirect to http://myapp.example.com/fizz.
</c:if>
Don't need to add any other things. hope it will help you.
inside your else loop you can use
response.sendRedirect("http://myapp.example.com/fizz");
yes the Url should be within double quotes("") because
response.sendRedirect() accepts a String argument
and yes a ; should be at the end otherwise your code wont compile.
String site = new String("http://www.google.com");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
Regarding your query in the gau123 answer to your question
if I don't specify "http://", then what if I want to use SSL (https)?
For that you could use ur project path,for example if you want to go to the link http://myapp.example.com/fizz or even with https://myapp.example.com/fizz
you will use reponse.sendRedirect("../fizz");
In both cases it will redirect you to the fizz page
Also Most reliable would be to create a domain-relative URL with the context path included.
response.sendRedirect(request.getContextPath() + "/fizz");
(Referred from Send redirect to relative path in JSP?)

Get data from servlet to JSP without forward?

I need a double value from my servlet to markup in my JSP. My doGet() is sending back formatted HTML tables with values from an ArrayList, so after I got that working I decided to tackle this part.
Servlet:
//Code getting the tables I need
//Send back the result, this all works good
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(returnAsHTML.toString());
What I added to try and get the double value
//Send back the result
double test = 20;
request.setAttribute("Test",test);
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(returnAsHTML.toString());
getServletContext().getRequestDispatcher("index.jsp").forward(request,response);
In JSP:
<!-- This variable is unresolved -->
<small>Test : ${Test}</small>
The forwarding seems to crash the whole party. I am new to JSP, I'm sure I am missing something small. I need to keep the response.getWriter() stuff there, it gets a lot of the information I need. Now I just don't know how to get my double values I need as well, because they will be displayed on a whole different part of the page.
You cannot write output to the servletOutputStream and redirect at the same time.
What do you expect from the browser: to display content or to navigate to another page? If the first, don't redirect. If the second, don't display HTML content.
Try using httpsession. Encapsulate whatever object you have using session.setAttribiute().
Then forward it using the sendRedirect() method.
Might be of this kind
HttpSession session=request.getSession();
double test = 20;
session.setAttribute("Test",test);
response.sendRedirect("Index.jsp");
On the JSP page
String s=(String)session.getAttribite("Test");
double d=Double.parseDouble(s);

Sending Information from a Servlet to a JSP

ok this is what I'm trying to do...I have 1 JSP page that gets 2 integers from a user. I use a form in this JSP so I can send the information to the servlet with the doGet method.
Then I want to take those numbers find the greatest common denominator and send that to another JSP. Getting the GCD isnt the issue right now, I'll just use function. But I cant figure out how to send anything to a new JSP.
request.setAttribute("TEST", "TESTING");
request.getRequestDispatcher("/WEB-INF/JSP2.jsp").forward(request, response);
Thats what I was playing around with to send information from the servlet to another JSP called JSP2. but whenever I hit submit on JSP (where I enter the numbers) I get an error.
Any help will be greatly appreciated
Show us the directory structure of your project. Make an index.jsp page saying hello and see if you can access it.
How do you deploy the application, show us the .war unzipped contents.
Your idea to use the requestDispatcher is correct, as well as adding stuff to the request, and later in another servlet/jsp using them. Note that if you access the index.jsp by server:port/index.jsp then the requestDispatcher argument should also be "your.jsp" and not "WEB-INF/the.jsp", ie remove the WEB-INF.
If your form is POSTing to your servlet, shouldn't you be implementing doPost instead of doGet?

jsp to servlet communication with parameters from URL, not a form

I'm using netbeans to create a web application that allows a cell phone user to scan a QR code and retrieve a journal's previous/next title information. The take home point is that there's no form that the user will input data into. The QR code will contain the search string at the end of the URL and I want the search to start on page load and output a page with the search results. For now (due to simplicity), my model is simply parsing an XML file of a small sample of MARC records. Oh, to top it off...I'm brand new to programming in java and using netbeans. I have no clue about what javabeans are, or any of the more advance techniques. So, with that background explanation here's my question.
I have created a java class (main method) that parses my xml and retrieves the results correctly. I have an index.jsp with my html in it. Within the index.jsp, I have no problem using get to get the title information from my URL. But I have no clue how I would get those parameters to a servlet that contains my java code. If I manage to get the search string to the servlet, then I have no idea how to send that data back to the index.jsp to display in the browser.
So far every example I've seen has assumed you're getting form data, but I need parameters found, processed and returned on page load...IOW, with no user input.
Thanks for any advice.
Ceci
Just put the necessary preprocessing code in doGet() method of the servlet:
String foo = request.getParameter("foo");
// ...
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
And call the URL of the servlet instead of the JSP one e.g. http://example.com/page?foo=bar instead of http://example.com/page.jsp?foo=bar in combination with a servlet mapping on an URL pattern of /page/*.
You can get the url parameter in servlet using request.getParameter("paramName");
and you can pass the attribute to page from servlet using forwarding request from servlet to jsp.
See Also
Servlet wiki page
Bear in mind that your JSP page will compile internally to a servlet. So you can retrieve the string and print it back in the same JSP. For instance assuming you get the string in a parameter called param you would have something like this in your JSP:
<%
String param = request.getParameter( "param" );
out.println( "String passed in was " + param );
%>
One last thing, you mentioned the main method -- that only gets executed for stand alone applications -- whereas you're talking web/JSP :O

Call from one JSP file to another JSP

I need to call from one JSP to another, do some stuff over there..
I am inside the caller jsp, inside his handleReqeust(HttpServletReqeust request)
method I am trying to forward the request to another JSP, to call the other JSP file to his handleRequest(HttpServletReqeust request) off course with the request object
I tried it:
RequestDispatcher dispatcher = request.getRequestDispatcher("/theSecondJspFile.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
but to make it work I need for it the object response, but I don't have it,
I am sure I missed something basic, but what?
From my question you can see, I don't have solid backround in java, so please correct me, or refer me to good guide if you feel it necessary
Thanks.
-------------------Edit--------------------------------------
I don't need a redirect, I just want to call another JSP file to his handleRequest method
I think it relate to HTML
What I can make out of your question is that you need to redirect to a secondpage.html from firstpage.html with some data. You can use both GET or POST method to send the data.
For the GET method just redirect to secondpage,html?data=value. The data will be available in the HttpRequest parameter in the controller of the secondpage.html where it can be used as required.
For the POST method you would need to post the data (using a form on firstpage.html) to secondpage.html. In the controller of the secondpage.html the data should be available in a similar way as before.
To include another JSP in a jsp :
<jsp:include page="foo.jsp"/>
You can find some reference material here.
I can not be sure, but what I think you are trying to do is to include a jsp page on to your jsp page and use the the objects and other variables declared in the first jsp page in your second.
<%# include file="mypage.jsp" %> should help you do this.
If this is not what you are looking for, please make your question tad bit more clear. some code will help really.
JSPs are supposed to be used to present the final result. JSPs are not supposed to be part of business tasks leading to this result. There you use normal Java classes for, starting with a servlet class. Let the HTTP request (the one which you enter in browser address bar or specify in some HTML link or form) point to the URL of the servlet instead. This way you can write Java code in the servlet the usual way to invoke other Java classes/methods and finally forward the request to a certain JSP file based on the outcome of the result and then just let that JSP present the final result.
To start with servlets, I'd suggest to read our Servlets info page.
I just added empty Iframe, and set his URL when I needed to call him

Categories