How do the getRequestDispatcher() and forward() methods work? - java

I'm making a login/registration page using JSP, JSTL, and a Java servlet, and I'm using, in the doPost() method of the servlet:
request.setAttribute("message", "invalid login");
request.getRequestDispatcher("index.jsp").forward(request, response);
to alert the user when he enters invalid login credentials from index.jsp.
This works, but I don't know why it works; here are my questions:
Why is setAttribute() called on the request object and not the response object?
As I understand it, I'm forwarding the request and response objects to index.jsp, but how does a jsp page handle these objects? It's a bunch of html, so is the response object altered so that it includes all the html code of index.jsp?
Why is getRequestDispatcher() an instance method? That is, why can't RequestDispatcher objects be created using a constructor?
Thank you.

The HttpServletRequest is passed along until the response is finally handled. That is, when the JSP is being rendered, the request object is still available. This is how you pass arbitrary data throughout the whole request handling process.
JSP files are compiled to custom servlets that write the HTML to the response.
The RequestDispatcher is created from the request because it needs to know about the servlet environment. Otherwise it wouldn't know how to dispatch anything.

Related

Setting a session and ajax call happens parallely

I am setting a session variable in doGet() like
HttpSession session = request.getSession(true);
session.setAttribute("MySessionVariable", "String goes here");
I am trying to display that in my JSP page upon ready like
<%= session.getAttribute("MySessionVariable")%>
and I am making a call to the servlet on ready like
<Script>
$(document).ready(function() {
$.ajax({
type : "GET",
url : "UserInfoDisplay"
});
});
</Script>
But what I see is that, the value is null for the first time and when I refresh again I get the value. That is the ajax call onReady and the page load happens parallely. How should I fix this? I want the data to appear on the first load itself.
Well, it's not exactly like that. Page load happens first, and when the page is loaded, it invokes the servlet. You have to take into account that <%= session.getAttribute("MySessionVariable")%> is executed server side, before the browser gets any HTML. Then, the browser gets the response and your script calls the server again and sets the property, but the page was already rendered. You have to do this in a different way. Can you explain what are you trying to achieve?
If you need it only for the first time, then why make a ajax call in the first place?
Ajax is meant for sending asynchronous requests. Correct me if I am wrong, the better approach would be to redirect a request to the servlet and get a response, isnt it?

Java Servlet execute method before serving page

I want to be able to have a method between getting the HTTP request and sending the webpage. A close equivalent to what I want is having some code on top of every jsp file.
Example:
<%
some.package.staticMethod();
%>
Does this make sense?
I believe ASP.net has a method Page_Load similar to what I want.
If this is applicable to all the responses for incoming HTTP requests, then you are talking about a Servlet Filter.

Change of scope from session to request

I am using a session scope to store the bean,and i want to project the bean value to the jsp page when needed like this way
request.getSession().setAttribute("bean", bean);
response.sendRedirect("test.jsp");
And in the jsp i am using the below code to get the value on jsp
<% bean1 bean = (bean1) session.getAttribute("bean");
%>
<%= bean.getValue() %>
Instead of using a session scope i want to use a request scope,so can i set my attribute in my servlet in this way
request.setAttribute("bean", bean);
So how can i call it on my jsp
can i say
<% bean1 bean = (bean1) request.getAttribute("bean");
But it is showing error.Or instead of using scriplet how can i show my output using JSTL.
You're not understanding what a redirect is. A redirect is a response you send to the browser so that the browser sends another, new request to the location you redirected to. So, when you call sendRedirect("test.jsp"), the browser will send a new request to test.jsp. And obviously, all the attributes you have stored in the current request won't be available anymore.
It's impossible, without context, to say if a redirect is something you should do in this case, or if you should instead forward to the JSP. A forward is very different from a redirect, since it only transfers the responsibility of the current request and response to another component. In that case, there would be a unique request, and the JSP could find the attribute set by the servlet in the request.
The only thing I can say is that, in a properly designed MVC application, the JSP is used as a view, and there should never be a direct request to the view. Each request should go through a controller.

Forwarding the request from one jsp to another jsp with all request parameters?

i have this scenario. User enter some stuff on jsp form in browser and submit. In servlet i process the request and show the jsp page1 to client which has just continue
button. Now on click of continue, i want to forward this request to another jsp page2 with all request parameter present on page1. basically i want to get all request parameters which were present in first request on page 2 also? I am not getting how should i go
for this? I dont think i can use jsp forward as per my understanding it would work only when both when we want to forward from jsp (on server side) not on client side?
There are two ways to implement that:
output all parameters in hidden fields, and submit them in the 2nd request
store everything in the session
Following are a pair of ways to achieve this
Put the information in session object in first request and access it from session object in second.
On the intermediate page displayed, have hidden form elements which will carry the values and send it back on continuing.
You can use Servlet Forward to pass all request parameters to another JSP or Servlet:
getServletContext().getRequestDispatcher("/yourJSP.jsp").forward(request, response);
Servlet forward will forward the existing request to another JSP or Servlet, so all the request parameters and attributes will be available to the destination JSP or Servlet (The reason you can use the Servlet forward is that JSP is also a Servlet after translation).
You may find following resources useful:
Pass data from servlet to jsp
Servlet Redirect vs Forward

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