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.
Related
I use Thymeleaf with Spring MVC 4.1.1 and I want to be able to re-use my Spring messages (with the user's automatically detected locale) for my JavaScript files. E.g. I want to do:
$('#fooTitle').text(messages['foo.title']);
...and #fooTitle would contain the value under foo.title for the user locale.
What would be the easiest way to do this? Note that I would like a JavaScript object ("dictionary") or another data structure which is easy to navigate.
If not the easiest (but admittedly easy enough), the cleanest and most robust way is to use html5 data attributes to pass back-end data to js. This way, no matter if you move your javascript to external files, it still works. Use some element as container (choose the most proper for your case) as a carrier of the thymeleaf back-end retrieved i18n values and then access them with jQuery
in html:
<div id="container" th:attr="data-foo-title-txt=#{foo.title}"></div>
in js:
$('#fooTitle').text($("#container").data("foo-title-txt"));
See also my older similar answer, (although the OP has not left any sign of life after that :) )
,
JavaScript, Thymeleaf and localizing text
The easiest way to include localization messages would be:
$('#fooTitle').text([[#{foo.title}]])
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. )
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 );
});
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().
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.