Set request attributes when a Form is POSTed - java

Is there any way to set request attributes (not parameters) when a form is posted?
The problem I am trying to solve is: I have a JSP page displaying some data in a couple of dropdown lists. When the form is posted, my Controller servlet processes this request (based on the parameters set/specified in the form) and redirects to the same JSP page that is supposed to display addition details. I now want to display the same/earlier data in the dropdown lists without having to recompute or recalculate to get that same data.
And in the said JSP page, the dropdown lists in the form are populated by data that is specified through request attributes. Right now, after the Form is POSTed and I am redirected to the same JSP page the dropdown lists are empty because the necessary request attributes are not present.
I am quite the n00b when it comes to web apps, so an obvious & easy solution to this problem escapes me at the moment!
I am open to suggestions on how to restructure the control flow in the Servlet.
Some details about this app: standard Servlet + JSP, JSTL, running in Apache Tomcat 6.0.
Thanks.

.. and redirects to the same JSP page ..
You shouldn't fire a redirect here, but a forward. I.e. do not do
response.sendRedirect("page.jsp");
but rather do
request.getRequestDispatcher("page.jsp").forward(request, response);
This way the original request remains alive, including all the parameters and attributes. A redirect namely instructs the client to fire a brand new request, hereby garbaging the initial request.
In JSP you can access request parameters by ${param} in EL and you can access request attributes the same way with ${attributeKey} where attributeKey is the attribute key which you've used to set the object in the request scope in the servlet as follows:
request.setAttribute("attributeKey", someObject);
As to retaining HTML input values in a JSP, you just need to set the <input> element's value attribtue accordingly with the request parameter value:
<input name="foo" value="${param.foo}">
This prints the outcome of request.getParameter("foo") in template text. This has however a XSS risk, better is to escape any user-controlled input with help of JSTL's fn:escapeXml() as follows:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="foo" value="${fn:escapeXml(param.foo)}">
Retaining the selected option in a dropdown is a bit different story. You basically need to set the selected attribute of the <option> element in question. Assuming that you're -as one usually would do- using JSTL's <c:forEach> tag to display a Map<String, String> or maybe a List<JavaBean> of option values, you can solve it as follows (assuming ${countries} is a Map<String, String> which you've placed as an attribute in the request, session or application scope):
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}" ${country.key == param.country ? 'selected' : ''}>${country.value}</option>
</c:forEach>
</select>
This prints the selected attribute when the currently iterated option key equals the submitted one in the request parameter map.

Related

If I need to return value from servlet to jsp

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.

read parameters passed by one jsp to another

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.

How can I call setParameter in a request object?

This is probably due to my misunderstanding and incomplete information of JSP and JSTL. I have a web page where I have input elements such as
<input name="elementID" value="${param.elementID}"/>
When I am trying to save the form, I check for that elementID and other elements to conform to certain constraints "numeric, less than XXX". I show an error message if they don't. All the parameters are saved and user does not need to type it again after fixing the error.
After saved, when I am redirecting to the same page for the object to be edited, I am looking a way to set the parameter like request.setParameter("elementID",..) Is there a way to do this ? However the only thing I can find is request.setAttribute.
HTTP responses does not support passing parameters.
JSP/Servelets allows you to either use request.setAttribute or session.setAttribute for that purpose. Both methods are available when processing the page you're redirecting to, So basically, you got it right...
Also, from what you describe, you may want to check client-side validation: don't submit the form until you're validating it using client-side scripting (javascript)
After the servlet processes the form, (ie. saves the user input in the database), have the servlet forward (not redirect, because that would lose the request params) the request to the same jsp which contains the form. So there is no need to set the params since the servlet is just passing back the same request object.
The jsp which contains the form should have inputs similar to this:
<form>
...
<input type="text" value="${elementid}"/>
...
</form>
The syntax ${varname} is EL. So if the elementid already has a value, it that textfield will contain that value. Alternatively if you have not used EL and/or JSTL, you use scriptlets (but that is highly unadvisable, EL and/or JSTL should be the way):
<form>
...
<input type="text" value="<%= request.getParameter("elementid") %>"/>
...
</form>
I had to include <%# page isELIgnored="false"%> to my jsp to allow code like ${elementid} to work

Pass Value From JSP To JSF Page Backing Bean

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&param2=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/

Passing customized messages from Servlet to a JSP page?

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[]...

Categories