Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, April 6, 2013

Step By Step Java EE 5 tutorials

Java EE 5 tutorials

These are Java Enterprise Edition 5 tutorials. (J2EE tutorials). These Java EE tutorials are suitable for novice Java EE programmers. The purpose of this set of tutorials is to get you started with the Java Enterprise Edition platform.

Table of contents

Java EE

Java Platform, Enterprise Edition is a set of libraries, tools, specifications, best practices for developing, deploying and managing server side enterprise level applications.

Object relational mapping with iBATIS

Object relational mapping with iBATIS

In this part of the JEE programming tutorial, we will talk about the object relational mapping with iBATIS.
Object Relational Mapping, ORM is a programming technique for converting data between relational databases and object oriented programming languages. Data is handled differently in both systems. The problem that arises from these differences is called the object-relational impedance mismatch. The ORM tools were created to help application programmers to cope with these issues. Hibernate or Toplink are two of such tools. In large JEE applications developers mostly do not work directly with SQL, but they use ORM tools.
iBATIS is another ORM mapping tool. I chose iBATIS for these tutorials, because it is simple and easy to use. iBATIS can be used with Java, .NET or Ruby. It is developed by the Apache Software Foundation. Simplicity is the biggest advantage over other ORM tools.

Commmand line example

The first example will be command line. The example will get all data from a database table using iBATIS. We will use books database and books table again.
mysql> describe books;
+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| author | varchar(30) | YES | | NULL | |
| title | varchar(40) | YES | | NULL | |
| year | int(11) | YES | | NULL | |
| remark | varchar(100) | YES | | NULL | |
+--------+--------------+------+-----+---------+----------------+
5 rows in set (0.23 sec)
This is the books table.
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

<transactionManager type="JDBC" commitRequired="false">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL"
value="jdbc:mysql://localhost:3306/books"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value=""/>
</dataSource>
</transactionManager>

<sqlMap resource="ibatis/Books.xml"/>

</sqlMapConfig>
This is the configuration file for the iBATIS. We can give it an arbitrary name. Inside the configuration file, we define the datasource an various sql map files. We use the MySQL database.
Book.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="Book">

<typeAlias alias="Book" type="ibatis.Book"/>

<select id="selectAllBooks" resultClass="ibatis.Book">
select * from books
</select>

</sqlMap>
This is the sql map file. This file will map a java class to a database table. In our case the Java class is Book.java and the table is books in the books database.
Book.java
package ibatis;

public class Book {

private int id;
private String author;
private String title;
private String year;
private String remark;

public String getAuthor() {
return author;
}

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

public int getBookId() {
return id;
}

public void setBookId(int id) {
this.id = id;
}

public String getRemark() {
return remark;
}

public void setRemark(String remark) {
this.remark = remark;
}

public String getTitle() {
return title;
}

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

public String getYear() {
return year;
}

public void setYear(String year) {
this.year = year;
}
}
This is the Books bean java class with all its properties and setter and getter methods.
Main.java
package ibatis;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

public class Main {

public static void main(String[] args)
throws IOException, SQLException {

Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

List<Book> books = (List<Book>)
sqlMap.queryForList("selectAllBooks");

for (Book a : books) {
System.out.println(a.getAuthor() + " : " + a.getTitle());
}
}
}
This code loads the configuration file, receives the data using the queryForList() method call and prints authors and titles of books to the console.
$ java -jar ibatis.jar 
Leo Tolstoy : War and Peace
Leo Tolstoy : Anna Karenina
ralf reuth : rommel
Balzac : Goriot
David Schwartz : The magic of thinking big
Johannes Leeb : Der Nuernberger prozess
Siegfried Knappe : German Soldier
Kertész Imre : Sorstalanság
Napoleon Hill : Think and grow rich
Brett Spell : Professional Java Programming
This is the result that we get.

Web example

The next example will enhance the previous one. In addition to selecting all books, we will also have the ability to insert and delete books.
style.css
* { font-size: 12px; font-family: Verdana }

input { border: 1px solid #ccc }

a#currentTab {
border-bottom:1px solid #fff;
}

a { color: black; text-decoration:none;
padding:5px; border: 1px solid #aaa;
}

a:hover { background: #ccc; cursor: pointer; }

td { border: 1px solid #ccc; padding: 3px }
th { border: 1px solid #ccc; padding: 3px;
background: #009999; color: white }

.navigator { border-bottom:1px solid #aaa; width:300px; padding:5px }

.hovered { background-color: #c4dcff }
.selected { background-color: #a5ffb8 }
.highlighted { background-color: #e33146 }
.unselected { background-color: #ffffff }
Simple css file used in our example.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5">
<servlet>
<servlet-name>GetAllBooks</servlet-name>
<servlet-class>com.zetcode.GetAllBooks</servlet-class>
</servlet>
<servlet>
<servlet-name>InsertBook</servlet-name>
<servlet-class>com.zetcode.InsertBook</servlet-class>
</servlet>
<servlet>
<servlet-name>DeleteBooks</servlet-name>
<servlet-class>com.zetcode.DeleteBooks</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAllBooks</servlet-name>
<url-pattern>/GetAllBooks</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InsertBook</servlet-name>
<url-pattern>/InsertBook</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeleteBooks</servlet-name>
<url-pattern>/DeleteBooks</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
This is the web.xml file. Here we configure our three servlets.
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

<transactionManager type="JDBC" commitRequired="false">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL"
value="jdbc:mysql://localhost:3306/books"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value=""/>
</dataSource>
</transactionManager>

<sqlMap resource="ibatis/Books.xml"/>

</sqlMapConfig>
The sqlMapConfig.xml file is unchanged.
Book.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="Book">

<typeAlias alias="Book" type="com.zetcode.Book"/>

<select id="selectAllBooks" resultClass="com.zetcode.Book">
select * from books
</select>

<insert id="insertBook" parameterClass="com.zetcode.Book">
insert into books (
author,
title,
year,
remark )
values (
#author#, #title#, #year#, #remark#
)
</insert>

<delete id="deleteBooks" parameterClass="String">
delete from books where id = #id#
</delete>

</sqlMap>
The Book.xml file has three statements. It enables to select, insert and delete data. The values between the # characters are parameters to the sql map client.
Book.java
package com.zetcode;

import java.io.Serializable;

public class Book implements Serializable {

private String id;
private String author;
private String title;
private String year;
private String remark;

public String getId() {
return id;
}

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

public String getAuthor() {
return author;
}

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

public String getTitle() {
return title;
}

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

public String getYear() {
return year;
}

public void setYear(String year) {
this.year = year;
}

public String getRemark() {
return remark;
}

public void setRemark(String remark) {
this.remark = remark;
}
}
The Book.java file is the same as in the first example.
DriverManagerExample.java
function getBooks() {
form = window.document.getElementById("form");
form.action="GetAllBooks";
form.submit();
}

function insertBook() {
form = window.document.getElementById("form");
form.action="InsertBook";
form.submit();
}


function OnDelete() {

var tbl = document.getElementById("books");
var tds = tbl.getElementsByTagName("td");

var id;

for(var i=0; i < tds.length; ++i )
{
if (!(i%5))
if (tds[i].parentNode.className == "selected") {
id = tds[i].innerHTML;
}
}

var form = document.getElementById("form");
var input = document.getElementById("bookId");
input.value=id;

form.action="DeleteBooks";
form.submit();
}

function select(obj) {
if (obj.className != "selected")
obj.className = "hovered";

}

function unselect(obj) {
if (obj.className == "hovered")
obj.className = "unselected";
}

function clicked(obj) {

var tbl = document.getElementById("books");
var trs = tbl.getElementsByTagName("tr");

for(var l=0; l < trs.length; ++l )
{
if (trs[l].className == "selected")
trs[l].className = "unselected";
}

obj.className = "selected";
}
This is the javascript that we use in our example.
function getBooks() {
form = window.document.getElementById("form");
form.action="GetAllBooks";
form.submit();
}
The getBooks() function will call the GetAllBooks servlet.
The insertBook() function will call the InsertBook servlet. The OnDelete() function will figure out, what row is currently selected and call the DeleteBooks servlet afterwards.
If we hover a mouse pointer over a row in a table, we change it's colour to light blue. We do this using select() and unselect() JavaScript functions.
function clicked(obj) {

var tbl = document.getElementById("books");
var trs = tbl.getElementsByTagName("tr");

for(var l=0; l < trs.length; ++l )
{
if (trs[l].className == "selected")
trs[l].className = "unselected";
}

obj.className = "selected";
}
If we click on a specific row, we change it's color to dark blue. The for loop makes sure, that only one row is selected at a time. All previously selected rows get unselected.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Books database</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>

<script src="scripts.js"></script>

<body>
<br>

<div class="navigator">
<a id="currenttab" href="index.jsp">Add</a>
<a onclick="getBooks();">Show</a>
</div>

<br> <br> <br>


<form method="post" name="form" id="form">
<table>
<tr>
<td>Author</td><td><input type="text" name="author"></td>
</tr>
<tr>
<td>Title</td><td><input type="text" name="title"></td>
</tr>
<tr>
<td>Year</td><td> <input type="text" name="year"></td>
</tr>
<tr>
<td>Remark</td><td> <input type="text" name="remark"></td>
</tr>

</table>

<input type="button" value="Insert" onclick="insertBook()">

<br>
</form>
</body>
</html>
This is the introdutory jsp file. It has a html form to add a new book to our database.
show.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.*" %>
<%@page import="com.zetcode.Book" %>


<html>
<head>
<title>View</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="scripts.js"></script>
</head>

<body>

<br>

<div class="navigator">
<a href="index.jsp">Add</a>
<a id="currenttab" href="show.jsp">Show</a>
</div>

<br> <br> <br>
<form method="get" id="form">
<input type="hidden" name="bookId" id="bookId">
<table id="books">
<tr>
<th>Id</th>
<th>Author</th>
<th>Title</th>
<th>Year</th>
<th>Remark</th>
</tr>
<%

List<com.zetcode.Book> list = (List<com.zetcode.Book>)
session.getAttribute("books");

for (Book a : list) {
out.print("<tr class='unselected' id='row' onclick='clicked(this)' " +
"onmouseout='unselect(this)' onmouseover='select(this)'>");
out.print("<td id='id'>");
out.print(a.getId());
out.print("</td>");
out.print("<td>");
out.print(a.getAuthor());
out.print("</td>");
out.print("<td>");
out.print(a.getTitle());
out.print("</td>");
out.print("<td>");
out.print(a.getYear());
out.print("</td>");
out.print("<td>");
out.print(a.getRemark());
out.print("</td>");
out.print("</tr>");
}
%>

</table>
<br>
<input type="button" value="Delete" onclick="OnDelete()">

</form>

<br>

</body>
</html>
The show.jsp file shows the data from the books table. It also enables to delete a currently selected book from the database.
DeleteBooks.java
package com.zetcode;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.net.*;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;


public class DeleteBooks extends HttpServlet {


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");


try {
Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

String id = request.getParameter("bookId");
sqlMap.delete("deleteBooks", id);


} catch (SQLException ex) {
Logger.getLogger(GetAllBooks.class.getName()
).log(Level.SEVERE, null, ex);

} finally {

RequestDispatcher dispatcher =
request.getRequestDispatcher("/GetAllBooks");
dispatcher.forward(request, response);
}
}


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
The DeleteBooks servlet deletes a book from the database.
String id = request.getParameter("bookId");
sqlMap.delete("deleteBooks", id);
We get the id of the book from the request. The id is given to the sql map client delete statement.
RequestDispatcher dispatcher = request.getRequestDispatcher("/GetAllBooks");
dispatcher.forward(request, response);
After we delete the book, we call the GetAllBooks servlet.
GetAllBooks.java
package com.zetcode;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.sql.*;
import java.io.*;
import java.net.*;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetAllBooks extends HttpServlet {


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

try {

Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

List<Book> books = (List<Book>) sqlMap.queryForList("selectAllBooks");
request.getSession().setAttribute("books", books);

} catch (SQLException ex) {
Logger.getLogger(GetAllBooks.class.getName()).log(
Level.SEVERE, null, ex);

} finally {
RequestDispatcher dispatcher =
request.getRequestDispatcher("/show.jsp");
dispatcher.forward(request, response);
}
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
The GetAllBooks servlet selects all data from the books table and put it into the session object. Later in the show.jsp file we retrieve this data.
List<Book> books = (List<Book>) sqlMap.queryForList("selectAllBooks");
request.getSession().setAttribute("books", books);
Here we select the data and put it into the session.
InsertBook.java
package com.zetcode;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.sql.*;
import java.io.*;
import java.net.*;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;

public class InsertBook extends HttpServlet {



protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

String author = request.getParameter("author");
String title = request.getParameter("title");
String year = request.getParameter("year");
String remark = request.getParameter("remark");

try {

Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);


Book book = new Book();

book.setAuthor(author);
book.setTitle(title);
book.setYear(year);
book.setRemark(remark);

sqlMap.insert("insertBook", book);


} catch (SQLException ex) {
Logger.getLogger(GetAllBooks.class.getName()).log(
Level.SEVERE, null, ex);

} finally {

RequestDispatcher dispatcher =
request.getRequestDispatcher("/GetAllBooks");
dispatcher.forward(request, response);
}
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

The InsertBook servlet inserts a new book into the database.
String author = request.getParameter("author");
String title = request.getParameter("title");
String year = request.getParameter("year");
String remark = request.getParameter("remark");
We get the necessary data from the request.
Book book = new Book();

book.setAuthor(author);
book.setTitle(title);
book.setYear(year);
book.setRemark(remark);
Create and fill the Book class.
sqlMap.insert("insertBook", book);
Insert the data into the database using the sql map client.
iBATIS
Figure: iBATIS
In this chapter we have shortly talked about ORM with iBATIS.

Custom JSP tags

Custom JSP tags

In this part of the JEE tutorials we will talk about custom tags.
A custom tag is a user-defined JSP language element. It is an extension to the JSP language. Custom tags are reusable software components. Custom tags are used to handle common functionality. They also separate programming code from the content. They make the JSP pages look uniform. This way the JSP pages are more maintainable.
Custom tags can be created using:
  • Tag handlers
  • Tag files
Tag handlers are Java classes, that implement the custom tag. A tag file is a source file containing JSP code that is translated into a simple tag handler by the web container. Same as with JSPs and serlvets.
Tag handlers can be made available to a web application in two basic ways. The classes implementing the tag handlers can be stored in an unpacked form in the WEB-INF/classes/ subdirectory of the web application. Alternatively, if the library is distributed as a JAR, it is stored in the WEB-INF/lib/ directory of the web application.

Empty custom tag

When we started with JavaServer pages, we introduced a simple example, that showed the current date. In the following example, we put the java code into the tag handler and thus, separate the code from the content.
Each custom tag implemented with a tag handler must be declared in a special xml file called tag library descriptor(TLD). The TLD file maps custom tags to their corresponding simple tag handler implementation classes.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="d" uri="http://zetcode.com/tlds/date" %>

<html>
<head>
<title>Custom tags</title>
<style>
* { font-size: 12px; font-family: Verdana }
</style>
</head>
<body>
<h2>Date</h2>
<b>Today's Date: </b> <d:DateTag />
</body>
</html>
This is the jsp file, that will output the current date.
<%@taglib prefix="d" uri="http://zetcode.com/tlds/date" %>
The taglib directive will enable us to use the custom tag in this jsp page. The uri parameter is a unique identifier for the tag library. In the previous versions of the JSP technology, developers had to edit the web.xml file. Today this is not necessary. The container will automatically map the uri with the coresponding TLD. The uri must be unique within the application. The taglib directive also specifies the prefix, used in our custom tag.
<b>Today's Date: </b> <d:DateTag />
Here we use our custom tag. This tag displays current date and time. The DateTag is the name of the custom tag, specified in the date.tld file. We have a tag with empty body, so there is ending tag.
date.tld
<?xml version="1.0" encoding="UTF-8"?>

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>d</short-name>
<uri>http://zetcode.com/tlds/date</uri>

<tag>
<name>DateTag</name>
<tag-class>com.zetcode.DateTagHandler</tag-class>
<body-content>empty</body-content>
</tag>

</taglib>
This is the tag library descritor, for our example. In the tag element, we provide the name of the tag, the Java class, that implements the tag. We also specify, that our tag has no body. We placed the date.tld file into the WEB-INF/tlds directory.
DateTagHandler.java
package com.zetcode;

import java.util.Date;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;


public class DateTagHandler extends SimpleTagSupport {

public void doTag() throws JspException {

JspWriter out=getJspContext().getOut();

try {

out.println(new Date());

} catch (java.io.IOException ex) {
throw new JspException(ex.getMessage());
}
}
}
This is the implementation of the tag halder for our custom tag.
out.println(new Date());
We print the current date.
An custom tag
Figure: A custom tag

Tag file

The other way of creating custom tags is using the tag files. The idea is identical to how jsp files are transformed to servlets. Similarly, the tag files are first transformed into the tag handlers. And then compiled.
In the next example, we will use custom tags to indicate mandatory and non mandatory fields in a html form. Our custom tag will also have an attribute.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<html>
<head>
<title>Tag File</title>
<style>
* { font-size: 12px; font-family: Verdana }
input, textarea { border: 1px solid #ccc }
</style>
</head>
<body>

<div style="width:400px">
<center>
<form>
<table>
<tr>
<td><t:field text="Name" mandatory="yes" /></td>
<td><input type="text" name="from"></td>
</tr>
<tr>
<tr>
<td><t:field text="Email" mandatory="no" /></td>
<td><input type="text" name="to"></td>
</tr>
<tr>
<td><t:field text="Message" mandatory="yes" /></td>
<td><textarea cols="25" rows="8" name="message"></textarea></td>
</tr>
</table>
<br>
<input type="submit" value="submit">
</form>
</center>
</div>
</body>
</html>
This is the jsp file, where we use our custom tag.
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
The prefix attribute defines the prefix that distinguishes tags defined by a given tag library from other tag libraries. The tagdir attribute identifies the location of the tag library. The value of the attribute must start with /WEB-INF/tags/
<td><t:field text="Name" mandatory="yes" /></td>
The custom tag creates a text field in the html form. It is a mandatory field, so we will see an asterix.
field.tag
<%@tag description="normal or mandatory fields" pageEncoding="UTF-8"%>


<%@attribute name="mandatory" required="true"%>
<%@attribute name="text" required="true"%>


<%
if ("yes".equals(mandatory)) {
out.println(text + "*");
} else {
out.println(text);
}
%>
The tag fiel field.tag is created using the jsp syntax. We placed the field.tag file into the WEB-INF/tags directory. If a tag is implemented as a tag file and ispackaged in WEB-INF/tags/ or a subdirectory, a TLD will be generated automatically by the web container.
TagFile project
Figure: TagFile project
<%@attribute name="mandatory" required="true"%>
This directive creates an attribute for our custom tag. The attribute name is mandatory and it is not optional. We must provide it, when we use the custom tag.
if ("yes".equals(mandatory)) {
out.println(text + "*");
} else {
out.println(text);
}
Mandatory fields will have an asterix.
A tag file
Figure: TagFile

Random numbers

If we need a custom tag, we might look, if it wasn't already created by someone. Say we want to generate random numbers using custom tags. There is already a library to achieve this. The random tag library from the Jakarta Project. From their web http://jakarta.apache.org/taglibs/ , we download the latest random tag library. The name of the jar is taglibs-random.jar. We put the jar file into the WEB-INF/lib directory.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib uri="http://jakarta.apache.org/taglibs/random-1.0" prefix="rand" %>

<html>
<head>
<title>Random</title>
<style>
* { font-size: 12px; font-family: Verdana }
</style>
</head>
<body>
<h2>Random numbers</h2>
</body>

<% for (int i = 0; i < 100; i++) {%>

<% if (i % 10 == 0) {
out.println("<br>");
} %>

<rand:number id="random1" range="1-100"/>
<jsp:getProperty name="random1" property="random"/>  

<% } %>

</html>
In this example, we display 100 random numbers.
<%@ taglib uri="http://jakarta.apache.org/taglibs/random-1.0" prefix="rand" %>
We declare, that we use the random tag library in our jsp page. The uri is a unique identifier for the tag library. The container tries to match it against any <taglib-uri> elements in the application’s web.xml file or the <uri> element of TLDs in JAR files in /WEB-INF/lib/ or TLDs under WEB-INF.
In our case, the Resin AS will look inside the taglibs-random.jar at the META-INF/tablib.tld file for the uri.
<taglib>
<taglib-uri>
http://jakarta.apache.org/taglibs/random-1.0
<taglib-uri>
<taglib-location>
/WEB-INF/tlds/taglibs-random.tld
<taglib-location>
</taglib>
For older containers, we must edit the web.xml file. We must provide the uri and the taglib location. For newer containers, we need not to copy the taglibs-random.tld. The TLD is already available in the jar file and the contaner will look it up automatically.
<rand:number id="random1" range="1-100"/>
<jsp:getProperty name="random1" property="random"/>  
Here we create and display a random number in range from 1 .. 100.
In this chapter we have described custom JSP tags.

Tutorials on Java Beans

Java Beans

In this part of the JEE tutorials, we will talk about client side Java Beans components. This is a technology directly supported by the JavaServer pages.
Java Beans are reusable software components. The idea behind a software component is to create a specialized piece of self-contained code, that could be easily plugged into various applications as needed. For example in GUI programming, we might have a chart, a clock or a spreadsheet component that could be used in an application without exposing the programmer to complicated details that are behind the code.
Technically Java Beans are Java classes conforming to particular conventions. A bean can be a particular specialized Java Swing component (e.g. a chart ) that can be plugged into the application, a server side component called Enterprise Java Bean, EJB or a client side component. In this chapter, we will talk about client side Java Beans.
  • The class must have a no-argument public constructor
  • The properties of the Bean must be accessible using accessor methods
  • The class should be serializable
JavaServer Pages technology directly supports using JavaBeans components with standard JSP language elements.

A Bean

In the Bean example we have a form that sends data to a jsp page. The JSP page will output those data. This time we do not use scriptlets or expressions, but we use Java Beans technology.
style.css
* { font-size: 12px; font-family: Verdana }

input { border: 1px solid #ccc }
This is a css file for the code example.
index.css
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<title>Bean</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>

<form action="show.jsp" method="post">

<table>

<tr>
<td>Author</td>
<td><input type="text" name="author"></td>
</tr>

<tr>
<td>Title</td>
<td><input type="text" name="title"></td>
</tr>

<tr>
<td>Available</td>
<td><input type="checkbox" name="available" value="true"></td>
</tr>

</table>

<br>
<input type="submit" value="submit">
</form>

</body>
</html>
Here we define a simple form. We have three input boxes. The author, title and the availability of the book. The parameters are sent to the show.jsp page.
MyBean.java
package com.zetcode;

import java.io.Serializable;


public class MyBean implements Serializable {

private String author = "";
private String title = "";
private String available = "";


public String getAuthor() {
return author;
}

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

public String getTitle() {
return title;
}

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

public String getAvailable() {
return available;
}

public void setAvailable(String available) {
this.available = available;
}
}
This is our bean. It is a simple java class. Has no argument constructor. It implements the Serializable interface. We have three properties of a Bean. Each of the property names begins with small letter. Each of the accessor methods is public. The properties are private. The accessor methods consists of two parts. The first part begins with get, set or is and the second part is the name of the property with first letter capitalized.
show.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<title>Show</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>

<jsp:useBean id="MyBean" class="com.zetcode.MyBean" scope="page">
<jsp:setProperty name="MyBean" property="author" param="author" />
<jsp:setProperty name="MyBean" property="title" param="title" />
<jsp:setProperty name="MyBean" property="available" param="available" />
</jsp:useBean>

<jsp:getProperty name="MyBean" property="author"/><br>
<jsp:getProperty name="MyBean" property="title"/><br>
<jsp:getProperty name="MyBean" property="available"/>

</body>
</html>
The show.jsp page sets the parameters into the bean and prints them.
<jsp:useBean id="MyBean" class="com.zetcode.MyBean" scope="page">
...
</jsp:useBean>
We use this element to declare that our JSP page will use a bean. The id parameter identifies the bean. The class parameter is a fully clasified classname. The scope parameters sets the bean validity for this page only.
<jsp:getProperty name="MyBean" property="author"/><br>
This element retrieves the author property from the bean.

Another Bean

Next we modify our previous example a bit.
show.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<title>Show</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>

<jsp:useBean id="MyBean" class="com.zetcode.MyBean" scope="page">
<jsp:setProperty name="MyBean" property="*"/>
</jsp:useBean>

<jsp:getProperty name="MyBean" property="author"/><br>
<jsp:getProperty name="MyBean" property="title"/><br>
<jsp:getProperty name="MyBean" property="available"/>

</body>
</html>
We slightly change the show.jsp page.
<jsp:setProperty name="MyBean" property="*"/>
This element will automatically fill the bean properties with the request parameters. This works only if the parameter names match the bean property names.
In this chapter we have briefly mentioned Java Beans.

Exceptions in Java EE 5

Exceptions

In this part of the JEE tutorials we will work with Exceptions.
An exception is a condition, often an error, that causes a program to call a different routine. Exceptions should be divided in some logical groups. For example, we can divide exceptions into application exceptions and system exceptions. System exceptions react to low level system errors. Like memory shortage, lost connection etc. Application exceptions are higher level errors. They are usually less serious. They occur when some rules in application logic are broken. For example, when a user enters invalid data, an application exception is called.
In our next example, we will work with both kinds of exceptions. We will react to three kind of system exceptions and one kind of application exception. We will have system errors and application warnings. To inform user about exceptions, we will create message windows. This will be created using css and JavaScript. The example is quite complicated. Works on Firefox and Opera.
style.css
* { font-size: 12px; font-family: Verdana }

form { margin-top: 5%; }

input, textarea { border: 1px solid #ccc }

.message {
position: absolute;
display: none;
background: #577580;
width: 235px;
height: 150px;
cursor: move;
padding: 5px;
color: white;
}

.header {
font-weight: bolder;
margin-bottom: 7px;
}

a#close {
position: absolute;
display: block;
border: 1px solid #ccc;
padding: 2px;
width: 60px;
bottom: 20px;
left: 88px;
text-decoration: none;
font-weight: bolder;
color: white;
}
This is a stylesheet applied to our example. The .message class creates a message window for us. It is initially not visible. The .header class creates header of the message window. The close selector defines style for an anchor, that will serve as our close button.
util.js
var savedTarget = null;
var orgCursor = null;
var dragOK = false;
var dragXoffset = 0;
var dragYoffset = 0;

function showError() {
if (msg.style.display == 'block') {
msg.style.display = 'none';
msg.innerHTML = '';
} else {
msg.style.display = 'block';
msg.innerHTML = '<b>Error</b><p>';
var string = error + '</p><center>';
string += '<a id="close" href="javascript:showError()">';
string += 'close</a></center>';
msg.innerHTML += string;
}
}

function showWarning() {
if (msg.style.display == 'block') {
msg.style.display = 'none';
msg.innerHTML = '';
} else {
msg.style.display = 'block';
msg.innerHTML = '<b>Warning</b><p>';
var string = warning + '</p><center>';
string += '<a id="close" href="javascript:showWarning()">';
string += 'close</a></center>';
msg.innerHTML += string;
}
}

function moveHandler(e){
if (e == null) { e = window.event }
if (e.button <= 1 && dragOK){
savedTarget.style.left = e.clientX - dragXoffset + 'px';
savedTarget.style.top = e.clientY - dragYoffset + 'px';
return false;
}
}

function cleanup(e) {
document.onmousemove = null;
document.onmouseup = null;
savedTarget.style.cursor = orgCursor;
dragOK = false;
}

function dragHandler(e){
var htype='-moz-grabbing';
if (e == null) { e = window.event; htype = 'move';}
var target = e.target != null ? e.target : e.srcElement;
orgCursor = target.style.cursor;

if (target.className == "message") {
savedTarget = target;
target.style.cursor = htype;
dragOK = true;
dragXoffset = e.clientX - parseInt(msg.style.left);
dragYoffset = e.clientY - parseInt(msg.style.top);
document.onmousemove = moveHandler;
document.onmouseup = cleanup;
return false;
}
}

document.onmousedown = dragHandler;
The util.js file will have most of the javascript code. The showWarning() function displays the application warning message window, the showError() displays the system error message window. The moveHandler(), cleanup() and dragHandler() fuctions enable to move the window with the mouse pointer. The javascript code is adapted from hunlock.com.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Exceptions</title>

<link rel="stylesheet" href="style.css" type="text/css">
<script src="util.js" type="text/javascript" ></script>

<script type="text/javascript">

<%!
String error;
String warning;
String okm;
%>

<%
error = (String) request.getAttribute("ErrorMessage");
warning = (String) request.getAttribute("Warning");
okm = (String) request.getAttribute("OkMessage");
%>

var error = "<%=error%>";
var warning = "<%=warning%>";
var okm = "<%=okm%>";
</script>

</head>

<body>
<h2>Exceptions</h2>

<center>
<form action="ProcessServlet" >
<table>
<tr>
<td>From</td>
<td><input type="text" name="from"></td>
</tr>
<tr>
<td>To</td>
<td><input type="text" name="to"></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="subject"></td>
</tr>
<tr>
<td>Message</td>
<td><textarea cols="25" rows="8" name="message"></textarea></td>
</tr>
</table>
<br>
<input type="submit" value="submit">
</form>
</center>

<div id="messageID" class="message"></div>

<script type="text/javascript">

msg = document.getElementById('messageID');
msg.style.top = (window.innerHeight-235) / 2;
msg.style.left = (window.innerWidth-150) / 2;

</script>

<%
if (error != null) {
%>

<script>
showError();
</script>

<% } else if (warning != null) { %>
<script type="text/javascript">
showWarning();
</script>

<% } else if (okm != null) {
out.print(okm);
} %>

</body>
</html>
The index.jsp file creates a html form. It is also a place, where message windows will pop up.
var error = "<%=error%>";
var warning = "<%=warning%>";
var okm = "<%=okm%>";
Here we can see, how data from java code is passed to javascript. These JavaScript variables will determine, which message window will appear on the screen.
<div id="messageID" class="message"></div>
The message window is a simple div tag. It is initially not visible. If an exception occurs, the div is made visible by the javascript code. The visibility of the tag is changed from none to block.
msg = document.getElementById('messageID');
msg.style.top = (window.innerHeight-235) / 2;
msg.style.left = (window.innerWidth-150) / 2;
This javascript code positions the window into the middle of the screen.
<%
if (error != null) {
%>

<script>
showError();
</script>

<% } else if (warning != null) { %>
<script type="text/javascript">
showWarning();
</script>

<% } else if (okm != null) {
out.print(okm);
} %>
This embedded java code decides, which message window to display. If no exception occurs, we simply output All OK message.
Message Window
Figure: Message Window
Process.java
package com.zetcode;

import java.io.*;
import java.net.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import com.mysql.jdbc.CommunicationsException;

public class Process extends HttpServlet {

protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

Connection con;
String url = "jdbc:mysql://localhost:3306/";

try {

this.testForm(request);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, "root", "");
con.close();

} catch (CommunicationsException ex) {
request.setAttribute("ErrorMessage",
"Cannot connect to database");

RequestDispatcher dispatcher =
request.getRequestDispatcher("/index.jsp");

dispatcher.forward(request, response);

} catch (SQLException ex) {
request.setAttribute("ErrorMessage", ex.getMessage());

RequestDispatcher dispatcher =
request.getRequestDispatcher("/index.jsp");

dispatcher.forward(request, response);

} catch (ClassNotFoundException ex) {
request.setAttribute("ErrorMessage", "MySQL driver not found");

RequestDispatcher dispatcher =
request.getRequestDispatcher("/index.jsp");

dispatcher.forward(request, response);

} catch (UserException ex) {
request.setAttribute("Warning", ex.getMessage());

RequestDispatcher dispatcher =
request.getRequestDispatcher("/index.jsp");

dispatcher.forward(request, response);
}

request.setAttribute("OkMessage", "All OK");
RequestDispatcher dispatcher =
request.getRequestDispatcher("/index.jsp");

dispatcher.forward(request, response);
}

public void testForm(HttpServletRequest request) throws UserException {

String from = (String) request.getParameter("from");
String to = (String) request.getParameter("to");
String subject = (String) request.getParameter("subject");
String message = (String) request.getParameter("message");

if (from.isEmpty() || to.isEmpty() ||
subject.isEmpty() || message.isEmpty() ) {
throw new UserException("Form not correctly filled");
}

}

protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
This is the servlet, where the exceptions arise. It does nothing in particular, only enables us the test various error conditions. The servlet will react to four different exceptions: CommunicationsException, SQLException, ClassNotFoundException and UserException. We can test the CommunicationsException by shutting down the MySQL database. The SQLException will arise, when we e.g. provide invalid password to the database user. If we do not include MySQL driver library , we will have the ClassNotFoundException. Finally, the UserExeption will occur, when at least one of the form parameters is empty.
sudo /etc/init.d/mysql stop
Here we stop the MySQL database server.
} catch (CommunicationsException ex) {
request.setAttribute("ErrorMessage",
"Cannot connect to database");

RequestDispatcher dispatcher =
request.getRequestDispatcher("/index.jsp");

dispatcher.forward(request, response);
}
This exception will react to the system error, caused by the lost connection. The code sets an attribute to the request and forwards back to the index.jsp page.
public void testForm(HttpServletRequest request) throws UserException {

String from = (String) request.getParameter("from");
String to = (String) request.getParameter("to");
String subject = (String) request.getParameter("subject");
String message = (String) request.getParameter("message");

if (from.isEmpty() || to.isEmpty() ||
subject.isEmpty() || message.isEmpty() ) {
throw new UserException("Form not correctly filled");
}
}
The testForm() method will test if all parameters are set. If not, we throw an UserExeption.
UserException.java
package com.zetcode;


public class UserException extends Exception {

public UserException(String msg) {
super(msg);
}

public String getMessage() {
return super.getMessage();
}
}
The UserException is an application exception. This exception will cause the warning message windows.
In this chapter we have briefly mentioned exceptions.

DataSource And DriverManager Java EE 5

DataSource & DriverManager

In this part of the JEE 5 tutorials, we will compare DataSource object with the DriverManager object.
DataSource and the DriverManager are the two basic ways to connect to a database in a JEE application. The DriverManager is older facility, DataSource is newer. It is recommended to use the new DataSource facility to connect to databases and other resources. DataSource facility has several advantages over DriverManager facility. Using DataSource increases portability. The DataSource enables connection pooling and distributed transactions, the DriverManager does not allow such techniques. Properties of a DataSource are kept in a configuration file. Any changes to the data source or database drivers are made in the configuration file. In case of a DriverManager, these properties are hard coded in the application and for any changes we must recompile the code.
In this chapter, we will have two examples. One of the examples will use a DriverManager, the other one will use a DataSource to connect to a MySQL database.
mysql> describe books;
+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| author | varchar(30) | YES | | NULL | |
| title | varchar(40) | YES | | NULL | |
| year | int(11) | YES | | NULL | |
| remark | varchar(100) | YES | | NULL | |
+--------+--------------+------+-----+---------+----------------+
5 rows in set (0.27 sec)
We will use a books table.

DriverManager

The first example will use a DriverManager.
style.css
* { font-size: 12px; font-family: Verdana }

td { border: 1px solid #ccc; padding: 3px }
th { border: 1px solid #ccc; padding: 3px;
background: #009999; color: white }

This is the stylesheet file.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>DriverManager</servlet-name>
<servlet-class>com.zetcode.DriverManagerExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DriverManager</servlet-name>
<url-pattern>/DriverManager</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
In the web.xml configuration file, we configure our servlet.
DriverManagerExample.java
package com.zetcode;

import java.io.*;
import java.net.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;


public class DriverManagerExample extends HttpServlet {

static final String url = "jdbc:mysql://localhost:3306/books";


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

try {


Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");

Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM books");

out.print("<html>");
out.print("<head>");
out.print("<title>Servlet NewServlet</title>");
out.print("<link rel='stylesheet' href='style.css' type='text/css'>");
out.print("</head>");
out.print("<body>");

out.print("<table>");
out.print("<tr>");
out.print("<th>Author</th>");
out.print("<th>Title</th>");
out.print("<th>Year</th>");
out.print("<th>Remark</th>");
out.print("</tr>");


while (result.next()) {
out.print("<tr>");
out.print("<td>");
out.print(result.getString("author"));
out.print("</td>");
out.print("<td>");
out.print(result.getString("title"));
out.print("</td>");
out.print("<td>");
out.print(result.getString("year"));
out.print("</td>");
out.print("<td>");
out.print(result.getString("remark"));
out.print("</td>");
out.print("</tr>");
}

con.close();

} catch (SQLException ex) {
Logger.getLogger(DriverManagerExample.class.getName()).log(
Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DriverManagerExample.class.getName()).log(
Level.SEVERE, null, ex);
} finally {
out.close();
}
}


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

processRequest(request, response);
}


protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

processRequest(request, response);
}

}
The example will display a books table from the books database in a html table.
static final String url = "jdbc:mysql://localhost:3306/books";
We provide the connection url. This is an url for a MySQL database.
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
We load the driver and get the connection to the database.
DriverManager
Figure: DriverManager

DataSource

The next example uses the DataSource facility. We use the same data.
style.css
* { font-size: 12px; font-family: Verdana }

td { border: 1px solid #ccc; padding: 3px }
th { border: 1px solid #ccc; padding: 3px;
background: #009999; color: white }
Simple stylesheet.
resin-web.xml
<web-app xmlns="http://caucho.com/ns/resin">
<!--
- Configures the database.
-
- jndi-name specifies the JNDI name
- type specifies the driver class
- path is a driver-specific configuration parameter
-->
<database>
<jndi-name>jdbc/mysql</jndi-name>
<driver>
<type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type>
<url>jdbc:mysql://localhost:3306/books</url>
<user>root</user>
<password></password>
</driver>
</database>

<!--
- Configures the initialization servlet. The bean-style init
- it used to look up the JNDI DataSource in the configuration file.
-->

<servlet>
<servlet-name>datasource</servlet-name>
<servlet-class>com.zetcode.DataSourceExample</servlet-class>
<init>
<data-source>${jndi:lookup('jdbc/mysql')}</data-source>
</init>
</servlet>

<servlet-mapping>
<url-pattern>/DataSource</url-pattern>
<servlet-name>datasource</servlet-name>
</servlet-mapping>

</web-app>
This is the resin-web.xml configuration style. It is Resin specific. It overrides the configuration in the web.xml file. In our file, we configure the datasource and the servlet mapping.
The DataSource configuration is done within the <database> tags. We specify the driver type, connection url, user name and password.
In our example, we use the JNDI (The Java Naming and Directory Interface) API. This API is used to look up data and objects via a name. The JNDI enables separation of resource configuration from the application code.
DataSourceExample.java
package com.zetcode;

import java.io.*;
import java.net.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

public class DataSourceExample extends HttpServlet {

private DataSource _ds = null;


public void setDataSource(DataSource ds) {
_ds = ds;
}


public void init()
throws ServletException {
if (_ds == null) {

throw new ServletException("datasource not properly configured");
}
}

protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();


try {

Connection conn = _ds.getConnection();

Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM books");

out.print("<html>");
out.print("<head>");
out.print("<title>DataSource</title>");
out.print("<link rel='stylesheet' href='style.css' type='text/css'>");
out.print("</head>");
out.print("<body>");

out.print("<table>");
out.print("<tr>");
out.print("<th>Author</th>");
out.print("<th>Title</th>");
out.print("<th>Year</th>");
out.print("<th>Remark</th>");
out.print("</tr>");


while (result.next()) {
out.print("<tr>");
out.print("<td>");
out.print(result.getString("author"));
out.print("</td>");
out.print("<td>");
out.print(result.getString("title"));
out.print("</td>");
out.print("<td>");
out.print(result.getString("year"));
out.print("</td>");
out.print("<td>");
out.print(result.getString("remark"));
out.print("</td>");
out.print("</tr>");
}


out.print("</table>");
out.println("</body>");
out.println("</html>");

result.close();
stmt.close();
conn.close();

} catch (SQLException ex) {
Logger.getLogger(DataSourceExample.class.getName()).log(
Level.SEVERE, null, ex);
} finally {
out.close();
}
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

processRequest(request, response);
}
}
The example will display a books table from the books database in a html table too.
public void setDataSource(DataSource ds) {
_ds = ds;
}
The method is called by the Resin application server at configuration time.
public void init()
throws ServletException {
if (_ds == null) {

throw new ServletException("datasource not properly configured");
}
}
The init() method checks whether the datasource was configured properly.
Connection conn = _ds.getConnection();
We get the connection from the datasource object.
This chapter of the JEE tutorials was about DataSource and DriverManager.
DataSource
Figure: DataSource
In this chapter we have briefly mentioned DataSource and DriverManager.

Creating a captcha in a Java Servlet

Creating a captcha in a Servlet

In this part of the JEE tutorials we will use a captcha test in our form.
A captcha is a type of challenge-response test used in computing to determine whether the user is human. Captcha is a contrived acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart". (Wikipedia) Using captchas on Internet is almost inevitable, because the forums and message boards are infested with spam.

Captcha

In the following example, we will demonstrate a captcha system in a small example. We have a html form. At the bottom of the form, we have a input tag named code. Here the user has to copy the characters of an image, which is displayed below the input box. This is the most common captcha system on the Internet. The main part of the captcha system is a image, displaying random alphanumeric characters. The characters are usually blurred or otherwise made a bit more difficult to read.
style.css
* { font-size: 12px; font-family: Verdana }

input, textarea { border: 1px solid #ccc }

tr { margin: 5px; padding:5px;}

.alert { font-size:15px; color:red; font-weight:bolder }
This is a simple stylesheet for our example. The .alert class is used to format text displaying whether we passed the test or not.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Captcha</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<form method="post">
<table cellspacing="15">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Message</td>
<td> <textarea type="text" cols="25" rows="8" name="message"></textarea></td>
</tr>

<tr>
<td>Are you human?</td>
<td><input type="text" name="code"></td>
</tr>

</table>

<br>
<img src="http://localhost:8080/captcha/CaptchaServlet">

<br><br>
<input type="submit" value="submit">

</form>
<br><br>
<%
String captcha = (String) session.getAttribute("captcha");
String code = (String) request.getParameter("code");

if (captcha != null && code != null) {

if (captcha.equals(code)) {
out.print("<p class='alert'>Correct</p>");
} else {
out.print("<p class='alert'>Incorrect</p>");
}
}
%>
</center>
</body>
</html>
This is the file, where we define the html form, load the captcha image and react to submit action.
<form method="post">
If we don't provide the action parameter, the processing is transfered to the same file by default. e.g index.jsp in our case.
<img src="http://localhost:8080/captcha/CaptchaServlet"> 
This is the way, how we get the image from the servlet. We provide the location of the servlet to the src parameter of the html img tag. Each time we refresh the page, we get a new image from the CaptchaServlet.
String captcha = (String) session.getAttribute("captcha");
String code = (String) request.getParameter("code");

if (captcha != null && code != null) {

if (captcha.equals(code)) {
out.print("<p class='alert'>Correct</p>");
} else {
out.print("<p class='alert'>Incorrect</p>");
}
}
This code receives the parameters from the request. The message and name parameters are ignored. The captcha is a string, that is set randomly by the servlet. This string is being shown in the image. The code is the text, which is put by the user. If these two strings match, we output "Correct" string, otherwise "Incorrect".
Captcha
Figure: Captcha
CaptchaServlet.java
package com.zetcode;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;

import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;


public class CaptchaServlet extends HttpServlet {


protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

int width = 150;
int height = 50;

char data[][] = {
{ 'z', 'e', 't', 'c', 'o', 'd', 'e' },
{ 'l', 'i', 'n', 'u', 'x' },
{ 'f', 'r', 'e', 'e', 'b', 's', 'd' },
{ 'u', 'b', 'u', 'n', 't', 'u' },
{ 'j', 'e', 'e' }
};


BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = bufferedImage.createGraphics();

Font font = new Font("Georgia", Font.BOLD, 18);
g2d.setFont(font);

RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(rh);

GradientPaint gp = new GradientPaint(0, 0,
Color.red, 0, height/2, Color.black, true);

g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);

g2d.setColor(new Color(255, 153, 0));

Random r = new Random();
int index = Math.abs(r.nextInt()) % 5;

String captcha = String.copyValueOf(data[index]);
request.getSession().setAttribute("captcha", captcha );

int x = 0;
int y = 0;

for (int i=0; i<data[index].length; i++) {
x += 10 + (Math.abs(r.nextInt()) % 15);
y = 20 + Math.abs(r.nextInt()) % 20;
g2d.drawChars(data[index], i, 1, x, y);
}

g2d.dispose();

response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(bufferedImage, "png", os);
os.close();
}


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
In the Captcha servlet, we create an image of 150*50 size. To create the image, we use the Java 2D vector library. The image is filled with red - black gradient. We draw randomly a string into the image.
char data[][] = {
{ 'z', 'e', 't', 'c', 'o', 'd', 'e' },
{ 'l', 'i', 'n', 'u', 'x' },
{ 'f', 'r', 'e', 'e', 'b', 's', 'd' },
{ 'u', 'b', 'u', 'n', 't', 'u' },
{ 'j', 'e', 'e' }
};
This is an array, from which we choose our string.
BufferedImage bufferedImage = new BufferedImage(width, height, 
BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = bufferedImage.createGraphics();
We will draw into a buffered image.
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(rh);
The rendering hints are used to increase the quality of the text.
g2d.setRenderingHints(rh);

GradientPaint gp = new GradientPaint(0, 0,
Color.red, 0, height/2, Color.black, true);

g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);
Here we draw the gradient.
Random r = new Random();
int index = Math.abs(r.nextInt()) % 5;

String captcha = String.copyValueOf(data[index]);
request.getSession().setAttribute("captcha", captcha );
Here we randomly choose an index into the array. We also set the chosen string into the session, so that we can compare it later to the parameter, specified by the user.
int x = 0; 
int y = 0;

for (int i=0; i<data[index].length; i++) {
x += 10 + (Math.abs(r.nextInt()) % 15);
y = 20 + Math.abs(r.nextInt()) % 20;
g2d.drawChars(data[index], i, 1, x, y);
}
This is the code, that draws the string into the image. We must make sure, that the text fits into the boudaries of the image.
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(bufferedImage, "png", os);
os.close();
Finally, we return the image through a byte stream. We set a content type to png image. The write() method of the ImageIO class writes the data from the buffered image into the servlet output stream. This way we send binary data to the client.
In this chapter we have created a captcha in a Java Servlet.

Sending email in a Java Servlet

Sending email in a Servlet

In this part of the JEE tutorials we will send an email using a servlet. To work with email, we use the Java Mail API. If we build the example with the Netbeans IDE (with the JEE pack), the necessary jars are provided. Otherwise we need to download the mail.jar and the activation.jar files.

Sending email

In the next example we fill in the form and send an email. We use the Java Mail API. In order to succeed sending an email, we must have a gmail account. We use the Google's smtp server to forward the email. So in the form, we must provide the login and the password of our gmail account. The example consists of five files. A css style file provides the look and feel for our jsp pages. The index.jsp is used to fill in the form and send the data to the servlet. The EmailServlet processes the data and tries to send the email to the recipient. If it succeeds, the servlet forwards to the success.jsp file. If not, we receive an error message in error.jsp file.
style.css
* { font-size: 12px; font-family: Verdana }

input, textarea { border: 1px solid #ccc }
textarea { text-align:left}
table { margin-top: 10% }

.error { margin-top: 10%; border: 1px dotted #db1f1f; width: 250px }
.msg { margin-top: 10%; border: 1px dotted #ccc; width: 250px }
This is a stylesheet file. The .error class provides a style for the error message. It is a dotted red rectangle. The .msg class is used in the success.jsp file. It is a gray dotted rectangle.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sending email</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<center>
<form action="EmailServlet">
<table>
<tr>
<td>From</td>
<td><input type="text" name="from"></td>
</tr>
<tr>
<tr>
<td>To</td>
<td><input type="text" name="to"></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="subject"></td>
</tr>
<tr>
<td>Message</td>
<td><textarea cols="25" rows="8" name="message"></textarea></td>
</tr>
<tr>
<td>Login</td>
<td><input type="text" name="login"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
</table>
<br>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>
This is the form for sending the email. There are also inputs for the gmail's login and password.
Email Form
Figure: Email Form
EmailServlet.java
package com.zetcode;

import java.io.*;
import java.net.*;

import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmailServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

final String err = "/error.jsp";
final String succ = "/success.jsp";

String from = request.getParameter("from");
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String message = request.getParameter("message");
String login = request.getParameter("login");
String password = request.getParameter("password");

try {
Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");

Authenticator auth = new SMTPAuthenticator(login, password);

Session session = Session.getInstance(props, auth);

MimeMessage msg = new MimeMessage(session);
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(msg);

} catch (AuthenticationFailedException ex) {
request.setAttribute("ErrorMessage", "Authentication failed");

RequestDispatcher dispatcher = request.getRequestDispatcher(err);
dispatcher.forward(request, response);

} catch (AddressException ex) {
request.setAttribute("ErrorMessage", "Wrong email address");

RequestDispatcher dispatcher = request.getRequestDispatcher(err);
dispatcher.forward(request, response);

} catch (MessagingException ex) {
request.setAttribute("ErrorMessage", ex.getMessage());

RequestDispatcher dispatcher = request.getRequestDispatcher(err);
dispatcher.forward(request, response);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
dispatcher.forward(request, response);

}

private class SMTPAuthenticator extends Authenticator {

private PasswordAuthentication authentication;

public SMTPAuthenticator(String login, String password) {
authentication = new PasswordAuthentication(login, password);
}

protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
This is the servlet, that tries to send the email.
String from = request.getParameter("from");
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String message = request.getParameter("message");
String login = request.getParameter("login");
String password = request.getParameter("password");
We get the necessary parameters from the request.
Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
The properties class is used for configuration. Notice that we set the authentication property to true.
Authenticator auth = new SMTPAuthenticator(login, password);
We create a new Authenticator class to check the login and the password.
Session session = Session.getInstance(props, auth);
We create a new mail session. We provide the properties and the Authenticator.
MimeMessage msg = new MimeMessage(session);
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(msg);
Here we create a message. We set the text of the message, subject, sender and recipient email addresses. Finally, we send the email message.
} catch (AuthenticationFailedException ex) {
request.setAttribute("ErrorMessage", "Authentication failed");

RequestDispatcher dispatcher = request.getRequestDispatcher(err);
dispatcher.forward(request, response);
}
Many things might go wrong, while sending an email. For example we might provide a wrong email address or the authentication fails. Here we react to an AuthenticationFailedException. If we receive such an exception, we set an ErrorMessage attribute to the request and forward to the error.jsp file. The ErrorMessage attribute will be used in the error.jsp file.
error.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<center>
<div class="error">
<h2>Error</h2>
<p>
Message: <%= request.getAttribute("ErrorMessage") %>
</p>
</div>
</center>
</body>
</html>
This jsp file will be displayed, when an error occurs. The ErrorMessage attribute, which was set in the servlet, is displayed.
success.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<title>Message</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<center>
<div class="msg">
<h2>Message</h2>
<p>
Email sent
</p>
</div>
</center>
</body>
</html>
This is the jsp file, which will be displaed, if no errors occured.
In this chapter we have sent an email using a Java Servlet.