How to design an extendable HTML form without JavaScript? - java

Designing and processing a form where the user can add an arbitrary number of new input fields is very tedious without using JavaScript.
Currently I am doing the following: using two different submit buttons in a form, one for adding a new input field and one for submitting the form which results into a database request.
the used method is POST
for adding new input fields I would like to use GET but since two methods in one form is not possible I have to do it in the POST request.
making this for one type of input field is rather easy, but when you need to do this for sub-forms (some groups of input fields in the same form), this becomes not only tedious, but also error-prone!
I am not satisfied, is there a more intelligent way to realize this without starting to write a lot of processing code and doing redirection or at least ease the implementation to reduce the error risk!
Also, maybe there is a solution provided by Java to solve this generically elegant, since I am using Java Servlets.
With JavaScript turned on I would offer a separate solution, I am only concerned with the fall back solution, this is not the normal case.

See, working without JavaScript severely restrict your abilities: you have to rely upon the standard HTTP request/response cycle. In other words, you have to rebuild a new page (adding some input field) and send this new page each time - there's no workarounds.
Here's how I would implement it:
<form action="/path/to/action" method="post">
<input name="param_a" />
<input name="param_b" />
<button type="submit" name="next_input" value="param_c">Add a field</button>
<button type="submit" name="submit">Submit your form</button>
</form>
... then within the server-side code I'd just check whether next_input param is sent or not. If sent, its value will be used to get the control which is to be added - and give the corresponding value (param_d, for example) to the next next_input.
UPDATE: but I just can't help wondering is this really necessary. Usually we design for 'No JS' cases when these pages are typical landing pages (scanned by search robots). Thinking about some users that will go to your page without JS enabled, yet willing to use it with all pretty things enabled... well, it's not very cost-effective, to say the least. )

Related

Java web development: transfer control from one servlet to another while passing the request object [duplicate]

This question already has answers here:
Design Patterns web based applications [closed]
(5 answers)
Closed 6 years ago.
EDIT: I have posted a somewhat shorter and revised question here: Java web development: transfer control from one servlet to another while passing the request object (Version 2)
As more or less a beginner at Java web development, I’m unsure about how I should structure the flow between servlets/pages when a form is submitted (POST). It’s an elementary issue, I suspect this may be an easy question to answer for the experts. (Still, my book and some googling didn’t deliver a clear answer.) My question is a bit long, and that's because I want to make it clear where I'm coming from. Thanks for you patience.
Let’s say we have two servlets A en B, with each having its ‘own’ .jsp-page; let’s call those pages a.jsp and b.jsp respectively. Now as long as there are no forms on either page (i.e., no POST method used), it’s clear how things should go. That is, before any .jsp-page is shown, the corresponding servlet is activated, doing some preparation for the .jsp-page by setting the relevant data elements (most notably, as attributes of the request object) that the .jsp-page needs, then forwarding the request object (etc.) to the .jsp-page, which then actually displays the page with the data. So for example, a link on page a.jsp may link to the servlet B, and on clicking that link a GET-request for servlet B is triggered, which then does some preparation (setting some request attributes), before forwarding to its ‘own’ .jsp-page (i.e. b.jsp).
But now let’s assume that page a.jsp displays a form with a submit button, method=”POST” and action=”B”. Then yes, servlet B is activated, and this servlet has to determine whether the data entered by the user is valid. If the data is in fact valid, we can simply forward to b.jsp, no problem there. But what if the data is NOT valid?
In that case, we obviously want to show a.jsp (the form page) again, with the data that the user entered the first time still present. One way to achieve this, is to simply have servlet B forward to a.jsp (thus bypassing servlet A). However, there is a big problem with that: the URL shown to the user, in the address bar, will still read “……/B”. So the user will see the correct page (i.e., a.jsp, containing the form), but with the wrong URL (/B). So for example, if we take “Register” and “ThanksForRegistering” instead of “A” and “B”, the user will see register.jsp – but with URL “……/ThanksForRegistering”! Not good.
And calling ‘include()’ instead of ‘forward()’ on the request-dispatcher doesn’t seem to work either. If we do that, not only does it result in a GET-request (as opposed to the POST-request we want), but we actually lose the whole (original) request-object with its attributes (which we need, after all, to re-populate the form). At least, that’s what my own experimentation seems to show. So using ‘include()’ doesn’t seem like a viable option at all.
Another obvious idea is to have "action=A" (instead of "action=B") for the submit. Then the servlet A itself can handle the validation, and if validation fails it can simply forward to a.jsp again, no problem. BUT then what if validation succeeds? Then we want to show the follow-up page b.jsp, but that page may well need the attributes from the original request-object (from the form-submit) again; for example, to have the user check that his entered data was in fact all correct. So basically we have the same problem as before, but with the roles of A and B (and their respective .jsp-pages) reversed. So this doesn't seem like a real solution either.
And I don’t see any other alternatives.
So basically, I’d simply like to be able have one servlet give control back to another servlet, but with the request object being passed from the former to the latter servlet. Or, if that’s not possible, I’d want to be able to forward from servlet B to a.jsp directly, but with the correct URL shown to the user. Or any other way to accomplish what I want.
Many thanks.
I think that the assumption that there has to be one page per servlet is causing the problem here....have one servlet which based on input redirects,forwards or includes a particular page....you dont really need to always invoke a different servlet for a page.....you can have a single front controller with a view resolver the combination of which will redirect or forward to a page.
You can use filters to achieve the same thing or think of setting attributes in HttpSession if validation is successful and retrieve the data in all the pages whenever it is required.
session.setAttribute("object", object);
I hope this is what you are looking for.

server side client side field state altertions

I've seen some variations of this question throughout stackoverflow, but I have a specific use case I'd appriciate inputs for.
The simplest I can get this to is:
1. On a web site, I have a form with two input fields. When A is populated with 'XYZ' B should be disabled, in all other cases it should be enabled.
2. This "page" can also be saved to the a DB by the client.
So, I need to be able to render the 2nd disabled field both at client tab-out (easy, simple Javascript) and when this "form" is firsy being loaded (Simple, in JSP manipulate the field's attribute when the page is loaded).
But... I ended up having the exact same logic coded in two place. Now, consider this is required for hundreds of fields and tens of logical conditions, some times as complex as combination of 5 fields together, set of specific values to do this or that, etc. etc..
Bottom line , what approach would you consider to reuse (as much as possible) UI oriented validaion/field state alterations between server side and client side (cosider that I do not want to use AJAX call with every user typing in a field.).
Thanks
A component based MVC framework like JSF (JavaServer Faces) allows you to define that in a single place. Here's a kickoff example of the particular use case:
<h:form>
<h:panelGroup id="inputA">
<h:inputText value="#{bean.inputA}">
<f:ajax event="blur" render="inputB" />
</h:inputText>
</h:panelGroup>
<h:panelGroup id="inputB">
<h:inputText value="#{bean.inputB}" disabled="#{bean.inputA != 'XYZ'}" />
</h:panelGroup>
</h:form>
That's basically all. Only the javabean code is omitted, but that's not so relevant here. True, ajax is used here, but that's partcularly cheap and there's basically no other way to keep the same state on both the server and client side anyway.
The above XHTML (Facelets) example will generate the appropriate HTML/JS code which will do the work at both server and client side. The only disadvantage is maybe the learning curve and lot of changes in existing pages.
My answer would be much the same a BalusC's.
But first a clarification of terminology: If all you are doing is enabling/disabling an HTML field, we would typically say that is client side validation, regardless of whether it is done in Javascript or JSP.
Yes, in the JSP case the logic to disable/enable the fields runs on the server, but since all it is doing is setting a field for the client to display, it tends to fall into the general description of "client side validation"
The alternative (well actually 'in addition to') to client side validation is to validate the form fields when they get POSTed to the server. That checks that the client has actually obeyed your validation rules (e.g. they might disable javascript, or they might use a tool like firebug to re-enable the field you disabled, etc.)
You may well know all of that already, and terminology isn't super important, but I thought it was worth pointing out.
Now, back to your question.
I would do it all in javascript, and ignore the logic in the JSP.
All you need to do is take the piece of javascript that fires when they tab out of "A", and run it when the page loads.
In JQuery, you'd do something like (untested)
var check_field = function(f)
{
if(!f) f=$(this);
if(f.val()=='XYZ') $("#field_B").attr('disabled', true);
else $("#field_B").attr('disabled', false);
};
$(function()
{
var a = $("#field_A");
check_field(a);
a.blur( check_field );
});

Java Web Application

I am interested in creating a simple web application that will take in user input, convert it to an XML file and send the file to a database.
Coding wise I feel I am okay, it is just the general setup and what implementation to use I am a bit unsure of.
At the moment I have a JSP page containing a form, the user fills out the form and on submit a POST method is sent to a servlet, in the servlet doPost() method the servlet is instantiating a java object and passing it the user inputted data. The java object then writes that data to an XML file and sends it to the database via REST.
All I would be interested to know is if this the standard/optimal way of creating such a web application.
Any and all feedback is appreciated.
Thanks
For a "simple webapplication" this high level approach looks fine in general. However, if you want more critical feedback, you'd need to give more details about the low-level approach. It may for example happen that it isn't memory efficient and thus may break when the webapp is been used by over 10 users concurrently, just to give an example.
I only question the choice for the GET method. You'd normally only use it to retrieve data (SELECT), not to create/alter data (INSERT/UPDATE/DELETE). For that you'd normally use POST, so that no one can execute it "accidently" by just clicking a (bookmarked) link. Changing GET to POST isn't that hard, add method="post" to the <form> element and rename doGet() to doPost().

Passing parameter without use of HTML forms in JSP

I have done some research, and majority of the examples I have found use forms (obviously for user input) to collect data which is then passed to another JSP page through the request object.
My question is: Is it possible to pass a parameter between JSP pages if the parameter hasn't been set in HTML <form> tags?
There are a few ways to pass information from one JSP page to another.
1. Hidden values.
Simply write the data to an input field within a form with the type 'hidden', e.g.
<input type="hidden" name="mydata" value="<%=thedata%>">
Data written thus will get posted back when the relevant form is submitted. This can be a useful way to 'carry along' information as the user fills out a series of dialogs as all state is user side and the back and forward buttons will work as expected.
2. URL writing.
Attach parameters to URLs in links on the page, e.g.
<a href="another.jsp?mydata=<%=thedata>>Go!</a>
This also maintains the state with the client while removing the need for a form element to be submitted.
3. Cookies.
Should speak for itself.The state is still user side but is now handled by a cookie. More fragile in some ways since some people disable cookies. Also the back and forward buttons may do unexpected things if you are not careful
4. Server side (session)
Finally you could store the data in a session variable on one JSP and retrieve it on the next, e.g.
session.setAttribute(String key, Object value)
and
session.getAttribute(String key)
Here the state is kept server side which has some benefits (the user can browse away and return without losing his place, but tends to make the back and forward buttons in the browser a bit unreliable unless you are careful. Also the value is available to all pages.
It does however have the advantage that the information is never sent to the client and is thus more secure and more tamper proof.
There's no way a JSP page can tell the difference between a manually constructed GET url, e.g.:
Go to the next JSP page, versus something like:
<form method="get" action="/foo.jsp">
<input name="bar" value="baz">
</form>
Either way it can be accessed through getParameter or getParameterValues
Is that what you're asking?
You usually pass data between servlet/JSP or JSP pages in scoped attributes (in request, session or application). E.g. request.setAttribute("key", data) can set "key" attribute in one JSP, and request.getAttribute("key") gets you this data in other JSP (if multiple JSPs are processing same request).
It is possible to create fake parameters by wrapping your request, and overriding getParameter and similar method, if that is what you really need.
Update: my answer is talking about passing data between several parties which all process same request. This may or may not be what you want, as your question isn't clear.

How would you easily validate a JSP option pick list?

I need to validate this simple pick list:
<select name="<%= key %>">
<option value="ETC" SELECTED>Select an option...</option>
<option value="ONE">Lorem ipsum</option>
<option value="TWO">dolor sit amet</option>
</select>
So the user would never submit the form with the, excuse the repetition, "Select an option..." option selected. In principle I'm allowed to use JavaScript but It'd be interesting to learn how to solve it within JSP too.
You can never really satisfy the condition 'never submit a given value' because you don't have control over the client side. The user can always manipulate HTML to submit whatever they want.
It is a good approach is to use JavaScript to do client-side validation and give the user quick feedback and catch 99%+ of the cases, then do a server-side validation of the submitted parameters to catch the minority that don't have JS enabled or who manipulate the HTML to submit non-expected values.
Just remember that the client-side validation is optional, and is good for those 'common mistakes' input validation, but the server-side validation is mandatory for all input whether or not any client-side checks have been done on the given input.
Nowadays you usually don't validate in JSPs, because they only visualize whatever was processed earlier. So the only validation that you do "in jsps" is usually Javascript. For the rest (the real validation) I second what Pete answered: You have to do it serverside in whatever technique you are using there. When it's displayed in the JSP again, validation has hopefully long been done.
As I said "nowadays": When JSP was a shiny new concept, a lot more was done inside the boundaries of a JSP and sometimes even Forms were posted to JSPs. How to validate was even more nonstandard at that time.
JSP is a "view" in MVC pattern, and should therefore only be used to present the data to the user. Any application logic, including validation logic, should be done server-side.
If this JSP is intended to be a part of a large app, I would recommend using Spring MVC to set up your app, and writing a validator to validate the input.
But even if we're not talking about some large application here, the validation should still be done server-side, as others before me have already noted.

Categories

Resources