Nov 13, 2008

Simple AJAX with JQuery(part 1) – ugly example

After getting some experience with JQuery from the previous tutorials, you may be ready for some fun. AJAX development is relatively easy with the JQuery framework.

For this part I’ll show how to use “load” in a basic example. We will have a online book and we will load the chapters without reloading the whole page. This is a stupid example, for many reasons. First – online publishers prefer more reloads. The AJAX functionality is a better decision for online business solutions, not for online reading. But I have no imagination for other relatively simple demo and I am lazy.

So – our example. It is an online book. We will select our chapter with prev(previos) and next buttons. The full ugly working example can be seen here - http://ldeveloper.hit.bg/book.load.html

We will store our chapter names in a JavaScript array:


var bookchapters = new Array( "chapter1.html", "chapter2.html", "chapter3.html" );



The load – loads a html and injects it into the DOM element. It can also filter the incoming document – very convenient if you don’t need the whole page.

So back to our example – the html:



<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<form>
<input type="button" value="Prev" id="prev">
<input type="button" value="Next" id="next">
</form>
<br>
<br>
<strong>Book Title</strong>
<div id="book">
</div>
</body>



And we load a chapter with the following(For this example our chapters are in a folder “book”):


$("#book").load("book/" + bookchapters[index]);



The whole code(html, js and css):


<html>
<head>
<title>JQuery and AJAX tutorial</title>
<style type="text/css">
#book {
background-color: #F0FFF0;
border : thin ridge;
height: 450px;
overflow: scroll
}
input {
background-color : White;
color : #006400;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var bookchapters = new Array( "chapter1.html", "chapter2.html", "chapter3.html" );
$(function () {
var index = 0;
$("#book").load("book/" + bookchapters[index]);
$("#prev").click(function () {
if(index > 0) {
index--;
$("#book").load("book/" + bookchapters[index]);
}
else {
alert("first chapter");
}
});
$("#next").click(function () {
if(index < bookchapters.length - 1) {
index++;
$("#book").load("book/" + bookchapters[index]);
}
else {
alert("last chapter");
}
});


});
</script>
</head>
<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<form>
<input type="button" value="Prev" id="prev">
<input type="button" value="Next" id="next">
</form>
<br>
<br>
<strong>Book Title</strong>
<div id="book">
</div>
</body>
</html>





Filtering the incoming page



This example shows how to use it. The “div:first” after the url in the load parameter string selects only the first div of the incoming document.


<html>
<head>
<title>JQuery and AJAX tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#page").load("in.html div:first");       
});
</script>
</head>
<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<br>
<div id="page">
</div>
</body>
</html>



And the in.html:


<html>
<body>
<div>
First part of the document that will be loaded!
</div>
<br>
<div>
Next part, that won't show into the other.
</div>
</body>
</html>



Nov 6, 2008

Intro to JQuery - part 2 - JQuery examples

If this is your first encounter of JQuery, I recommend the post – Intro to JQuery.

This is a short document on how-to use JQuery API. Necessary knowledge for this post includes JavaScript, HTML and CSS basics.


Let’s change the last example of the previous post a little. We can handle the logic without the counter variable:


<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
var c = parseInt($(this).html());
$(this).html(c + 1);
});
} );
</script>



We can add more complex code with the html(), not only one number. For example:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
$(this).html(String($(this).html() + "<br/><b>We added a row!</b>"));
});
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
Click in the box:
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
This is our test div element.
</div>
</body>
</html>



Be careful to add a correct html for the html() function value or you will end with unexpected results.

JQuery have more methods for DOM manipulations. For full list of these methods I recommend reading the documentation - http://docs.jquery.com/Manipulation

Very power JQuery functionality is the opportunity to easily traverse the DOM tree. One very useful element in this part is the each(). It is used to execute a function within the context of every matched element. This is simple example of its usage:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("div").each(function () {
$(this).css({border : "medium double Red", backgroundColor: "orange"});
}
);
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div>First div element
</div>
<div>Second div element
</div>
</body>
</html>



And now a little more complex example:
The code bellow gets all the <p>(paragraph) childs of the <div> elements and sets them a css class “our class”. There are many other ways to achieve the same thing, this is just example of using each() and children().


<html>
<head>
<title>JQuery basic tutorial</title>
<style type="text/css">
.ourclass {
border : medium double #FFA500;
width: 90px;
height: 90px;
}

</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("div ").each(function () {
$(this).children("p").each(function () {
$(this).addClass("ourclass");
});
}
);
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div style="border : 1px solid Black;">First div element<div></div>
</div><br/>
<div style="border : 1px solid Black;">Second div element with two paragraphs
<p>First <b>p</b></p>
<p>Second p</p>
</div>
<p style="border : 1px dotted Black;">This is a paragraph but it is not a div child</p>
</body>
</html>

Oct 31, 2008

Intro to JQuery

JQuery is a lightweight JavaScript framework that got a lot of attention lately so I decided to write few rows about it.

This post-tutorial is recommended for people with basic javascript, html and css knowledge.

To run and test the examples in this tutorial, you need to save them as html pages. You can use any text editor like notepad or anything convenient.

What do you need to start using JQuery? Just download and save it in the same directory (I’ll call it jquery.js) and include the following code anywhere above your javascript code:


<script type="text/javascript" src="jquery.js"></script>



The best place for our javascript code is in the head section of the html document but you are not restricted to it. Anyway I’ll use the head section for most of my examples.

Ok, let’s use some basic functionality to test if we’ve done it right.

example1.html:

<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert('Works!!!');
} );
</script>
</head>
<body>
JQuery basic tutorial
</body>
</html>




So, what happens here? Nothing special, we just show an alert with text ‘Works!!!’.

$ function is a factory method (shortcut) for the JQuery object.


$(document).ready(function() {
// code
});



With $(document).ready we register our code to the ready event of the document. The above code can be shortened:


$(function () {
// code
} );



Selectors and events



In JQuery an element can be selected in different ways – by id, by element type, by css class and so on.
This is a simple code showing how to use events and selectors:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
alert("Click");
});
} );

</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
Div
</div>
</body>
</html>



The click(fn) binds a function to the click event of our matched element.
Let’s make our example a little more complex. We will count the clicks.


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function () {
$("#ourID").click(function () {
counter++;
$(this).html(counter);
});
} );

</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
Click in the box:
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
0
</div>
</body>
</html>


Oct 28, 2008

Fast and easy Hibernate example-tutorial (Part 2)

Fast and easy Hibernate example-tutorial (Part 1)

In the first part of this tutorial we met the basic functionality of Hibernate. We store and retrieve some simple objects to and from the database.

This time I’ll make the example a little harder. Now our table books will have author_id instead of author(simple string for the name) and we will have table authors with two columns: id, name.

Let’s assume that our book can have single author but our authors may have many books. It is rather dull example, far away from the real world where one book may be written by more than ten people but it would be easy for my example this way.

Also I'll make the id keys serial - I don't want to bother to set ids.

Here is the Author class:

public class Author {
private Integer id;
private String name;

public Integer getId() {
return id;
}

public String getName() {
return name;
}

public void setId(Integer id) {
this.id = id;
}

public void setName(String name) {
this.name = name;
}
}


And the Author.hbm.xml mapping:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Author" table="authors">

<id name="id" type="java.lang.Integer" column="id">
<generator class="sequence">
<param name="sequence">authors_id_seq</param>
</generator>
</id>


<property name="name" column="name" type="java.lang.String" />

</class>
</hibernate-mapping>


Book.java:

public class Book {
private Integer id;
private String title;
private Author author;

public Integer getId() {
return id;
}

public String getTitle() {
return title;
}

public Author getAuthor() {
return author;
}

public void setId(Integer id) {
this.id = id;
}

public void setTitle(String title) {
this.title = title;
}

public void setAuthor(Author author) {
this.author = author;
}
}


Book.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Book" table="books">
<id name="id" type="java.lang.Integer" column="id">

<generator class="sequence">

<param name="sequence">books_id_seq</param>

</generator>
</id>
<property name="title" column="title" type="java.lang.String" />

<many-to-one name="author" class="Author" lazy="false">
<column name="author_id"></column>
</many-to-one>

</class>
</hibernate-mapping>


And finally the hibernate.cfg.xml:

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost/example</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">secret</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>

<mapping resource="Author.hbm.xml" />
<mapping resource="Book.hbm.xml" />

</session-factory>
</hibernate-configuration>


We have our classes and now we are ready to test them. This is a simple test example for storing objects:

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class BookExample {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Author author = new Author();
author.setName("Crazy book author First");
Author author2 = new Author();
author2.setName("Writer");
Book book = new Book();
book.setTitle("Crazy book");
book.setAuthor(author);
Book book2 = new Book();
book2.setTitle("Crazy old book");
book2.setAuthor(author);
Book book3 = new Book();
book3.setTitle("Book Title");
book3.setAuthor(author2);

Transaction tx = session.beginTransaction();
session.save(author);
session.save(author2);
session.save(book);
session.save(book2);
session.save(book3);

tx.commit();

session.close();
sessionFactory.close();
}
}

The result must be something like this:
Hibernate: select nextval ('authors_id_seq')
Hibernate: select nextval ('authors_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: insert into authors (name, id) values (?, ?)
Hibernate: insert into authors (name, id) values (?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)


And now to retrieve the objects from the database:

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class BookExample2 {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();


Criteria criteria = session.createCriteria(Book.class);
List books = criteria.list();

Iterator it = books.iterator();
while (it.hasNext()) {
Book book = (Book) it.next();
System.out.println("Book: " + book.getTitle() + " with author: " + book.getAuthor().getName());
}

session.close();
sessionFactory.close();
}
}



The result:
Hibernate: select this_.id as id1_0_, this_.title as title1_0_, this_.author_id as author3_1_0_ from books this_
Hibernate: select author0_.id as id0_0_, author0_.name as name0_0_ from authors author0_ where author0_.id=?
Hibernate: select author0_.id as id0_0_, author0_.name as name0_0_ from authors author0_ where author0_.id=?
Book: Crazy book with author: Crazy book author First
Book: Book Title with author: Writer
Book: Crazy old book with author: Crazy book author First


In this example I use few rather interesting options. The first is the generator child element of id with option sequence. It uses a sequence from our database (PostgreSQL, remember? ).
The second is many-to-one relation between the objects with lazy set to false. This option tells Hibernate to retrieve the author object together with our book object. However, most of the time you will use lazy set to true, this is also the default value.

Oct 17, 2008

Fast and easy Hibernate example-tutorial (Part 1)

This tutorial tries to provide fast and easy instructions on getting started with Hibernate. You can download Hibernate from http://www.hibernate.org.
I won't explain how to make Java project with eclipse or netbeans, it is beyond the scope of this text.

Hibernate is an open-source ORM(object relational mapping) library. It is one of the basic tools for fast and reliable java application development. Hibernate is published under LGPL license that allows you to use it in both open-source and commercial projects.

The fastest way to learn something new is with examples. So I'll write some basic example for its usage. For this exercise I'll use PostgreSQL as my database server. It doesn't matter so much, changing to another type is easy from the Hibernate configuration file.

Lets have database called 'example' with table 'books'. Books will have 3 columns - id, title and author.
Here is our persistent class - I'll call it Book


public class Book {
private Integer id;

private String title;

private String author;

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}



And this would be our mapping xml file Book.hbm.xml:


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


<hibernate-mapping>

<class name="Book" table="books">

<id name="id" column="id">

<generator class="native"/>

</id>

<property name="title" column="title" type="java.lang.String" />

<property name="author" column="author" type="java.lang.String" />

</class>

</hibernate-mapping>



This is the Hibernate configuration file :

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


<hibernate-configuration>

<session-factory>

<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>

<property name="hibernate.connection.url">jdbc:postgresql://localhost/example</property>

<property name="hibernate.connection.username">username</property>

<property name="hibernate.connection.password">secret</property>

<property name="connection.pool_size">1</property>

<property name="show_sql">true</property>

<mapping resource="Book.hbm.xml" />

</session-factory>

</hibernate-configuration>




Now we are ready to test what we've done. Lets make simple text class BookExercise.

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class BookExercise {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Book firstBook = new Book();
firstBook.setId(1);
firstBook.setTitle("Our first book title");
firstBook.setAuthor("Our Author");

Book secondBook = new Book();
secondBook.setId(2);
secondBook.setTitle("Second book title");
secondBook.setAuthor("Our Author");

Transaction tx = session.beginTransaction();

session.saveOrUpdate(firstBook);
session.saveOrUpdate(secondBook);

tx.commit();

session.close();
sessionFactory.close();
}
}


Now you must have two records in your books table. To view them you can try to change the exercise class this way:


import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class BookExercise {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Criteria criteria = session.createCriteria(Book.class);
List books = criteria.list();

Iterator it = books.iterator();
while(it.hasNext()) {
Book book = (Book) it.next();
System.out.println("Book: " + book.getTitle() + " with author: " + book.getAuthor());
}

session.close();
sessionFactory.close();
}
}

Oct 16, 2008

Laziness

I haven’t written anything to my blog for a while. I am not exactly devoted blogger, so this is easy to explain. And recently I am too lazy to do anything. Or maybe I am just tired.

May 4, 2008

Offtopic: A picture of the sky

Dynamic tables with JMesa


JMesa is a very useful open source project.It is a dynamic HTML table that allows you to edit, filter, sort, paginate and export your data. By my opinion it is a really cool and useful tool for development a java web applications. Here is a simple and fast tutorial and example.
What do you need to run this tutorial?
1. JDK, JMesa requires 1.5 or above, I recommend 1.6
2. IDE - I'll use my favorite eclipse
3. JMesa latest
4. JQuery, JMesa requirement, prefer the latest version
5. I'll use Struts

OK, now what to do. Extract the jmesa archive and create new web project. Put jmesa.jar on your WEB-INF/lib directory. Put the JavaScript, CSS and image files in the corresponding folders. For me that would be /scripts, /styles and /images. For the data bean I'll use simple class Framework

public class Framework {
String name;
String url;
String license;
Boolean like;

public Framework(String name, String url, String license, Boolean like) {
this.name = name;
this.url = url;
this.license = license;
this.like = like;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public String getLicense() {
return license;
}
public Boolean getLike() {
return like;
}
public void setLicense(String license) {
this.license = license;
}
public void setLike(Boolean like) {
this.like = like;
}
}

Our framework action or servlet must set the data collection, in our case it will do something like this:

Framework jquery = new Framework("jQuery", "http://jquery.com", "MIT & GPL", true);
Framework mootools = new Framework("Mootools", "http://mootools.net/", "MIT License", true);
Framework gwt = new Framework("Google Web Toolkit", "http://code.google.com/webtoolkit/", "Apache License", false);
Framework dojo = new Framework("Dojo", "http://dojotoolkit.org/", "BSD & AFL", false);
Framework prototype = new Framework("Prototype", "http://www.prototypejs.org/", "MIT License", false);

ArrayList frameworks = new ArrayList();
frameworks.add(jquery);
frameworks.add(mootools);
frameworks.add(gwt);
frameworks.add(dojo);
frameworks.add(prototype);

request.setAttribute("frameworks", frameworks);


And our framework.jsp file:

And thats it. Our jmesa table is ready to be shown on public. Simple, easy and fun.

May 2, 2008

One annoying problem with jquery, ui.dialog plugin and Firefox

I have run into a small problem with jquery, ui.dialog and Firefox 2. If you just use the example code and the default plugin theme (flora) you will see the problem with Firefox - the middle of the dialog is empty. With IE 6 everything is working just fine. I spent some time pushing my head, trying to solve the problem. And then I came across the solution – the example that comes with the ui.dialog. The only difference with my code was the body tag that has class property. Just a css issue, not a dialog problem.
Quite nasty thing, not a bug, but it is not pleasant to make everything from the documentation and don’t get it working.

Sweating on a Web 2 Application

Have you asked yourself what is a good Web 2 application? What should it contain and what can be permitted to the users. I am working on a private configuration application, and I want to make it really useful for the users. Not just fancy picture sliding with JavaScript, in the matter of facts I don't have any pictures, but I have a lot of fancy JavaScript. My own opinion is that Java is the maturest language/technology for this kind of task. Java with Hibernate, Struts or maybe Spring. And of course JavaScript(give me a brake) for client scripting. JavaScript with JQuery, Mootools, Dojo or GWT. My personal liking goes for Mootools, but JQuery is a little more professional.

Strange exception

There is a new cry topic in one of the development forums I read, that make me think about this problem of the tomcat application server. The problem is about ojdbc14.zip(or any zip) in a web application. The exception was

org.apache.jasper.JasperException: JDBC Driver class not found: oracle.jdbc.driver.OracleDriver

despite the fact that ojdbc14.zip was in the project lib directory. I've just remembered how much time I spent on a similar problem, so I send him my answer. The reason for this bug is that tomcat have problems with zip archives. Renaming to jar will fix it. I haven't tested if the latest tomcat have zip problem though.

Popular Posts