How to pass parameter to servlet - java

How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code:
<input name = "deleteGameButton" type = "submit" value = "Delete"
onclick = "submitToServlet('DeleteGameServlet');">
Here is the corresponding javascript:
function submitToServlet(newAction)
{
document.userGameForm.action = newAction;
}
I'd like the servlet to have access to userBean
<jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />

You kind of mess things here.
onclick() is Javascript and executed on client side. It has no (direct) way to update session-scoped bean. That bean is left on server-side, and was used when the HTML page was generated. To pass parameters back to servlet you need to use good old form fields, and submit the form.
Add more fields to the form, set their values before submit, then submit.
In Servlet call request.getParameter("name");
P.S. To automate this kind of things USE STRUTS. :-) Struts does exactly what you want: before passing the parameters to action, it populates the bean with those parameters. Transparently.

It depends exactly what you are trying to do. The
<jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />
tag will allow you to use the userBean attribute of the session in your jsp. If there is not a userBean attribute in the session, it will create a new one (using the default constructor for org.project.User) and place it in the session.
Then, when you get to the servlet, you can retrieve it with:
User user = (User)request.getSession().getAttribute("userBean");

getServletConfig().getServletContext().getRequestDispatcher("servlet path & name");
dispatcher.forward (request, response);

Hi try with the next tag:
<jsp:useBean id = "userBean" scope = "session" class = "org.project.User"/>
<jsp:setProperty name="beanName" property="propertyname" value="value"/>
</jsp:useBean>
more here
Good luck!

Related

Accessing the value of servlet in two jsps

I have a Servlet, which sends values to a JSP1. I am setting the values in the servlet as
request.setAttribute();
and i am using
dispatcher.forward(request, response);
and i am able to access these values in the JSP1 using expression language.
Now, I also need to use this in another JSP2.
These two JSP's are clubbed together to display in a single page. So, I need to access the values of the servlet in the second jsp as well. How can i do that?
As you say you have both the jsp clubbed in a single page , you can simply get the attribute as,
${attributeName}
it refers to the object set in the HttpServletRequest scope . I suggest to take the tutorial for Expression language
It is quite simple. If you are setting an attribute "attr1" in a servlet and then forwarding to a JSP (file1.jsp):
request.setAttribute("attr1", "first attr");
request.getRequestDispatcher("file1.jsp").forward(request, response);
And suppose in the first JSP (file1.jsp), you are including another JSP (say file2.jsp):
<body>
.....
<jsp:include page="file2.jsp"></jsp:include>
.....
</body>
Then in file2.jsp, you can access attr1 by calling the request object's getAttribute method:
<body>
....
${attr1}
....
</body>
In case of jsp:include action, when file2.jsp is included in file1.jsp, both request and response objects are passed to file2.jsp as parameters. So file2.jsp can access the attributes of file1.jsp's request object.

How to create a parameter in JSP? [duplicate]

What is the difference between getAttribute() and getParameter() methods within HttpServletRequest class?
getParameter() returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String
getAttribute() is for server-side usage only - you fill the request with attributes that you can use within the same request. For example - you set an attribute in a servlet, and read it from a JSP. Can be used for any object, not just string.
Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.
An attribute is a server variable that exists within a specified scope i.e.:
application, available for the life of the entire application
session, available for the life of the session
request, only available for the life of the request
page (JSP only), available for the current JSP page only
request.getParameter()
We use request.getParameter() to extract request parameters (i.e. data sent by posting a html form ). The request.getParameter() always returns String value and the data come from client.
request.getAttribute()
We use request.getAttribute() to get an object added to the request scope on the server side i.e. using request.setAttribute(). You can add any type of object you like here, Strings, Custom objects, in fact any object. You add the attribute to the request and forward the request to another resource, the client does not know about this. So all the code handling this would typically be in JSP/servlets. You can use request.setAttribute() to add extra-information and forward/redirect the current request to another resource.
For example,consider about first.jsp,
//First Page : first.jsp
<%# page import="java.util.*" import="java.io.*"%>
<% request.setAttribute("PAGE", "first.jsp");%>
<jsp:forward page="/second.jsp"/>
and second.jsp:
<%# page import="java.util.*" import="java.io.*"%>
From Which Page : <%=request.getAttribute("PAGE")%><br>
Data From Client : <%=request.getParameter("CLIENT")%>
From your browser, run first.jsp?CLIENT=you and the output on your browser is
From Which Page : *first.jsp*
Data From Client : you
The basic difference between getAttribute() and getParameter() is that the first method extracts a (serialized) Java object and the other provides a String value. For both cases a name is given so that its value (be it string or a java bean) can be looked up and extracted.
It is crucial to know that attributes are not parameters.
The return type for attributes is an Object, whereas the return type for a parameter is a String. When calling the getAttribute(String name) method, bear in mind that the attributes must be cast.
Additionally, there is no servlet specific attributes, and there are no session parameters.
This post is written with the purpose to connect on #Bozho's response, as additional information that can be useful for other people.
The difference between getAttribute and getParameter is that getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string. getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource (JSP / Servlet). So before you forward the request you can set an attribute which will be available to the next resource.
-getParameter() :
<html>
<body>
<form name="testForm" method="post" action="testJSP.jsp">
<input type="text" name="testParam" value="ClientParam">
<input type="submit">
</form>
</body>
</html>
<html>
<body>
<%
String sValue = request.getParameter("testParam");
%>
<%= sValue %>
</body>
</html>
request.getParameter("testParam") will get the value from the posted form of the input box named "testParam" which is "Client param". It will then print it out, so you should see "Client Param" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.
-getAttribute() :
request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.getAttribute always return object.
getParameter - Is used for getting the information you need from the Client's HTML page
getAttribute - This is used for getting the parameters set previously in another or the same JSP or Servlet page.
Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.
Using getAttribute, you can retrieve the Session variable.
from http://www.coderanch.com/t/361868/Servlets/java/request-getParameter-request-getAttribute
A "parameter" is a name/value pair sent from the client to the server
- typically, from an HTML form. Parameters can only have String values. Sometimes (e.g. using a GET request) you will see these
encoded directly into the URL (after the ?, each in the form
name=value, and each pair separated by an &). Other times, they are
included in the body of the request, when using methods such as POST.
An "attribute" is a server-local storage mechanism - nothing stored in
scoped attribues is ever transmitted outside the server unless you
explicitly make that happen. Attributes have String names, but store
Object values. Note that attributes are specific to Java (they store
Java Objects), while parameters are platform-independent (they are
only formatted strings composed of generic bytes).
There are four scopes of attributes in total: "page" (for JSPs and tag
files only), "request" (limited to the current client's request,
destroyed after request is completed), "session" (stored in the
client's session, invalidated after the session is terminated),
"application" (exist for all components to access during the entire
deployed lifetime of your application).
The bottom line is: use parameters when obtaining data from the
client, use scoped attributes when storing objects on the server for
use internally by your application only.
Another case when you should use .getParameter() is when forwarding with parameters in jsp:
<jsp:forward page="destination.jsp">
<jsp:param name="userName" value="hamid"/>
</jsp:forward>
In destination.jsp, you can access userName like this:
request.getParameter("userName")
Basic difference between getAttribute() and getParameter() is the return type.
java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)

Using JSP Bean in a Servlet

So I'm using a bean on a JSP page to store some data, like so:
<jsp:useBean id="data" class="myclass" scope="session" />
Is there anyway to access this bean from a servlet at a later time in the same session?
EDIT:
Apparently I'm not accessing the same session when I load the jsp page and the servlet. I'm printing out the session ID and it's giving me a different value for both pages, so I can't access the bean. Any ideas?
Yes, you can obtain it as attribute from the session by the id as key.
Data data = (Data) request.getSession().getAttribute("data");
Note that you need to put classes in a package, else you cannot import it. You'd also like to give it a more sensible name than myclass.

How do set request parameter value while calling java method?

I need to call a method of java class from jsp page.. While calling that in jsp page, need to set some request parameters also. How do i do that in jsp page?
Ex :
Java class :
public void execute() {
string msg = request.getParameter("text");
}
JSP file :
I need to call the method here and also need to set parameter values (eg : &text=hello)
Please help me...
Just embed your Java code inside the JSP. The object "request" is available to get parameters (parameters can't be set). Unless you plan to forward to another JSP in another context with an attribute should be enough.
To refer to your own class do not forget to add the import statement at the beginning of the JSP (similiar to an import in a Java class).
<!-- JSP starts here -->
<%#page import="test.MyClass" %>
<%
MyClass myClass = new MyClass();
String text=myClass.execute();
// This is not neccessary for this JSP since text variable is already available locally.
// Use it to forward to another page.
request.setAttribute("text");
%>
<p>
This is the <%=text%>
</p>
You cannot set request parameters. I suggest you try using the attributes as suggested in the previous answers.
You can't set request parameters - they're meant to have come from the client.
If you need to give the method some information, you should either use normal method parameters, or some other state. The request parameters are not appropriate for this, IMO.

Using request.setAttribute in a JSP page

Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as <input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />. This will then be available in the servlet as a request parameter.
Put it in the session (see request.getSession() - in a JSP this is available as simply session)
I recommend using the Session as it's easier to manage.
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.
You can do it using pageContext attributes, though:
In the JSP:
<form action="Enter.do">
<button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>
In the Servlet (linked to the "Enter.do" url-pattern):
String s=(String) request.getServletContext().getAttribute("opp");
There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.
If you want your requests to persists try this:
example: on your JSP or servlet page
request.getSession().setAttribute("SUBFAMILY", subFam);
and on any receiving page use the below lines to retrieve your session and data:
SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.

Categories

Resources