I am doing one project on Struts 2 that I am getting knowledge little by little bit..
I have the action like this
<action name="backaction" class="HandlerAction">
<result name="user_profile" type="redirect">hai.jsp</result>
In the class Handler action I have the object userprofile in which the name and age are members.
In the execute function
log.info(userprofile.getName())//it is giving name xyz
return "user_profile"
I am getting hai.jsp but I am unable to retreive the value in that object userprofile in jsp.
hai.jsp is as follows..
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<s:textfield name="user_name" value="%{userprofile.name}"/>
</body>
</html>
I tried by putting as value="%{name}" also but i am not getting the value xyz..
The problem is with
<result name="user_profile" type="redirect">hai.jsp</result>
since you are using redirect result type which means that framework will create a new Request and response object and discarding old request/response Object.So when you are returning from your action your user-object is theirs in the value stack till you tell S2 that you want to use redirect result type.
On seeing redirect result type, it will discard any existing data and will create a new request for you place its content in value stack and that's why this is not working for you.I am not sure why you using redirect result type since you can do the same using any build in result type say success.
If you still want to use redirect result, i suggest you to save the user-profile data in either Session and retrieve it in your next action or use scope-interceptor
Struts2 Redirect Result
Calls the {#link HttpServletResponse#sendRedirect(String) sendRedirect} method to the location specified. The response is told to redirect the browser to the specified location (a new request from the client). The consequence of doing this means that the action (action instance, action errors, field errors, etc) that was just executed is lost and no longer available. This is because actions are built on a single-thread model. The only way to pass data is through the session or with web parameters (url?name=value) which can be OGNL expressions.
Related
I'm totally new in jsp/servlet and working with an application that I have many jsp pages and servlet.
In the first jsp page I choose a customer.
<select id ="sel" name="customer">
<option>customer1</option>
<option>customer2</option>
<option>customer3</option>
<option>customer4</option>
</select>
In the second jsp page it shows me the menu related to this customer(for example I choose configuration and goes to the third jsp page )
<% HttpSession session = request.getSession(true);
String chos_cust=request.getParameter("customer");
session.setAttribute("cust_menu",chos_cust); %>
....
<%= session.getAttribute("cust_menu")%>
In the third jsp page I choose cateories related to this customer(there are many categories for each customer)
An sql query runs here to show categories as radio buttons:
<input type="radio" name="chos_gr" value="${groups.group_name}"checked > ${groups.group_name}
In the forth jsp page according to the chosen category it will show subcategories. In this jsp page I have three div
in html form with hidden type.In the first div list of products has been shown , the second div is for adding a product and in the last div products can be deleted.
String config_gr = request.getParameter("chos_gr");
session.setAttribute("config_menu",config_gr);
I have used a servlet to do these operations(add, delete). It works well but when I add or delete a product and use requestDispstcher/forward in servlet to back to the last jsp to see the result(list of products) it
shows null for category and nothing in list of products.
If I should return the value of category in the servlet to the last jsp?
Could someone tell me what the problem is?
I can't add a comment for this post. As #underdog suggested I used ${sessionScope.config_menu} in the last jsp and it still shows null for category. It's weird because I get the customer value when I return to the last jsp to see the result but nothing for category.
You are adding all the object/values in a session attribute. With request dispatcher you forward the flow to a jsp with request & response objects. The request object contains no info of the customer you have set in the session object.
In the jsp try accessing the values from the session scope.
${sessionScope.config_menu} would give you the desired output.
Instead of using a response.sendRedirect(url), consider using following:
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request,response);
Above code with the getRequestDispatcher() will allow you to include your calling servlet's request by using dispatcher.forward, which will include the session attributes you were missing.
[NOTE: OP was already doing the above]
[UPDATE]
Based on the way you were suggesting to code certain parameters in <input type="hidden" name="myfield"> fields, I suspect, you did nothing else to store the values. Which means, the first time around, they might have been set using the parameters from the previous request, but when using the dispatcher.forward, this did not happen.
For fields to be initiated with the appropriate value, they require to be made available either through request parameters (e.g. GET parameters, encoded in the URL), or otherwise set within the JSP itself trough <input type="hidden" value="${whatever}" name="myfield"> or similar code. I am also missing that part of the code to be able to validate.
Using a dispatcher.forward(), you might not have required parameters set.
I want to read parameter passed by one JSP to another using HTTP POST method.
Following are my two JSP files.
One.jsp
<body>
<form action="Two.jsp" method="post">
<input type="text" value="test value" name="txtOne">
<input type="submit" value="Submit">
</form>
</body>
Two.jsp
<body>
<% response.getWriter().println(request.getParameter("txtOne")); %>
</body>
I can access the parameter in Two.jsp file using scriplet.
I want to avoid scriplet, so I am looking for JavaScript or jQuery solution.
So far I have searched and found JavaScript solution which only reads parameters sent using GET method(query string only).
Any suggestion will be appreciated.
Thanks in advance.
Solution:
I was able to get the value using JSTL:
${param.txtOne}
Try expression language - ${txtOne}, of if the method in one.jsp is GET instead of POST, you would be able to read URL in javascript and extract parameter value from there.
Yes you can get the value by use of JSTL
${param.txtOne}
Update
From EL info page
In EL there are several implicit objects available.
EL Scriptlet (out.print and null checks omitted!)
---------------------------------- ---------------------------------------------
${param.foo} request.getParameter("foo");
${paramValues.foo} request.getParameterValues("foo");
${header['user-agent']} request.getHeader("user-agent");
${pageContext.request.contextPath} request.getContextPath();
${cookie.somename} Too verbose (start with request.getCookies())
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext: The context for the JSP page. Provides access to various objects including:
servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie
initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
I want to avoid scriplet, so I am looking for JavaScript or jquery solution.
Simply you cannot.
request object can only accessible on server side, i.e in your JSP. You cannot access request or response object in client side that i.e javascript/jquery/whatever.
If you want access jsp value in javascript, try something like
var news=<%= request.getParameter("txtOne")) %>;
As a side note: Avoid scriplets and go for Expression language.
It is time for you to move to some MVC framework like struts than plain JSP. Then you can fill an ActionForm from parameters and use them on Two.jsp.
Is it possible to pass parameter from a JSP page to a JSF page's backing bean?
JSP page is popup window open when I invoke a button in JSF page and my selected value in JSP page, I should be able to pass to JSF's backing bean.
P.S. When I add comment and I put #anyname when someone replies, #namyname part is getting truncated.
Update 1
To get the selected value from JSP to bean I did a crude approach.
I added the the following in JSP
String str = request.getParameter("selectname");
and assigned string str to a hidden field
<input type="hidden" name="hid" value="<%=str%>" />
and in my bean I am getting the value like the following
logger.info("jsp value "+FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("hid"));
This almost works except I always gets the value which I previously selects.
E.g. First time when I selects 1 and value returned in bean is null, second time when I selects 2, value returned is 1.
How could I get the currently selected value in my bean?
First, if your JSF view technology is JSP, then you can use the <h:> tags in the jsp and it becomes straightforward 0 just add a <h:commandButton action="#{yourBean.yourMethod}" />
Otherwise, you still can perhaps, but I'd suggest that you make your popup also a JSF page. JSF and JSP don't coexist well. If you really must retain the situation, then you can try to emulate a JSF POST request to the target jsf URL.
f:viewParam lets you associate bean
properties with request parameters
–
-This introduces several new capabilities
New tags that navigate via GET instead of POST and tags that
navigate via GET instead of POST, and send parameters along with the
address
Sending data from non-JSF forms to JSF pages
Make results pages results pages bookmarkable
This is a new feature in JSF 2.0
example:
<f:viewParam name="fg" value="#{colorPreferences.foreground}" />
If the “fg” parameter is non-null, it is passed to
setForeground before the page is rendered
<f:metadata>
<f:viewParam name="param1" value="#{bean.prop1}"/>
<f:viewParam name="param2" value="#{bean.prop2}"/>
</f:metadata>
<h:head>…</h:head>
<h:body>
Blah Blah blah #{bean prop1} , blah, #{bean.prop1}
</h:body>
If the page is called with page.jsp?param1=foo¶m2=bar, then “foo” and “bar” are passed to “setProp1” and “setProp2” before the page is rendered. If any of the parameters are null (i.e., no such request parameter exists), then the associated setter is not called at all, and the bean has its normal value for that property
You can find the answer from the JSF tutorial http://www.coreservlets.com/JSF-Tutorial/jsf2/
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)
I am new to JSP and Servlets.
What i want to know is the best way to pass some customized message to client web pages.
For example suppose i have a web page say student.jsp which has a form,to register a new student to our online application.after successfully inserting all the fields of the form,
user submits the form and data is submitted to our servlet for further processing.Now,Servlet validates it and add it to our database.so,now servlet should send a message indicating a
successful insertion of data entered by end user to end user (In our case student.jsp).
So,i could i pass this type of message to any client web page.
I don't want to pass this message as URL query String.
is there ant other better and secure way to pass these type of messages ...
use request.setAttribute("message", yourMessage) and then forward (request.getRequestDispatcher("targetPage.jsp").forward()) to the result page.
Then you can read the message in the target page via JSTL (<c:out value="${message}" />) or via request.getAttribute(..) (this one is not preferable - scriptlets should be avoided in jsp)
If you really need response.sendRedirect(..), then you can place the message in the session, and remove it after it is retrieved. For that you might have a custom tag, so that your jsp code doesn't look too 'ugly'.
I think it looks like this in JSTL:
<c:remove var="message" scope="session" />
I also think that, if "message" is a Java String, it can be set to the empty string after it's been used like this:
<c:set var="message" scope="session" value="" />
Actually, it also looks like it works if "message" is an array of Java Strings: String[]...