Sending Information from a Servlet to a JSP - java

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?

Related

How to change the url after forwarding a servlet to jsp page?

I have a search.jsp page that has some html content and a form. When the form is submitted, there is a servlet handle the form data and forward the results to the search.jsp page. However, the url in the browser after processing the form is changed to the servlet name:
http://localhost:8080/MyProject/SearchServlet
not the search.jsp page:
http://localhost:8080/MyProject/Search.jsp
How I can change the url to the search.jsp? In other words, I just want to refresh the search.jsp page to display the results in the same page. How I can do that?
You cannot do that by forwarding the request: you need to "tell" the browser to generate a new http request by using the response.sendRedirect() method.
Now the question is why do you want the url bar to display the name of the Jsp?
Hiding the real destination path is a desired feature when forwarding requests: users do not need to know the server side redirects (that's how they are also called) happening in your web app.
Think about it: to carry out its tasks a servlet potentially can forward the request a number of times before getting to the final destination: you don't want the url bar to change each and every single time.
Give a fancier name to your servlet like: "Search" rather than "SearchServlet" so that users will know they are on the search page of your web application and not in the "SearchServlet" page.
In addition to that, if you visit any professional website, you will hardly ever see the .jsp or .html or .php extension on the address bar. While that is not a requirement or specification and you are free to do so, I believe the first approach is best practice (it looks even better to me honestly). There is even a folder WEB-INF whose purpose is to hide your .jsp pages from direct access via url bar.
What I like doing is having a servlet as the landing-welcome page of the web app, that will be responsible to forward and redirect requests based on the user input and the inner working of the application.
Now back to your final request (pun intended)
"In other words, I just want to refresh the search.jsp page to display the results in the same page. How I can do that?"
What I would do is:
redirect the user to the "Search" servlet from the welcome/home servlet.
In the doGet method of the Search servlet I would forward the request to the search.jsp page (you could set attributes before forwarding if you need to).
In the search.jsp I would set the action attribute of the form to "Search" (the name of the servlet) and the method to POST.
In the doPost method of the Search servlet you would implement whatever logic you wish to implement and finally forward the request to the search.jsp
After hitting the search button (and even after the submit button is clicked) what the user will see on the address bar is simply
http://localhost:8080/MyProject/Search
Hope that makes sense.
Are you using the same search.jsp for searching and well as showing the result? It is possible to use the same jsp to perform both the functions but it's easier and desirable to make another jsp which will only show the results.
If you are not able to see the results on search.jsp then make sure that you are setting the proper response in the Servlet class before forwarding it to the jsp and also whether you are reading the response sent by the Servlet class properly in the jsp.
If you want, the page to not refresh at all, then go for AJAX.

jsp:forward in jsp:include doesn't prevent the original page to finish processing?

To understand the question I will explain the situation:
main.jsp - the main window of the application
jsp_seacurity.jsp - JSP file which send redirect in case user has no access to given page (I created separate file to reuse it in different pages)
noaccess.jsp - access denied page
In my main.jsp, one of the first lines is:
<jsp:include page="jsp_security.jsp?bo_item=main&bo_permission=view"/>
In jsp_security.jsp I do some checks and if the user doesn't have permission for specific part of application I have the following code:
<jsp:forward page="noaccess.jsp"/>
After signing in with user without permission for main.jsp, I have noticed, Glassfish was showing exception in log file, which was occurring in some line of main.jsp which is after my jsp:include. I have checked jsp:include documentation and that was what I found
When the include action is finished, the JSP container continues
processing the remainder of the JSP file.
And now the question is, does it continue processing main.jsp even after I perform jsp:forward in jsp_security.jsp? Is there any workaround for this? I'm not pro in security, maybe what I'm doing is completely wrong?
Thanks for help,
Serhiy.
It does. What this line puts in the generated servlet file (a jsp is compiled to a servlet), is request.getRequestDispatcher("target.jsp").forward(req, resp).
This does not mean the doGet() method returns - it will continue to execute.
That's why you should use a Filter to add security checks. If the condition is not met, you don't call chain.doFilter() but redirect to a 'forbidden' page instead.

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

How to handle HTML tags in servlet java program?

1) In my servlet program, I have a statement which will be printed using the code as follows,
out.println("<b>This is servlet output</b>");
Instead of getting printed in bold, it just gets printed with the tag in the broswer itself.
How to rectify the same?
2) Also, in the servlet page after the submission of a jsp form, I want to add the below HTML tag inside the java code of the servlet program.
Go to JSP form
How to achieve the same? Please advise.
1) The browser is interpreting your output like text, try adding
response.setContentType("text/html");
This line tells the browser that you're sending HTML and that it should be interpreted that way.
2) The same as bold text
out.println("Go to JSP form");
On a related note, I'd suggest that none of your Servlet class directly write HTML content to the response page. Servlet are made to handle forms, and aren't easy to use when it comes to write HTML responses.
Once thing you can try is to write the response in a JSP page, then forwarding the request to the JSP so it can handle user output.
Here is a sample:
1) servet_output.jsp
<b>My bold test</b>
Go to JSP form
2) Your servlet redirects to the JSP page:
request.getRequestDispatcher("servlet_output.jsp").forward(request, response);
This way, your servlet handles the request, and the JSP takes care of writing the response to the browser.
Don't use servlets for html.jsp is the right place to use that.
just use
request.getRequestDispatcher("name.jsp").forward(request, response);
and write html code there.

Categories