How can I call setParameter in a request object? - java

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

Related

How to process form by <jsp:setBean> and send it to servlet?

Could you help me to come up with solution.
There are JSP-page which sends form parameters to servlet.
Usually I parse parameters by HttpServletRequest.getParameter() which works fine for forms with tiny parameter numbers.
Now I'm developing application which has a lot of JSPs with number of parameters and the standard way of form processing is inconvenient.
I think that possible solution might be by using -action.
I don't understand whether it works for me.
I browsed a lot of materials but find nothing about it.
I mean that there is any information regarding possibility to get form parameters in jsp by ,
automatically create instance of the entity class,
map all the parameters to entity-properties and send the entity-instance to the servlet.
Please take a look at the code:
index.jsp
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="NewFormServlet" enctype="application/x-www-form-urlencoded">
<jsp:useBean id="client-bean" class="model.entity.Client" scope="request"/>
<h3>Please enter client information</h3><br>
Client first name<input type="text" name="first-name"/><br>
<jsp:setProperty name="client-bean" property="firstName" value="${requestScope.first-name}"/>
Client last name<input type="text" name="last-name"/><br>
<jsp:setProperty name="client-bean" property="lastName" value="${requestScope.last-name}"/>
Client address<input type="text" name="address" size="100"/><br>
<jsp:setProperty name="client-bean" property="address" value="${requestScope.address}"/>
Client city<input type="text" name="city"/><br>
<jsp:setProperty name="client-bean" property="city" param="${requestScope.city}"/>
Client postal code<input type="text" name="postal-code"><br>
<jsp:setProperty name="client-bean" property="postalCode" value="${requestScope.postal-code}"/>
<input type="hidden" name="jsp-identifier" value="client-form">
<input type="submit" value="Submit">
</form>
</body>
</html>
What is incorrect in this code? Thank you in advance.
You should first think about what occurs on server and what occurs in browser, as well as what is transmitted via HTTP. A form submission uses many phases :
on server : the JSP is executed using servlet context, session, and request attributes, with still full access at the previous request (parameters, ...) => all that generates a HTML page (with eventually css or javascript linked or included)
on browser : the browser gets and parses the HTML page, optionnaly gets linked resources (images, etc.), and display the form to the user
on browser : the user fills the input fields of the form and clicks the input button
on browser : the browser collates data form input fields, generate an new HTTP request (usually a POST one) and sends it to server
on server : the servlet container pre-processes the request (until that is is only a stream of bytes conforming to HTTP protocol) and calls the appropriate servlet method with a new HttpServletRequest reflecting current HTTP request, and a HttpServletResponse to prepare what will be sent back to browser after processing
All that means that anything you can do to request attributes in the JSP part will be lost at the time of processing of the submitted form by the servlet. You can only rely on session attributes, and on input form fields that will be accessible as request parameters.
So with your current JSP, the Servlet will find nothing in request attributes (it is a different HttpServletRequest) and will only be able to use parameters with names firstName, lastName, address, city, etc.
I can understand it is not the expected answer, but HTTP protocol is like that ...
EDIT per comment :
You can put the attribute in session, and then the servlet will use the same session as the JSP. But read again what I wrote above and think when things happen :
on server, when executing the JSP, you create an empty Client bean that you put in session scope, and use its value to initialize the form fields. Stop for the server part
on client, user fills the input fields - the server knows nothing on that - and submit the form through a new request
on server, the servlet has the values in request parameters, but the session still contains the previous values and so the Client bean has null values
I'm sorry but there's not enough magic for the server to automatically find in its attributes (either request or session) what comes from form submission : it only exists in request parameters, and it is the servlet job to process them and eventually put them in attributes.
Edit:
It appears that jsp:useBean is an old school way to collect up a group of parameter values for easier display on a page.
It does not add an attribute when the request is posted.
Based on that,
I see little value in the jsp:useBean tag,
since you can use el expressions to access attributes that you set in a servlet.
This does not help you get the posted parameter values into a bean in the servlet.
You can write a method on the bean to extract the parameter values from the request (visitor pattern).
For example:
class bean
{
private String value;
public void loadFromHttpServletRequest(final HttpServletRequest request)
{
value = request.getParameter("value");
}
}
Consider using a package like spring-mvc.

How does the Spring forms .jsp tag library work?

So I have a .jsp page which has a form on it, like this (naturally this is a massive simplification):
<form:form commandName="myCommand" method="post">
<form:select path="values" class="select-tall" multiple="multiple" id="mySelect">
<option>first</option>
<option>second</option>
<option>third</option>
</form:select>
<button type="submit" class="button">Save</button>
</form:form>
When the submit button is pressed, the form is submitted(somehow) and the path= attributes are used to bind the data inside the form elements to the properties of an instance of a plain old java object. I understand how this POJO is specified, and I understand how the POST request is routed to the correct controller, but I don't understand where or how the form values are mapped to the given POJO.
What I don't understand is:
How does the spring tag library modify the form such that this binding takes place?
How would one go about doing this in a manual or ad-hoc fashion(using a Javascript onSubmit() method, say)?
Essentially my question is: How does the spring-form.tld tag library work?
Any resources, or even a high-level explanation in your own words, would be extremely helpful.
I've implemented a work-around solution in the mean time (dynamically adding items to a hidden form element), but I feel like this is hack-y and the wrong solution.

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 do I send data between servlets?

I am pretty new to servlets and web development in general.
So basically I have a servlet that queries a database and returns some values, like a name. What I want is to turn the name into a link that opens a details page for that name (which another servlet would handle). How can I send the name to the other servlet so it can query a database for the relevant details?
Maybe I'm taking the wrong approach?
Edit: I am using Tomcat 5.5
Pass it as request parameter.
Either add it to the query string of the URL of the link to the other servlet which is then available by request.getParameter("name") in the doGet() method.
link
Or add it as a hidden input field in a POST form which submits to the other servlet which is then available by request.getParameter("name") in the doPost() method.
<form action="otherservlet" method="post">
<input type="hidden" name="name" value="${name}" />
<input type="submit" />
</form>
See also:
Servlets info page - contains a Hello World
Not sure if I understand correctly, but you may look at javax.servlet.RequestDispatcher and forward the url to the second servlet.
The url could be created using the name:
http://myhost.mydomain/my.context/servlet2.do?name=John
I would create the URL either in the first servlet or in a client using a configurable template for the URL. This way both servlets are clearly separated - you can even have each one on different machine.

Set request attributes when a Form is POSTed

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.

Categories