Passing variables from JSP to servlet - java

All the time, when I searched on Google, I got dozen of answers which are posted in Stackoverflow about passing variables to servlet from JSP.
But I am wondering, I don't get answer of: How to pass a variable from JSP to a servlet class? Is it possible?
Actually I am doing a simple PhoneBook application. Here I have to send contact id to a servlet for editing and deleting. How can I pass this value?
I know, we can pass variable from servlet to JSP by using request.setAttribute(key, value)
But when I used it to set variable in JSP and again get it by using session.getAttribute(key ) then result is null.
God help me.

The standard way of passing/submitting data to the server in the pure Servlets/JSP world (as in your case from the JSP to the servlet) is by using HTML form, i.e. the same way as when using other technologies (ASP.NET, PHP etc). And it doesn't matter whether it is a pure HTML page or JSP page. The recommended/most used method of submitting data from the form to the server is POST.
You also can pass data in the query string that is contained in the request URL after the path (this also happens when instead of POST you use GET method in the form). But that is for the simple cases, like constructing URLs for the pagination etc (you can see the example of constructing URLs with the additional queries here: Composing URL in JSP)
Example of passing parameters in the URL:
http://example.com/foo?param1=bar&page=100
For the difference between submitting data using GET and POST methods read here:
GET versus POST Requests on HTML
Forms
In HTML forms, what’s the difference between using the GET method
versus
POST?
So you can configure some servlet to process data sent/submitted from a JSP or HTML etc.
It is highly recommended to submit data using POST method and respectively to process the submitted data using the doPost() method in your servlet.
You will then get the parameters passed by the client in the request by using one of the following ServletRequest methods:
java.lang.String getParameter(java.lang.String
name)
java.util.Map
getParameterMap()
java.util.Enumeration
getParameterNames()
java.lang.String[] getParameterValues(java.lang.String
name)
Here is a nice tutorial with examples: Handling the Client Request: Form Data
The above tutorial is from the following course:
Building Web Apps in Java:
Beginning & Intermediate Servlet & JSP Tutorials
Another way of exchanging data using Java EE is by storing data as attributes in different scopes. (Following is the excerpt from one of my answers on SO)
There are 4 scopes in Java EE 5 (see The Java EE 5 Tutorial: Using Scope Objects). In Java EE 6 and in Java EE 7 there are 5 scopes (see The Java EE 6 Tutorial: Using Scopes and The Java EE 7 Tutorial: Using Scopes). The most used are:
Request scope
Session scope
Application scope (Web Context)
You can store some data in all the above scopes by setting the appropriate attribute.
Here is a quote from the Java EE API docs related to ServletRequest.setAttribute(String, Object) method in regard to request scope:
void setAttribute(java.lang.String name,
java.lang.Object o)
Stores an attribute in this request. Attributes are reset between
requests. This method is most often used in conjunction with
RequestDispatcher.
...
So with every new request the previous attributes you have set in request will be lost. After you have set an attribute in a request, you must forward the request to the desired page. If you redirect, this will be a totally NEW request, thus the attributes previously set will be lost. (If you still want use redirection read this: Servlet Redirection to same page with error message)
Those attributes that are set in a HttpSession (in the session scope) will live as long as the session lives and, of course, will be available to only the user to which session belongs.
As for the context attributes they are meant to be available to the whole web application (application scope) and for ALL users, plus they live as long as the web application lives.
Also maybe this article will be useful for you as well: How Java EE 6 Scopes Affect User Interactions
Also pay attention to the following issue. You wrote (quote):
I know , We can pass variable from servlet to jsp by using request.setAttribute(key , value)
But when I used it to set variable in jsp and again get it by using session.getAttribute(key ) then result is null.
As the users #neel and #Sanchit have noticed, you are setting an attribute in the request object, but trying to get it back from the session. No wonder you are getting null in this case.
Hope this will help you.

Related

Managing session and request attributes in Servlet

I have a very simple JSP page where it has one search box and based off the input, in the search box, it will return a response with a submit button to get the following response.
I noticed that whenever I use request.getattribute("foo") in my servlet to retrieve some request it returns null due to the request ending so I looked at the answers on here and started using session.getattribute("foo") instead. However, now I am stuck having session variables responses being set and it is causing my view to have old session data that isn't suppose to be there so now I have to use session.removeAttribute("foo"), whenever, I don't want that particular response data to be shown.
Is there a better way to go about managing this instead of having to use session.getattribute("foo"), session.removeAttribute("foo") and session.setattribute("foo")?
You should work with request.getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
Set an attribute:
request.getSession().setAttribute("foo")
And get attribute using:
request.getSession().getAttribute("foo")
It will be used in the context of the request and not effect other requests, so you don't need to remove attribute.
Read more in Servlets tutorial
Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level interface that allows the server to "remember" a set of information relevant to a particular user's on-going transaction, so that it can retrieve this information to handle any future requests from the same user.
You can go for request.getparameter("foo") or request.setparameter("foo", obj)
This can be used for every request, and it will not add to your session variables and basically will not make your "session object heavy".
Java doc:
Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

Java web development: transfer control from one servlet to another while passing the request object (Version 2)

EDIT: changed file name to 'follow-up.jsp' for clarity.
This is a shorter, and hopefully better version of a longer question I posted earlier today (link: Java web development: transfer control from one servlet to another while passing the request object).
I have a form that is POST-ed upon submit. In the corresponding servlet to which the POST action is done, I want to show either the form page again or a follow-up page, depending on whether validation succeeds. BOTH the form page AND the follow-up page need the form data submitted by the user; the form page needs it to re-populate the form fields, and the follow-up page needs it to show some of this data (for example, to have the user double-check that it is correct). Therefore, I want the request object containing the submitted data to be available to BOTH pages.
Forwarding back to the form is not a problem:
RequestDispatcher rd =
getServletContext().getRequestDispatcher("/form.jsp");
rd.forward(request, response);
But how do I reach the follow-up page (say, follow-up.jsp) in such a way that the request object containing the submitted form data is still accessible in that follow-up page?
The following doesn’t seem to work:
response.sendRedirect("/MyProject/follow-up.jsp");
This is because if “name” is a form parameter that was assigned to an attribute of the request object in the form handling servlet, with this attribute conveniently also being called "name", then the following line in follow-up.jsp:
Your name is: ${name}.
does NOT print the user-submitted name (instead it prints nothing, i.e. only “Your name is:”). In other words, the attributes of the original request object are no longer available in follow-up.jsp. This makes sense in that response.sendRedirect triggers a new HTTP-request (with its own request and response objects). But is not what I want.
Another (secondary) concern is that sendRedirect is unable to issue POST-requests (it only uses GET; see [link] response.sendRedirect() from Servlet to JSP does not seem to work).
EDIT: Also, I realise I could actually use:
rd.forward(request, response);
for BOTH requests. However, that would result in both pages having the same URL showing in the address bar (i.e. the name of the routing servlet, like "...../Register"). And that is definitely bad, because the form page and the follow-up are completely different pages; the follow-up page has little to do with the form (except for displaying some of the submitted form data).
Thanks.
In this case I believe you need to store the data not in request, but in a conversation scope....or in the session scope...regarding redirection not supporting post...then ideally all redirections by definition should be get requests only.....if you want to redirect using a a POST request please re-evaluate your approach...

In BrightSpotCMS HOWTO inspect the "request" object from HttpServlet before the JSP is rendered for a "Content" object

In many MVC frameworks when a request is made it goes to a controller/action class (based on the URL pattern among other things). If the developer wants to do something with the request object or other processes then it does that with in the execute or doGet or doPost etc methods & then forwards it to the dispatcher. The response type could be a JSON, JSP, XML etc.
I have a brightspot cms webapp in which I want to do something similar. It is based on the open source project dari framework.
In case of a object of type Content if I want to setup some pre-processing of variables to be used in the JSP page based on the request object, how can I do it? I am unable to find the point of intervention between the request going to conten type object AND request being forwarded to the backing JSP page.
I know I can just add scriptlets to the JSP page, but I had rather not do it for variety of reasons.
I was able to resolve this by adding a Filter for the URL pattern I was interested in. More info here.

Can a jsf managed bean behave like a servlet?

Normally, a servlet has doGet() and doPost() methods. They are utilized to capture the incoming request parameters, which can then be used in any part of the application, if the developer wishes so.
Now, If instead of using a servlet, a developer wishes to use a jsf managed bean, is there a way to get the request parameters in the bean itself ? If so , how can it be done ?
I have seen this POST which shows a way of getting stuff from request in JSF. Can this be used to get a request parameter in managed bean like this :
HttpServletRequest origRequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String myReqQuery1 = origRequest.getParameter("ReqQuery1");
In this case, will the application follow a jsf life cycle or a servlet life cycle or both ?
JSF does not really work like that. The form fields in the view (.jsf or whatever) are mirrored by fields and properties in the bean. They are automatically populated by JSF when the servlet is invoked further up the stack.
This makes the need to read HTTP parameters redundant except when the browser lands on a JSF page from a non-JSF based form. For that something like Spring-MVC can accept the URI being targetted and make a connection to the ManagedBean instance before redirecting the browser to a JSF powered URL.

JSP and Java Servlet problems

I am new to JSP and Java Servlet. I am quite confusing about Session object. I saw session When I learned PHP session and cookie. Are there complete different things? And how a Session object is created, structured and used. This object is in JSP or Java Servlet? could somebody tell me this by words(like concept). In addition, in what situation a JSP page would be appropriate for?(when should I use a Java Servlet and when should I use a Java Servlet Page).For Java Servlet object, for example, ran an email site. There will be a lot of users. How does one Java Servlet object deal with interactions from so many browsers?(like hundreds of logging, reading, etc.)I know there should be only one copy of Java Servlet object exists. But why? If only one there, when is it created and destroyed. Ah... So many questions. If someone can help me I will really grateful for this. Thanks a million!
? And how a Session object is created, structured and used.
It depends on the implementation of it, here is the contract
This object is in JSP or Java Servlet?
This is as an implicit object in jsp and it can be retrieved from request instance from servlet's service method
what situation a JSP page would be appropriate for?(when should I use a Java Servlet and when should I use a Java Servlet Page).For Java Servlet object, for example, ran an email site. There will be a lot of users. How does one Java Servlet object deal with interactions from so many browsers
Use jsp as view servlet as controller, See MVC
now there should be only one copy of Java Servlet object exists. But why? If only one there, when is it created and destroyed.
each request is served in different thread so why to create different instance, we can have one instance of servlet doing all this for us. and its alive until garbage collection clears it
See : Head First
You can think about a session object as a file . every user have a session with id called jsessionid , the structure of a session is normally a map data structure which store key value
in Servlert you can construct a session object like this
HttpSession session = request.getSession(true);
then you can add item to the session like this
session.setAttribute(string ,object); ex : session.setAttribute("username","foo");
the session object exist in servlet and jsp , and btw jsp eventually is a servlet
but the difference is that when u want to use session in a jsp page there is no need to construct it. its defeind by default just use it
session.setAttribute(string,object);
JSP page used when a page contains a lot of html element and have a lot of design
and jsp let you maintain the page easily on the other hand you can use servlet as jsp page
but you will deal with every line o html source code
JSP is preferred as a view in the MVC model
and the servlet as controller .
the server keeps one object for each servlet and when a new request come the servlet object put the new request (client ) in a new thread so if you have 100 client at a time the is
100 thread in server . but you can configure the server to construct more than one object of a servlet .
i hope i could help u ..
I think many of your questions would be answered if you had a look at the Java Servlet Life Cycle.

Categories

Resources