I have a servlet application that page is an html form. I'd like to add some client-side code to validate the data. I'd like to avoid using java script or any Microsoft or flash based technologies. Is it possible with java technology.
You will have a VERY limited option when you do not want to use Javascript (not sure why). You have validation as a field attribute (like maxlength on input field ) which are very limited. Client side validation is always done along with Server side validation. They compliment each other.
You could use a Java applet, and render your user input controls using that instead of with an HTML form.
…but that way lies madness, it would be time consuming to build, take significantly longer to load than HTML + JS, and requires a browser plugin.
You really should use JavaScript for this, it is the only widely supported technology that can interact with HTML forms (without using JS as an intermediary).
Use Java Applets
Here you can use a lot of layouts to position your elements.
If you are saying to use no JS in the terms of coding you can use
GWT coding which is a normal java classes coding but it's a JS
under.
You can pass the parameter of the HTML form to the Servlet and validate the form data
for eg:
String uName= request.getParameter("userName");
String pwd= request.getParameter("password");
PrintWriter out= response.getWriter();
if(uName.equals("username") && pwd.equals("password")){
out.println("Valid User");
}
else
out.println("Invalid User");
You can use formcheck :- mootools validations.. easy and simple to use..
http://mootools.floor.ch/en/demos/formcheck/
For simple validation you can use standart HTML attributes for inputs, such as
<input type='text' maxlength=10> - not allows to type more then X symbols;
<input type="email"> -not allows to type not e-mail pattern in WebKit-based browsers.
etc.
Look w3c docs for more information.
But you should always remeber, that client side validation should only minimize capacity on server and data always should be validated on server side too.
Related
I am looking at writing a tutorial for a Java concept where it would be really nice if I could write the tutorial as a HTML-document with pretty printed Java sources.
I understand I can do this with e.g. http://code.google.com/p/google-code-prettify/ if I copy the various Java sources in my HTML document where I want them to be and put a styling class on the surrounding tag.
However, in order to ensure that the snippets are up to date I would really like to have the HTML page refer to the actual, real Java source files instead of a manually maintained copy.
To my understanding - which may be wrong - this is not supported directly by the Google Prettyprint library, but perhaps some trickery with Javascript pulling in the file and putting it in the DOM tree inside a <pre> tag could do it? I would like the HTML file to be present in the local file system, so doing server side scripting is not an option.
My question is - how can I do this?
(I intend to have the HTML file physically placed at the root of the source tree. This mean that all references from HTML to Java sources will be relative and without '..'. I do not know if that is important or not.)
There is no way to access files directly using JavaScript. JavaScript is restricted in this way for obvious security reasons.
You will need your webserver to serve the Java files. You don't need to do server side scripting but the content of your Java files has to be available at some web address. If they are you can load the content of the Java files with AJAX and inset the content into your webpage.
Using jQuery loading the text could be done as follows
$.get('java/somefile.java', function(data) {
$('#sourceCodeDestination').html(data);
// Prettyprint neeeds to run again in order to see the newly added code
prettyPrint();
}, "text");
This will load the url java/somefile.java get the content of it as plain text and insert it into the DOM element with the id sourceCodeDestination. For more information see the jQuery documentation on get() and ajax().
Here is a demo. As you can see it loads a minified version of the Prettyprint sourcecode from a CDN and pretty prints it.
if your users can accept the requirement of online access while reading your document, you could host your code somewhere like gist (https://gist.github.com/), and embed it in your html dopcument (see example by putting this into your document <script src="https://gist.github.com/sangohan/6494440.js"></script>)
Assuming prettify.js has been loaded previously you can invoke the function prettyPrint which takes arguments callback and rootNode.
<div id="foo">
<pre id="bar"></pre>
</div>
var pre = document.getElementById('bar');
pre.textContent = 'function () {\n return;\n}'; // assign code
pre.className = 'prettyprint'; // assign class
prettyPrint(null, document.getElementById('foo')); // prettify
DEMO
What I want to do:
I have a form with a lot of fields(nick, email, name, surname, etc.) but the user has to fill Nick and Email first in order to be able to fill the other fields(this is because we want to check that the nick and mail aren't in use by another client before he can introduce the rest of his information(name, surname, etc.)).
So, the user introduces Nick and Email and then he must press a button named "Validate", if the values are available(successful validation) then the rest of the fields are enabled and the user can continue filling the form, otherwise the fields stay disabled and an error is showed to the user.
The form will be located in a JSP, it will be submitted to a Servlet, once in the servlet I must validate the information that is in the form(i have a .JAR file included in this servlet, the validation consists in calling a function from that library, the function returns a boolean) and then I must return back to the same JSP the boolean that will represent the result of the validate function.
Now in the JSP I must enable(or not, depending on the value of the boolean) the rest of the TextFields.
I'm not sure if this is right but i was trying to submit with the button and at the same time run a javascript(onclick) that will use this boolean value that the servlet sends back to the JSP after making the validation. The javascript consists on an IF sentence that evaluates the boolean and if it's true then it enables all the fields on the JSP.
Problems so far:
I was able to send the Nick and Email from the JSP to the Servlet and to make the validation of the values, now i have the boolean but i have no idea on how to send it from the Servlet to the same JSP and use it in the onclick event of the same button I used to submit the info. I don't even know if it's possible to do this...
I'd be grateful if someone could give me a hand with this, i'm newbie in Java programming so i would appreciate simple explanations if possible.
Also, if there is a better way of doing what i want please share it, and if there are any doubts ask and i will try to explain it better.
There is no need for JavaScript at all.
In your servlet you can store the validation result into the request context:
req.setAttribute('checkResult', checkResult);
where req is of type HttpServletRequest and checkResult is a Boolean.
Then you can forward to your JSP:
RequestDispatcher dispatcher = req.getRequestDispatcher("/your.jsp");
dispatcher.forward(req, resp);
In your JSP you can set your form elements as read only depending on the attribute checkResult which you have put into the request context:
<textarea name="text" cols="50" rows="10"
<%= request.getAttribute("checkResult") != null && request.getAttribute("checkResult") ? "" : "readonly" %>
>...</textarea>
So if the check is not valid then the <textarea> element will contain the readonly attribute. Otherwise readonly is not present.
As Roy mentioned AJAX is best suited for your problem. You can use DWR! , it makes normal java classes available as AJAX services, just call the method on them and get the result. So easy.
I think AJAX is more suitable for your application, which will not require to submit the whole form and you can send back the validation flag as plain responseText or well-formatted responseXML. Also you can use a lot of good javascript library such as jQuery that helps you send an AJAX request quickly and simply.
Is it possible to write a little Javaa program which parses a xml file from my web hosting site and updates this file? Or is there a better alternative to do so? I have to update the file every 10 min with about 10 lines of code each, so I don't want to write it out every time.
You can write little java program. BTW you can write a bigger one two :).
You can write program using any language you want. Including Java.
The program written in any language can parse XML.
Well, now we arrived to the problem. What do you mean when you say that you wish to parse XML from the web site? Does your web site provides URL that allows to download the XML? In this case you can download it (e.g. using HTTP GET method) and parse.
The next problem is how to update the XML on the site. You have to provide such functionality on site itself (e.g. implement service that is able to receive the XML and store it. For example via HTTP GET.
Once you are done you can write truly little java program that downloads the file using HTTP GET, parses it, creates new one and the sends it back to the site using HTTP POST.
I would investigate running this code on your server. What is the update? Does it use data not on your server? You can do this easily in Java but more detail is needed for a better answer.
OK, your idea is fine if your web hosting lets you do http PUT you can get the file using GET, modify it, e.g. using the DOM, and PUT it back. You might prefer to do more server side scripting and write the update at that end, it lets you use relational databases instead of flat files for example. In this case, writing a server side script to accept a POST as the other answer suggested is a good idea.
I've put a little example for you here: http://jcable.users.sourceforge.net/scores.php
There are three files on this website:
scores - a text file that gets updated.
scores.php - a script that shows the current score
add.php - a script that updates the current score.
scores.php looks like this:
<html>
<body>
The current score is <?php readfile("scores"); ?>
</body>
</html>
add.php looks like this:
<?php
if(isset($_POST["score"])) {
$fh = fopen("scores", 'w') or die("can't open file");
fwrite($fh, $_POST["score"]);
fclose($fh);
}
else
{
?>
<HTML>
<BODY>
<FORM action="add.php" method="POST">
New Score: <INPUT type="text" name="score"/>
</FORM>
</BODY>
</HTML>
<?php
}
?>
if you get add.php it will present you the form. But if your program calls it as a post it won't bother. Hope this gives you some ideas - its the simplest possible web app I can think of that has persistent server side data. You can add complexity - xml or json, etc., but the principles are there.
Is it possible to mask/ hide the lengthy URL and just to display the domain name alone in address bar in the browsers like IE, Firefox, Chrome?
Please suggest.
Regards
Gourav
You shouldn't do that.
It's against the very basics of the technology and usability.
Every page should have its unique address, letting users bookmark it, send link to a friend, navigate your site after all!
You want to use AJAX for this. In your index file, include a javascript file which uses XMLHttpRequest (or you can use something like jQuery.load if you don't want to go so low level) to load your content. With jQuery, you can do something like this:
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(event){
event.preventDefault();
$('#content').load($(this).attr('href'));
return false;
});
});
</script>
However, do not do so lightly - this can break search engine optimization and many other things as some people may have javascript off etc.
And remember, this is a very simplified example - you'd have to take care of things like external URIs (CSRF protection in browsers means you can't XMLHttpRequest another domain). Maybe you could add a CSS class called link_internal and then add that in your jQuery selector etc.
domain = re.match(r'https?://(?:www\.)?([^/]+)', full_url).group(1)
This regex extracts the domain - without www. but any other subdomains if they exist.
It uses the python re module but it should be easy to adept it to another language.
I'm trying to fill-out a form automatically and press a button on that form and wait for a response. How do I go about doing this?
To be more particular, I have a a --HUGE-- collection DNA strains which I need to compare to each-other. Luckily, there's a website that does exactly what I need.
Basically, I type-in 2 different sequences of DNA and click the "Align Sequences" button and get a result (the calculation of the score is not relevant).
Is there a way to make a Java program that will automatically insert the input, "click" the button and read the response from this website?
Thanks!
You can use the apache http client to send a request to a web site.
Look at the source to the page in question, and you'll find the part. This contains all the fields that need to be sent to the server. In particular, you'll see that it needs to be sent as a Post, rather than the more common Get. The link above shows you how to do a post with the http client code.
You'll need to provide a nameValuePair for every field in the form, such as these ones:
<input type="hidden" name="rm" value="lalign_x"/>
<input type="checkbox" name="show_ident" value="1" />
<textarea name="query" rows="6" cols="60">
It will probably take some trial and error for you to get all the fields set up correctly. I'd recommend doing this with small data sets. Once it all seems to be working, then try it with your bigger data.
In Python you can use mechanize library (http://wwwsearch.sourceforge.net/mechanize/). It's quite simple and you doesn't need to know Python very well to use it.
Simple example (filling login form):
br = Browser()
br.open(login_link)
br.select_form(name="login")
br["email"] = "email#server.com"
br["pass"] = "password"
br.submit()
You could probably do this using Selenium.