0% found this document useful (0 votes)
87 views80 pages

Java Lessons

This document provides an introduction to server-side programming using Java frameworks and libraries. It discusses application servers, common Java EE components like Servlets and JSPs, and tools like Maven and Tomcat. It also covers data access using JDBC and Hibernate. Key topics include how application servers offload work from web servers, how to set up and use Maven to build and manage Java projects, and examples of connecting to and querying databases.

Uploaded by

Adi Rere
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
87 views80 pages

Java Lessons

This document provides an introduction to server-side programming using Java frameworks and libraries. It discusses application servers, common Java EE components like Servlets and JSPs, and tools like Maven and Tomcat. It also covers data access using JDBC and Hibernate. Key topics include how application servers offload work from web servers, how to set up and use Maven to build and manage Java projects, and examples of connecting to and querying databases.

Uploaded by

Adi Rere
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 80

PROGRAMMING USING

Lesson 6
Introduction to
the de­velopment
of server-based
solutions using Java,
Interaction with
data sources

Contents
Server Programming......................................................... 4
Frameworks and Libraries................................................ 7
Maven......................................................................................7
Tomcat...................................................................................19
JBoss.......................................................................................26
Spring.....................................................................................26
The first Spring application.................................................29
The second Spring application...........................................35
Hibernate..............................................................................39
The Concept of a Servlet................................................. 42
Data sources .................................................................... 56
JDBC......................................................................................56
Example of using Hibernate...............................................67
Homework Assignment................................................... 80

2
Server Programming

Server Programming
You are already familiar with the structure of web applica-
tions and remember that they consist of the client and server
parts. The client part of the web application is usually a browser
that generates requests to the server part of the application,
receives responses to its requests from the server, and displays
the information received from the server in the client area of
the browser.
The server part of the application can be created using
various software technologies. Consider how to create web
applications on the Java platform. The Java platform is divided
into several components, the main ones being SE (Standard
Edition) and EE (Enterprise Edition). So far, you have worked
within the SE platform. You have already seen that this platform
allows you to create a wide range of applications: console, with
graphical user interface, desktop, network, multithreaded, etc.
Does it have a limit of possibilities? Yes. Using Java SE, you
can not create web applications. To create web applications,
you must use the Java EE platform. Therefore, we need to
consider the possibilities of this platform.
But first you need to get acquainted with the new term —
application server. As soon as client server applications began
to be created, the developers faced the question: which part
of the application to load more, who in this pair (client or
server) should perform more actions?
Often the answer was dictated by the logic of a specific
situation. Of course, you know the answer to this question for
the case of web applications. In a browser&web-server pair,

3
Lesson 6

the client part, i.e. the browser, performs much more work
than the server part — the web server. This is done deliber-
ately, because one web server should be able to quickly serve
many clients, and one tries to minimize its workload as much
as possible. Even with this approach, the web server is often
the «narrow part» of the application. To unload it even more,
use the so-called application servers. The application server
is software that is located somewhere near the server side
of the application and takes over part of the client requests,
partially unloading the server itself. Perhaps you do not know
that IIS known to you for a long time is not a web server at
all, as many people think. This is a typical application server,
which in addition to the functions of the web server can per-
form a number of other actions. For example, deploy services,
including the WCF services.
In Java EE, application servers are used very widely. Soon
we will talk about utilities such as Tomcat or GlassFish, which
are typical representatives of application servers.
Now we can briefly talk about the main components of
Java EE. A more detailed conversation will be continued later
in this lesson.
So, the basic components of Java EE:
■■ To process client HTTP requests, Java EE offers such an
API as Servlet. Servlet is a Java class that can accept client
requests, process them, and send responses to the client.
Servlet is deployed and run on the application server —
for example, on Tomcat or GlassFish.
■■ To create interactive, dynamic html pages, use the API
Java Server Pages (JSP). This is a kind of server-side Java
language. JSP is used in conjunction with Servlet.

4
Server Programming

■■ To create web services, Java EE offers Enterprise JavaBeans


(EJB) technology. If you understand the statement that
a regular Java application consists of classes, then, by anal-
ogy, you can now remember that the web service consists
of EJB components that very much resemble classes, but
are more suitable for web services and therefore have more
advantages. EJBs initially support remote access, are mul-
tithreaded, support transactions, ensure data integrity and
have a number of other useful features.
■■ Java EE also offers its own API for working with data
sources, for working with JSON format, for processing
emails, for working with REST-services, and others. We will
also talk about some of these components in our lessons.
Details of the structure of the Java EE platform can be
found on the official website at: http://www.oracle.com/tech-
network/java/javaee/tech/index.html.

5
Lesson 6

Frameworks and Libraries


Maven
You have already created a lot of Java projects. In this case,
most likely, you did not really think about what the project
is, what parts it consists of, and how these parts are related to
each other. All this work is done by for you the IDE. It’s time
to consider this process in more detail.
What are the stages of the project? These are the compila-
tion of source files, the creation of a jar-file, distribution and
documentation. Generally speaking, this is a large amount
of work, especially when the built project consists of a large
number of files. This work is done with special tools. Now
we’ll look at one of them — the Maven utility.
Consider the advantages of this utility. Creating a Java
project using Maven is performed based on a script written in
a special xml file. This script is platform independent and allows
you to build a project in Windows or Linux without changing
the script file. As a rule, the creation of a project requires the con-
nection of various third-party libraries. In such a situation it is
necessary to take into account that different versions of such
libraries can conflict with each other. Maven is able to solve
such dependency problems and ensures the non-conflicting
operation of the connected libraries. The format of the project,
built with the help of Maven, is freely opened by the main inte-
grated development environments, which is also a big plus of
this utility. In addition, the management of the project creation
process is performed declaratively in XML format.

6
Frameworks and Libraries

Let’s install this utility and compile a simple Java project


with it. To install Maven, go to http://maven.apache.org/
download.cgi and download the distribution:

Figure 1. Downloading Maven


Now unpack the zip archive into any directory on your
disk — for example, directly to the system drive on the path C:\
apache-maven-3.5.0. Then click Win+Pause, go to Advanced
Settings and in the window that appears, click the button
Environment Variables below. Then, in the System Variables
window, create the following variables with the specified values:
■■ M2_HOME variable with the path value where you copied
Maven; in my case — C:\apache-maven-3.5.0;
■■ M2 variable with the value %M2_HOME%\bin;
■■ MAVEN_OPTS variable with the value — Xms256m or —
Xms512m;
■■ Path variable with the value %M2%.
Now check to see if you have a variable named JAVA_
HOME and with the value of the path where JDK is in-
stalled. In my case, this is the path C:\Program Files\Java\

7
Lesson 6

jdk1.8.0_25. If this variable does not exist, create it. Restart


the computer.
Run the following command in the console window:
mvn –version

to verify that the installation and configuration of Maven were


successful. You should see the version of the installed utility
and other related information. At me it looks so:

Figure 2. Maven version


Now you can proceed to build the project. Create a fol­
der somewhere, for example, with the name test, go to it in
the console window and run the following command:
mvn archetype:generate – DgroupId=com.mycompany.app –
DartifactId=project1 – DarchetypeArtifactId = maven–
archetype–quickstart – DinteractiveMode = false

The very first launch of Maven can take a long time, because
at this moment, the actual versions of all the necessary tools
are loaded. We must wait a little. In addition, if you go online
through a proxy, you must specify this in the Maven configu-
ration settings. In this case, open the file {M2_HOME}/conf/
settings.xml and enter the information for passing the proxy
in it. Find the proxy section in this file, uncomment it and
bring it to this form:

8
Frameworks and Libraries

<proxies>
<!-- proxy
| Specification for one proxy, to be used in
| connecting to the network.
| -->
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxy_user</username>
<password>proxy_pass</password>
<host>10.3.0.3</host>
<port>3838</port>
<nonProxyHosts>local.net|some.host.com
</nonProxyHosts>
</proxy>
</proxies>

Instead of proxy_user and proxy_pass, you must specify


a user and password for passing the proxy, and instead of
10.3.0.3 and 3838 — the proxy server’s address and port number.
After the successful completion of this command, you will
see something like this in your console window:

Figure 3. Successful creation of the Maven project

9
Lesson 6

After executing this command, the project1 folder will


be created in the test folder, according to the value specified
on the command line in the DartifactId attribute. The created
project will be located in this folder,. You will see there two
folders with names src and target, containing files with source
codes for the project and files with unit tests, respectively.
The project will be created in accordance with the script writ-
ten in the pom.xml file located directly in the project1 folder.
Initially, pom.xml looks like this:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/
XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/
POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>project1</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>project1</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

The groupId element, as a rule, specifies the domain


name for the project, for example com.mycompany.app.

10
Frameworks and Libraries

The artifactId and version elements form the complete name


of the project file, and the packaging element forms its
extension. In our case (we use the default values ​​of these
elements, except artifactId), the project file will be named
project1-1.0-SNAPSHOT.jar.
The main class template of the created application looks
like this:

package com.mycompany.app;
/*
* Hello world!
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}

Now, to build the project in the console window, run


the command:
mvn clean package

Generally speaking, this command performs two actions


at once: it deletes the components of the created project,
if they were already created (clean), and creates a project
(package). If you create the project for the first time, the clean
command can be omitted. In the target folder you should now
have the created jar project file named project1-1.0-SNAP-
SHOT.jar. This name is created by combining the values ​​of
the artifactId and version elements from the pom.xml file. It
11
Lesson 6

is clear that the values given


​​ are the default values, and they
can be changed.
Maven supports two project building modes: auto­
matic and interactive. The so-called archetype responds for
the build mode. If the mvn archetype:generate command is
present in the console command, the contents of the pom.
xml file are generated based on the data from the console
command. This is the case in our situation. When using
the interactive mode, initialization of the necessary param-
eters is carried out in stages by hand. We will not consider
this build mode.
Note that after executing the last command in the target
folder, there were a number of other changes, among which:
■■ a surefire-reports folder was created in which the file with
the com.mycompany.app.AppTest.txt report was created,
■■ a classes folder was created in which the compiled App.
class class was created,
■■ a maven-archiver folder was created with the properties
file of the created pom.properties project,
Now you need to run the following command in the con-
sole window:

java –cp target/project1-1.0-SNAPSHOT.jar com.


mycompany.app.App

to check the created project. When the command is activated,


you will see the result of executing the main() method from
the created Maven of the main class of the App.java application
in the console window.
12
Frameworks and Libraries

Figure 4. Successful execution of the Maven project


Now let’s see how using Maven you can add a new class
to the created project. Create a file named Fish.java next to
the App.java file and paste the class definition into it:

public class Fish


{
private String name;
private double weight;
private double price;

public Fish(String name, double weight, double price)


{
this.name=name;
this.weight=weight;
this.price=price;
}

public double getWeight()


{
return this.weight;
}

public double getPrice()


{
return this.price;
}

@Override
public String toString()
{

13
Lesson 6

return this.name+" weight:"+this.weight+"


price:"+this.price;
}
}

Next, you need to make changes to App.java to some-


how use the added class. We simply create an object of this
class and display its description in the console window. To
output an object description, use the overridden method
toString():

package com.mycompany.app;

/**
*
* Hello world!
*
*/

public class App


{
public static void main( String[] args )
{
Fish f = new Fish("salmon",2.5,180);
System.out.println( f );
}
}

Now we need to build the changed project. However, its


composition changed after the previous bulids, because we
added a new class. Therefore now it is necessary to notify
Maven, that it should execute compilation:
mvn clean compile

14
Frameworks and Libraries

After successful compilation, you can build the project.


In this case, the clean command will be more than appropri-
ate, since we have already performed the builds before, and
the results of these actions remain in the folders, which are
best removed before the new build:
mvn clean package

Now let’s execute our project again:

java –cp target/project1-1.0-SNAPSHOT.jar com.


mycompany.app.App

You should get a description of the created Fish class object


in the console window:

Figure 5. Successful execution of the changed project


In Windows OS, you can create a batch file and add several
Maven commands to it, which will be executed when such
a batch file is activated. Create the project1.bat file and insert
the following commands into it:

call mvn clean


call mvn package

15
Lesson 6

Now you just need to activate the project1.bat file in


the console window, and all Maven commands specified in
this file will be executed.
Maven also manages to generate documentation for the cre-
ated projects. Run the following command in the console
window:
mvn site

The first activation will take a long time, since Maven will
update the required dependencies. As a result of executing
the command, another folder named site will be created in
the target folder, and a site containing the project descrip-
tion will be placed in it. You can view this site by activating
the index.html file. For example, in my case, one of the pages
of the created site looks like this:

Figure 6. Project site


This site is created on the basis of pom.xml, and now it
does not contain any “personal” description of the project,
in addition to the general technical implementation. To add
more information about the project to the site, you need to
make changes to pom.xml. Bring this file to this form:

16
Frameworks and Libraries

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>project1</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>project1</name>
<url>http://maven.apache.org</url>
<description>
This project helps me to understand the basis
of Maven leverage
</description>
<developers>
<developer>
<id>Indy</id>
<name>Henry Walton "Indiana" Jones Jr</name>
<email>fourthdimension@world.com</email>
<roles>
<role>Project Manager</role>
<role>Developer</role>
</roles>
<organization>selfemployed</organization>
<timezone>-9</timezone>
</developer>
</developers>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

17
Lesson 6

Unlike the previous version of this file, you see two new
items added: description and developers. Although these
elements are inserted after the url element, this does not mean
that they should be located here. All elements can be added
anywhere in the file. The content of the description element
is displayed on the main page of the site. In this element you
can insert a detailed description of the project. If there is
a developers element in the main menu of the site, the Team
item appears, which displays information about the developers
of the project.

Figure 7. Project site


You can add a lot of different information about the proj-
ect to this site. You can read more about this, for example, via
the link: http://www.javaworld.com/article/2071733/java-
app-dev/get-the-most-out-of-maven-2-site-generation.html
Tomcat
In short, Tomcat is an application server for deploying
and executing Servlets and other web application components.
This is the product of the Apache Software Foundation com-
pany, the developer of the most popular Apache web server.
Tomcat, like most other products of this famous developer,
is an open source product.

18
Frameworks and Libraries

View a detailed description and download its distribu-


tion on the developer’s website at http://Tomcat.apache.org/
index.html.
This lesson will describe the installation of the Tomcat 8
version, a distribution of which can be downloaded from
http://Tomcat.apache.org/download-80.cgi.
Select the version you need based on the bit depth of your
operating system and download to your disk. For the Windows
operating system, this will be a zip archive. Deploy the archive
to a folder.
Before continuing, note that there is a known compatibil-
ity problem between Netbeans 8.1 and Tomcat, which often
leads to the inability to launch Tomcat in the specified version
of Netbeans. The network offers several ways to solve it. We
will offer you the best — just update Netbeans to version 8.2,
and compatibility problems will no longer exist. Believe me,
any way to fix this problem for Netbeans 8.1 is much more
time consuming than the regular update of Netbeans to
version 8.2. With this update, all your settings and previous
projects will not be affected.
At this point, you already have the NetBeans development
environment (preferably version 8.2), but probably now it
is configured to use the Java SE platform, and the Java EE
is not yet available. How do I know if the Java EE platform
is activated? Check if you have a Java Web and Java EE
project categories in the list of projects you are creating.
If you do not have them, then you need to install the Java
EE platform. It is not difficult to do this. First activate
the Tools – Plugins menu, as shown in the following
figure (Fig. 8).

19
Lesson 6

Figure 8. Adding a plug-in

Figure 9. Selecting and installing the Java EE platform

20
Frameworks and Libraries

In the window that appears, go to the Available plugins tab


and in the search box, in the upper right corner, enter what you
want to find, in our case — “web” or “Java EE base”. Then select
the “Java EE base” and “EJB and EAR” components in the left
pane, as shown in the figure, and finally click Install (Fig. 9).
After installing the plug-in, it may be necessary to over-
load NetBeans. To verify that the Java EE platform is installed,
go back to the File – New Project menu and check whether
the Java Web project type appeared there.

Figure 10. New project type Java Web


Please note, so far we have just installed the Java EE plat-
form. This platform allows you to create web applications. But
any web application requires an application server. Such as
Tomcat, which is waiting for us in the folder where we deployed
it. Now we’ll look at the process of installing Tomcat itself.

21
Lesson 6

Again activate the Tools – Servers menu. You will see


a window in which the application servers already installed
in your NetBeans are displayed. Perhaps this window will still
be empty, perhaps there will already be a GlassFish server
displayed — it does not matter for what we do. Therefore,
just click the Add Server button in the lower left corner of
the window, as shown in the figure:

Figure 11. Adding an Application Server


Now you will see a new window in which you can install
the required Tomcat. First, select the Apache Tomcat option
and click Next (Fig. 12).
In the next window, specify the path to the folder in which
you deployed the Tomcat distribution and other required data,
and click Finish (Fig. 13).

22
Frameworks and Libraries

Figure 12. Choosing Tomcat

Figure 13. Configuring Tomcat

After successfully completing these steps, your Tomcat


application server will be installed in your NetBeans, and

23
Lesson 6

will be used to develop web applications. To verify the Tom-


cat installation, go to the Services tab in the wizard window,
expand the Servers node, select Tomcat, and click the right
mouse button. From the context menu that appears, select
and activate the Start command.

Figure 14. Starting Tomcat


Now Tomcat is installed and ready to use. Very soon we
will start working with it, but for now consider some more
important components of the Java EE platform.

24
Frameworks and Libraries

JBoss
JBoss is another popular application server for the Java
EE platform. This product is an excellent platform for per-
forming medium and large distributed Java EE applications.
JBoss includes a set of preconfigured services that are required
to service them. Using JBoss provides such options for a dis-
tributed application:
■■ Clustering — the combination of a group of related com-
puters together is so dense that in many ways such com-
puters work as one;
■■ Load Balancing — optimization when distributing in-
coming requests;
■■ Caching of frequently used data — saving of such data
in temporary storage for the organization of faster access
to them;
Enterprise Java Beans — allows the use of these compo-
nents, which have gained wide popularity among developers
of Java EE.
In addition to the listed options, JBoss provides a number
of less significant ones. It’s clear that as an application server,
JBoss is the container for deploying and executing Java EE
components like Servlet and JSP.
Read more about this product on the official developer’s
website at http://www.jboss.org/.
Spring
You already know what a framework is. It is a software tool that
automates and formalizes the application development process.
There are many different frameworks for different programming
25
Lesson 6

languages. To work on Java, there is the Spring framework, which


is often called the framework of frameworks. This underlines its
importance and global relevance for Java development.
Although Spring is designed to develop Java EE appli-
cations, its individual modules can be used in other types of
applications. Here are the main features of this framework.
■■ Spring has a modular structure, and all its modules are
practically independent of each other. All you need to
know when using Spring is what module you need and
how to use it. At the same time, you may not know any-
thing about other modules at all, and this will not prevent
you from successfully working with Spring, because all
its modules work independently.
■■ Spring has its own MVC module, which allows you to do
without other MVC-frameworks.
■■ Spring has its own API for working with JDBC, which
eliminates the need for the developer to perform a huge
amount of routine work when using data sources.
■■ Spring has an API for processing exceptions that occur.
■■ Spring manages the creation of class objects that are part
of your application.
■■ Spring contains containers for managing the life cycle of
your application’s objects.
■■ Work with Spring is done declaratively.
■■ Applications created with Spring have a size of only about
2MB, which is also the advantage of this framework.
When creating an application, you should strive to ensure
that your classes are as independent as possible from each

26
Frameworks and Libraries

other. This will allow you to use them in other applications, and
also make it easier to perform unit testing. But, on the other
hand, the classes in the application must interact with each
other. How can these two mutually exclusive requirements
be reconciled? For this purpose, Spring suggests using
the Dependency Injection (DI) pattern, which is a variation
of the Inversion of Control (IoC) concept. IoC containers
are the central part of Spring.
These containers control all aspects of the life cycle of
objects: their creation, configuration, establishment of con-
nections between them. Containers perform all their actions
based on a script written either in XML format, or using Java
annotations, or in Java code.
In Spring, there are two types of containers: BeanFac-
tory and ApplicationContext. The BeanFactory container
is simpler and offers the basic steps necessary to perform
the DI. It is recommended to use it in the simplest appli-
cations. The ApplicationContext container includes all
the features of BeanFactory and, in addition, can still be
used in Java EE applications. It should be used if you create
a web application.
You are already familiar with the concept of Java bean.
This is a set of formal requirements for the declaration of
the Java class, the implementation of which makes this class
“correct” from the standpoint of Java, namely — turns a class
into a component that can be used multiple times in various
libraries and APIs. Using Java bean increases the efficiency of
using the class. If you forget the set of formal requirements for
Java bean, repeat them again. In order for a class to become
a Java bean, it must:

27
Lesson 6

■■ have a public constructor without parameters;


■■ be serializable;
■■ contain setters and getters for their properties.
Sometimes it is still required that the class contain methods
equals(), hashCode(), and toString().
Why do we now remember about Java bean? Because
Spring requires all application classes to be Java bean. In this
case, the IoC container takes full control of the life cycle of
the objects in your application. You must specifically describe
your requirements for the process of creating and using ob-
jects of each class, and then Spring, based on these metadata,
will control your objects. As we mentioned above, metadata
is described either in XML format, or using Java annotations,
or in Java code.
Now let’s summarize all this information together by
considering an example of creating a Java application using
Spring. In this app, the emphasis will be on using IoC contain-
ers to demonstrate how Spring works with classes. First, we
create an application that consists of one single class Student,
create several objects of this class and display their descrip-
tion. Then add another class to the application — Group,
create two groups of students and display their description.
The main purpose of this application is to show how Spring
works with classes.
The first Spring application
In NetBeans, create a new project with a name, for example,
Spring1. When the project is created, select it in the wizard
window and activate the Properties command. In the right

28
Frameworks and Libraries

Figure 15. Adding Spring

Figure 16. Adding a Spring configuration file

29
Lesson 6

part of the window that appears, select the Libraries option,


and then click the Add Library... button on the right. In
the window that appears, select the Spring Framework of
the latest version (Fig.15).
In our first Spring application, we will describe our classes
in a special configuration XML file. It should be located in
the src project folder, so to add it, select the SourcePackages
node, activate the context menu and click on the New – Other
option (Fig.16).
In the window that appears, choose Other – Spring­
XMLConfig(->):

Figure 17. Adding a Spring configuration file


Select the name for the configuration file to be added
and click Finish without any other options. Select the added
file — and you’ll see the blank of the XML file with the beans
root element:

30
Frameworks and Libraries

Figure 18. Spring configuration file


In this file, you need to describe the classes from which
we want to create the application. Let’s first give the Student
class code, and then describe this class in the configuration
file. Create a package called myclass in the project and add
the following class to it:

public class Student implements Serializable


{
private String name;
private double rate;

public Student() {
}
@Override
public String toString() {
return "Student{" + "name=" + name + ",
rate=" + rate + '}';
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getRate() {


return rate;

31
Lesson 6

public void setRate(double rate) {


this.rate = rate;
}
}

Note that the class is designed as a Java bean — this is


a prerequisite for using Spring. The Student class is very sim-
ple, it contains two fields and everything necessary for their
support. Now let’s see how this class should be described in
the configuration file.
Each class of the application should be described in the con-
figuration file by the bean pair element. In this element, you
must specify the id attribute and give it a unique value. Usually
this is the class name, but with a small letter:

<bean id="student">
</bean>

Then, using the class attribute, you need to specify which


class corresponds to this bean. When specifying a class name,
you must specify the name of the package in which the class
is defined:

<bean id="student" class="myclass.Student">


</bean>

Next, you need to specify a scope attribute that deter-


mines how Spring behaves whenever you create a bean named
student. The scope attribute has five values, the last three of
which are used only in web applications:

32
Frameworks and Libraries

scope="singleton" only one object of such a bean


will be created, and at each
attempt to create a new object
this object will be returned;
scope="prototype" at each attempt to create a new
object, a new object will be
created;
scope="request" indicates that the bean exists
only within the request;
scope="session" indicates that the bean exists
within the session;
scope="global-session" indicates that the bean exists
within the global session.

We plan to create many objects of the Student class, so


add the attribute scope with the prototype value:
<bean id="student" class="myclass.Student"
scope="prototype">
</bean>

In the bean element, you can describe the fields of a class


and assign them default values. A full description of our class
might look like this:
<bean id="student" class = "myclass.Student"
scope="prototype">
<property name="name" value="No Name"></property>
<property name="rate" value="0"></property>
</bean>

In this description, everything should be clear to you. Add


it to our configuration file.
Now let’s move on to the main() method in the main class
of our application and add the following code:

33
Lesson 6

public static void main(String[] args) {


ApplicationContext context = new
ClassPathXmlApplicationContext(
"MySpringXMLConfig.xml");
Student s1 = (Student) context.getBean("student");
s1.setName("Robert");
s1.setRate(145.5);
System.out.println(s1);
Student s2 = context.getBean(Student.class);
System.out.println(s2);
}

First, the application context is created — based on the con-


figuration file, in which all its classes are described. In our
application, only one Student class is described. In the future,
to create an object of some class, you will need to access this
context and call the getBean() method, passing it the bean
string identifier (value of the id attribute) as a parameter whose
object is to be created:
Student s1 = (Student) context.getBean("student");

Run our application, and you will see the following output
in the console window:

Student{name=Robert, rate=145.5}
Student{name=No Name, rate=0.0}

The second Spring application


Now we will finish our application. You can create a copy
of our Spring1 project, name the created project as Spring2
and continue working with the new project. Or you can make

34
Frameworks and Libraries

changes to the Spring1 project. Add another class to the project


and see how to describe file several classes and the relationship
between them in the configuration.
In the myclass package, which already has the Student
class, add the Group class:

public class Group implements Serializable


{
private String name;
private List<Student> students;

public Group()
{
this.students=new ArrayList<>();
this.name="noname";
}

public void addStudent(Student s)


{
this.students.add(s);
}

public void removeStudent(Student s)


{
this.students.remove(s);
}

public int getGroupSize()


{
return this.students.size();
}

public String getName()


{
return name;
}

35
Lesson 6

public void setName(String name)


{
this.name = name;
}

public List<Student> getStudents()


{
return students;
}

public void setStudents(List<Student> students)


{
this.students = students;
}

@Override
public String toString()
{
String str="";
str+="Group:\t"+name+"\n\n";
for (Student s:students)
{
str+=s+"\n";
}
str+="\n\n";
return str;
}
}

Note that the Group class is also designed as a Java bean,


and it has a field of List<Student> type. Now we need to add
a description of the new class to the configuration XML file.
Look at the properties of the Group class:

<bean id="student" class= "myclass.Student"


scope="prototype">

36
Frameworks and Libraries

<property name="name" value="No Name"></property>


<property name="rate" value="0"></property>
</bean>

<bean id="group" class="myclass.Group" scope="prototype">


<property name="students" >
<list></list>
</property>
<property name="name" value="No Name"></property>
</bean>

Finally, we bring the code of the main() method to this


form:

ApplicationContext context = new


ClassPathXmlApplicationContext(
"MySpringXMLConfig.xml");
Group g=(Group)context.getBean("group");
g.setName("SP2824");
Student s=null;
Random r=new Random();
String j;

for (int i = 0; i < 10; i++)


{
s=(Student)context.getBean("student");
j=String.valueOf((i+1));
s.setName("Student "+j);
s.setRate(r.nextInt(100));
g.addStudent(s);
}
System.out.println(g);

We create a group named “SP2824”, add ten students ran-


domly to it and display the description of the created group in

37
Lesson 6

the console window. My output of the application has turned


out as follows:

Group: SP2824

Student{name=Student1, rate=4.0}
Student{name=Student2, rate=67.0}
Student{name=Student3, rate=24.0}
Student{name=Student4, rate=47.0}
Student{name=Student5, rate=58.0}
Student{name=Student6, rate=51.0}
Student{name=Student7, rate=53.0}
Student{name=Student8, rate=27.0}
Student{name=Student9, rate=98.0}
Student{name=Student10, rate=1.0}

As you can see, one needs to follow the example of Stu-


dent9, and the rest have to work much harder.
These two simple examples allow you to understand how
Spring works with classes. For other aspects of using Spring,
please refer to the developer’s website: https://spring.io/guides.

Hibernate
Hibernate is a very useful tool for working with databas-
es. However, this is not only a means of access to databases
and a tool for performing queries. Hibernate is also an ORM
(Object Relational Mapping) system. What does it mean? Let’s
take a little digression to talk a little more about ORM.
Today, most applications are created in the OOP style.
In this case, the entities with which the application works are
described by classes. At the same time, databases are most
often used to store application data. In the overwhelming

38
Frameworks and Libraries

majority of cases, these are relational databases that store


information in linked tables. And here some problems arise,
due to the fact that at the time of the creation of relational
databases, the concept of OOP did not yet exist. Therefore,
such databases do not support the principles of OOP, which
would be very desirable for application developers. To elim-
inate this problem, the ORM systems appeared.
The main principle of such systems is that they create
a one-to-one correspondence between application classes and
tables in databases. Such a correspondence can be considered
as follows. A table is created for each application class in the da-
tabase. The fields in this table correspond to the properties of
the class by names and data types. Each object of such a class
can be turned into one string in the corresponding table.
And any string of such a table can be turned into an object of
the corresponding class. Generally speaking, this explanation
is rather rude. The fact is that most often one class is represent-
ed in the database not by one table, but by a group of related
tables. And the entity, with which the application works, can
be described not by one class, but several, which are referred
to as the “object model”. Therefore, it is necessary to speak
not about the ‘class-table’ correspondence, but, rather, about
the ‘object model — a group of related tables’ correspondence.
There are other problems that are solved using ORM systems.
For example, what about inheritance? How to display classes
associated with inheritance in the database? How to determine
the “identity” of objects? In the database, the identity is de-
termined by the coincidence of the primary key, and in OOP
there is the concept of identical objects (a==b) and matching
objects (a.equals(b)). How to establish the correspondence

39
Lesson 6

between data types of DBMS and Java? If you think about it,
you will agree that there are many such problems with such
a correspondence.
So, Hibernate is an ORM system that solves all such prob-
lems and includes also the means of access to and work with
the database. The main characteristics of Hibernate are:
■■ it is an open source system;
■■ it is a very fast system, largely due to the efficient use of
caching;
■■ it includes the HQL (Hibernate Query Language) — OOP
version of the SQL language, which allows you to write
database queries that are independent of a particular da-
tabase server;
■■ it allows creating tables in the database automatically;
■■ it simplifies the work with multi-table queries;
■■ it allows working with almost all known database servers;
Functionally, Hibernate includes components such as API
for performing CRUD operations on class objects, APIs for
configuring the correspondence between classes and tables,
and some others.
You can download Hibernate from the developer’s page
http://hibernate.org/orm/downloads/.
You can view how to use Hibernate at https://netbeans.
org/kb/docs/web/hibernate-webapp.html.
Later in this lesson, after we get acquainted with the use
of databases, we will create an application with Hibernate.

40
The Concept of a Servlet

The Concept of a Servlet


A servlet is an application running on a web server or,
more often, on an application server (Tomcat, GlassFish, etc.).
The servlet is located between the client and server parts of
the application and is designed to process client requests. By
processing client requests, the servlet can access the database,
the Web services, or form the Response itself.
By their nature, servlets are Java classes that inherit
the HttpServlet class. Implementation of these classes is based
on the packages javax.servlet and javax.servlet.http, which are
part of the Java EE. The servlet class defines the methods that
control its lifecycle. These are methods such as:
■■ init() is called once and initializes the servlet. The servlet
is usually created when the client accesses the Url corre-
sponding to the servlet. However, you can also make it so
that the servlet is initialized immediately when the server
is started;
■■ service() is called whenever the servlet receives a client
request. This is the main servlet method. It runs the work
for which the servlet was created. Each time a new request
is received from the client, the server calls the service()
method in the new thread, then the method itself checks
which HTTP method the request came from (GET, POST,
DELETE, PUT), and calls the corresponding doGet(), do-
Post(), DoDelete() method, and so on. Note that the service()
method is called by the container with the servlet, and
the programmer does not need to call it himself. The task

41
Lesson 6

of the programmer is to override the methods doGet(),


doPost(), doDelete(), etc.;
■■ destroy() is called only once and terminates the servlet,
after which the servlet is removed by the garbage collec-
tor. In this method, you need to perform such actions
as disconnecting from the database servers, terminating
daemon threads, saving cookies, etc.
After this initial information, let’s look at some examples of
using servlets. To work with them, you must have an installed
Java EE platform and some application server. At the moment,
both conditions are fulfilled: Java EE and Tomcat are installed.
So let’s move on to creating a new application.
Start NetBeans and create a new project using the Java
Web template:

Figure 19. Creating a web application

42
The Concept of a Servlet

Name the project, for example, as MyServlet1, and go to


the next window, where you will be asked to select a server
for hosting the application being created. Select the Apache
Tomcat option:

Figure 20. Server Selection


In the root folder of the created application, you will see
the index.html file, this is the login page of the created appli-
cation. Markup the body element of this file as follows:

<body>
<h1>Hello World!</h1>
<form action="GreetingServlet" method="POST">
Login: <input type="text" name="login"
size="20"> <br/>
Password:&nbsp;
<input type="password" name="pass" size="20">

43
Lesson 6

<br /><br />


<input type="submit" value="Submit">
</form>
</body>

We created a simple form for entering a name and password.


The query data processor that will be created when the submit
button is clicked in this form will be a servlet.
To add a servlet to the project, you can do this. Select
the Source Packages node in the project, right-click, then —
New, then — Servlet:

Figure 21. Adding a Servlet


For the name of the servlet, type GreetingServlet. You will
see a template for the servlet class derived from the Http­Servlet.
In this class, we will be interested in the ­processRequest()

44
The Concept of a Servlet

method with two parameters — HttpServletRequest and


HttpServletResponse. The first parameter contains the in-
coming request from the client. In the second, you record
the generated response to the received request. Bring this
method to this form:

protected void processRequest(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html;
charset=UTF-8");
PrintWriter out = response.getWriter();
String login = request.getParameter("login").
toString();
String pass = request.getParameter("pass").
toString();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet GreetingServlet
</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet GreetingServlet at" +
request.getContextPath () + "</h1>");
out.println("<p>Welcome, " + login + ",
your pass is " + pass + "</p>");
out.println("</body>");
out.println("</html>");
out.close();
}

In this method, very simple actions are performed. First


we set the required encoding and associate the output thread
with the response object to be able to write the markup in
the response that the client will receive as the result of pro-
45
Lesson 6

cessing the form. Then, from the request object, using the get-
Parameter() method, we name the controls to get the values​​
entered in the form. Next is the formation of markup for
the page returned to the client.
Run the application and the form will open in the browser.
Enter some data into it and click submit. This will create a re-
quest that will be sent to our servlet. There it will be processed
by the processRequest() method and returns the response
page. It looks so in my case:

Figure 22. Activating a Servlet


Let’s talk about what you saw in this example. You saw
a typical web application with the client part in the browser
and with the request generation using the form. The request
handler is a specific Java class — the GreetingServlet. It is
the servlet that received the request from our form, generat-
ed a reponse for this request, and sent it back to the client’s
browser. All the logic in the servlet was executed in the process­
Request() method. Perhaps you have a question: why did not
we describe this method among other servlet methods (init(),
service(), destroy())? The fact is that the processRequest()
method is not part of the servlet class. This method is added
by the NetBeans environment and is a convenient place to
perform request handling.
Let’s do one more example to get familiar with servlets. This
time the application will be more interesting and complicated.

46
The Concept of a Servlet

It will offer clients to upload images to the server. Images will


be accumulated in a special folder named images. This will all
be done in one servlet. Then a second servlet will be created,
which will allow clients to select any of the downloaded images
in the drop-down list and view it in the browser.
Create a new web application in NetBeans, as we did in
the previous example. I have this application called Servlet­
Images. Open the index.html file and paste the following
markup into it:

<h2>Select files for upload</h2>


<form method="POST" action="Servlet1"
enctype="multipart/form-data" >
<input type="file" name="file" multiple="multiple"/>
<input type="submit" value="Upload Images"/>
</form>
<hr/>
<br/>
<h2>Go to view page</h2>
<form method="POST" action="Servlet2">
<input type="submit" value="View Page"
name="showImages"/>
</form>

On the main page of the application, we create two forms.


One is designed to perform multiple file uploads. This is in-
dicated by the enctype attribute of the form, and the multiple
attribute of the input element. The handler for this form is
Servlet1. The second is for calling the second servlet named
Servlet2. In turn, Servlet2 creates a page on which it displays
a form with a select element with all the images in the images
folder, and displays an image selected by the user in the select
element.

47
Lesson 6

Now add two servlets with the names Servlet1 and Servlet2
to the application. Consider their contents. You should
already have noticed that the @WebServlet annotation with
the attributes name and urlPattern is automatically inserted
before the declaration of the servlet class. The same annotation
will be in our case, but, in addition to it, we need to add
one more annotation, which provides multifile unloading.
Annotations before our first servlet should be as follows:

@WebServlet(name = "Servlet1",
urlPatterns ={"/Servlet1"})

@MultipartConfig (
fileSizeThreshold = 1024*1024*2,
maxFileSize = 1024*1024*10,
maxRequestSize = 1024*1024*50
)

public class Servlet1 extends HttpServlet


{
}

Now let’s look at the code inside the servlet. We need


to determine the path to the folder where we plan to collect
the pictures, so at the very beginning of the class, add a line
that declares the SAVEDIR constant with the path to the folder:
public final static String SAVEDIR="Images";

Such a path declaration will cause the Images folder to be


created in the project at the build/web/Images path.
This time, we will not process the client requests in
the process­Request() method, as in the previous example. We

48
The Concept of a Servlet

will look at the use of the doPost() method, which more closely
matches the logic of our application, because the form sends
a request using the POST method. However, in the process­
Request() method, we still add one line that will redirect
the client back to the main application page after the doPost()
method is executed. We add this line at the beginning of
the method:
protected void processRequest(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
response.sendRedirect("index.html"); //added line
// rest of the default code
}

We do not change anything in this method. Let’s move


on to the doPost() method. Since our form forwards the re-
quest via the HTTP POST method, it will fall on the doPost()
method. You should not have confusion with the two words
“method” in the previous sentence. The first occurrence of
the word “method” means “the data transfer method that is
standardized in the HTTP protocol”, and the second is “the
doPost() method of the Servlet1 class”. Add the following code
to the doPost() method:

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException
{
if(request.getParts().size()>0)
{

49
Lesson 6

this.doUploud(request);
}
processRequest(request, response);
}

We check to see if the client has selected any files for


upload. If so, we call some doUpload()method, in which
we process the upload. Then, regardless of whether it was
unloaded or not, we send a request for further processing to
the processRequest() method. DoUpload() is our method in
which processing is performed. It can look like this:
private void doUploud(HttpServletRequest request)
{
String root=request.getServletContext().
getRealPath("");
String savePath=root+File.separator+Servlet1.SAVEDIR;
File dir=new File(savePath);

if(!dir.exists())
dir.mkdir();
String fn="";
InputStream in=null;
BufferedImage img=null;
FileOutputStream fos=null;

try
{
for(Part p : request.getParts())
{
fn=p.getSubmittedFileName();
in=p.getInputStream();
byte [] b=new byte[in.available()];
in.read(b);
fos = new FileOutputStream(savePath+File.

50
The Concept of a Servlet

separator+fn);
fos.write(b);
fos.close();
}

} catch (IOException ex)


{
Logger.getLogger(Servlet1.class.getName()).
log(Level.SEVERE, null, ex);

} catch (ServletException ex)


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

Actions are simple and understandable in this method:


■■ construct the path to the Images folder;
■■ create a folder if it is not already created;
■■ prepare the threads for recording binary content;
■■ loop through the files sent in the request, and save them
in the Images folder.
That’s all the actions that are performed in the first servlet.
We now turn to the second.
In this servlet, processing will again be performed in
the processRequest() method. Here, a form with a select
element will be created, filled with information about our
images from the Images folder, and the client selection will be
processed here. Processing reduces to creating an img element
for the selected image.
Give the method processRequest() in Servlet2 to this form:

51
Lesson 6

protected void processRequest(HttpServletRequest


request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

/* TODO output your page here. You may use


following sample code.
*/
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Servlet2</title>");
out.println("</head>");
out.println("<body>");

//
String btn1=request.getParameter("showImages");
String select=request.getParameter("lImages");

if( (btn1!=null && btn1.equals("View Page")) ||


select!=null)
{
String root=request.getServletContext().
getRealPath("");
tring savePath=root+File.separator+Servlet1.
SAVEDIR;
File dir=new File(savePath);
File f=null;
out.println("<h2>Select image to view</h2>");
out.println("<form method='POST'
action='Servlet2' >");
out.println("<select name='lImages'>");
for(String fname:dir.list())
{

52
The Concept of a Servlet

f=new File(savePath+File.separator+fname);
if(!f.isFile())
continue;
out.println("<option>"+fname+"</option>");
}
out.println("</select>");
out.println("<input type='submit'
value='Show image'/>");
out.println("</form>");

if(select!=null)
{
Path path = Paths.get(savePath+File.
separator+select);
byte[] data = Files.readAllBytes(path);

StringBuilder sb = new StringBuilder();


sb.append("data:image/png;base64,");
sb.append(new String(Base64.getEncoder().
encode(data)));
out.println("<img src='"+sb.toString()+"'/>");
}
}
//
out.println("<h4>The image is presented by
Servlet2 at " + request.getContextPath() +
"</h4>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}

You see a form handler that displays the file selected in


the select element. All actions in this code are understandable
to you. Run this application, download several pictures. Make

53
Lesson 6

sure that the Images folder is created and the selected images
are in it. Select a graphic file to view. My result looks like this:

Figure 23. Activating the servlet


This example more fully reveals the servlet’s capabilities.
You see certain user-defined logic created using two classes of
servlets, using different methods, redirecting, working with
folders, displaying binary content. Servlets have no functional
limitations, they can work with databases, with web services
and other components. Servlets are very widely used in Java
web applications.

54
Data sources

Data sources
JDBC
Generally speaking, the data source need not be a da-
tabase for sure. This can be a file and a collection. But it is
the databases that have become the standard data source.
To work with databases in Java SE, the java.sql package is
included, and contains the JDBC (Java DataBase Connecti-
vity) component. JDBC is based on the concept of a driver.
To connect to a particular database, you must dynamically
load the appropriate driver and pass it an analog of the con-
nection string, which in Java is called a URL. The main
role in JDBC is played by such interfaces as Connection,
Statement, PreparedStatement, CallableStatement and Re-
sultSet. The driver of each particular database implements
these interfaces as it needs.
The algorithm for working with the database looks like this:
■■ registration of the driver for a particular database server;
■■ connection to the database server (Connection);
■■ creating and executing a database query (Statement or
PreparedStatement);
■■ retrieving the result of the executed query (ResultSet).
Downloading and initialization of the driver occurs when
the string of code is executed:
Class.forName(driver);

Here, driver is a special driver string descriptor.

55
Lesson 6

The connection to the database server looks like this:

Connection connection =
DriverManager.getConnection(driverUrl);

Here, driverUrl is a string of a special type unique for


each database server.
Further actions are specific to specific queries that are
executed.
Working with JDBC practically closes the implementa-
tion of a particular database from the user. In other words,
the code that uses JDBC depends very little on the speci-
ficity of the database. In the case of a database change, very
few edits will need to be made Java code, and maybe you
will not need to do them at all, except for a few strings of
connecting the driver.
Consider an example of using a database. Let’s write an
application that will connect to MySQL and demonstrate
the execution of the basic actions with the database. You
should already have an instance of MySQL and PhpMyAdmin
installed. Run PhpMyAdmin and create a database named
jtest. Then start NetBeans and create a new console project.
My project will be called TryJDBC.
Since we will work with the MySQL server, we need to
add a JDBC driver to the application to work with this server.
You can download this driver from https://www.mysql.com/
products/connector/. Go to this page and activate the high-
lighted link (Fig. 24).
On the next page, select the distribution that corresponds
to your platform (Fig. 25).

56
Data sources

Figure 24. Downloading the MySQL driver

Figure 25. Selecting the MySQL driver distribution

Finally, on the next download page, click the link below,


which allows you to download the selected distribution with-
out registration (Fig. 26).
Unzip the downloaded archive into a folder on your disc.
Now you can add the downloaded driver to the newly creat-
ed project. Remember, this should be done for each project
in which you want to work with JDBC. Select the project
in the wizard window, activate its properties and select the

57
Lesson 6

Figure 26. Finishing the MySQL driver download

libraries option in the left part of the window. In the right part
of the next window click Add JAR/Folder, go to the folder
where you unpacked the downloaded driver, select the mysql-
connector-java-5.1.42-bin.jar file and click OK. Perhaps you
download another version of the driver, then the file name
will be different from the one given (Fig. 27).

Figure 27. Adding a MySQL JDBC driver to a project

58
Data sources

Now we can proceed to writing the code. Our applica-


tion will connect to the jtest database created, create a table
in it, add several entries to it, and then display the data from
the table in the console window.
We put the work from the database into a separate class. In
this class, we will create methods for executing a connection
to the database and a method for executing select queries.
Queries that do not return data from the database will be
executed in a different way, outside of this class. When creating
an object of this class, we will pass data identifying the address
of the server, the user, and the name of the particular database
to the constructor. Add the following class to the project:

public class DbManager {


private String host; //server address
private String user; //user name
private String pass; //user password
private String dbName; //DB name
private Connection conn; //connection object
public DbManager(String host, String user,
String pass, String dbName)
{
this.conn=null;
this.host=host;
this.user=user;
this.pass=pass;
this.dbName=dbName;

try
{
//driver registration
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex)
{

59
Lesson 6

Logger.getLogger(DbManager.class.getName()).
log(Level.SEVERE, null, ex);
}
}

public Connection connect()


{
String url="jdbc:mysql:
//"+this.host+"/"+this.dbName+
"?useUnicode=true&characterEncoding=
utf-8";
try
{
this.conn=DriverManager.
getConnection(url,this.user,this.pass);
return this.conn;
} catch (SQLException ex)
{
Logger.getLogger(DbManager.class.getName()).
log(Level.SEVERE, null, ex);
return null;
}
}

public ResultSet getSelectQuery(String sql,


Connection conn)
{
Statement comm = null;
ResultSet set = null;
try
{
comm = (Statement) conn.createStatement();
set = comm.executeQuery(sql);
}
catch (SQLException ex)
{

60
Data sources

Logger.getLogger(DbManager.class.getName()).
log(Level.SEVERE, null, ex);
}
return set;
}
}

The class constructor loads the MySQL driver. To download


the driver for MySQL, a string with the name of the driver of
the form: “com.mysql.jdbc.Driver” must be passed as a pa-
rameter to the method Class.forName(). This is a predefined
string. To connect to other databases, it will be different. For
example:
■■ for MS SQL Server — “com.microsoft.jdbc.sqlserver.SQL
ServerDriver”
■■ for Oracle — “oracle.jdbc.driver.OracleDriver”
■■ for PostgreSQL — “postgresql.Driver”.
You can always find out what the name of the JDBC driver
should look like on the developer’s site of the required DBMS.
The connect() method connects to the database specified
in the url string. Note that the format of the url string is also
strictly fixed and unique for each server. For MySQL, the format
of this string should be:

"jdbc:mysql://host/dbName?useUnicode=
true&characterEncoding=utf-8"

where:
■■ host — server address;
■■ DbName — database name;

61
Lesson 6

Further in this method the Connection object is initial-


ized, through which then database requests will be executed.
Now let’s move on to the main() method and insert the code
snippets there, explaining their work, where necessary. Add
the following two strings:

DbManager db = new DbManager("localhost:3307",


"root", "123456", "jtest");
Connection conn = db.connect();

We create an object of DbManager class, specifying


the data necessary for connection to our database. Then we
call the ­connect() method of the DbManager class we created
to get a ­Connection object. This is one of the central types
when working with databases. Having created this object, we
can use it (by calling the createStatement() method) to create
an object of Statement type. And the latter will allow us to
execute query to the database server.
Statement statement1 = conn.createStatement();

The Statement object has an execute() method that takes


a string with an SQL query and executes this query. We ex-
ecute a query that creates a Student table with the id, name
and rate fields. In order for the query not to be executed every
time the application was launched, we included the phrase “if
not exists” in it.

statement1.execute("create table if not exists


Student(" + "id integer primary
key auto_increment, " + "name
varchar(100), " + "rate double);");

62
Data sources

At this point you can start the application, and if you


typed the code without errors, the application will execute
successfully, and the Student table will be created in the da-
tabase. Make sure the table is created.
Now let’s look at the execution of insert queries to add
several entries to the created table. This can be done like this:

String s1_name="Corwin of Amber";


double s1_rate=190;
String ins1="insert into Student(name, rate)
values('"+s1_name+"',"+s1_rate+")";
statement.execute(ins1);

We prepare the variables with the required data, insert


this data into the query string, and then execute the query
again using the execute() method, as when creating the table.
This way of doing an insert will work, but you should not
use it. First, to embed data into the body of the query, to
follow the quotation marks is the routine work. Secondly,
data from variables are not checked at all, which is a gap
for SQL injection.
It is more preferable to use the PreparedStatement type,
which allows creating parametrized queries, in which instead
of parameters it is possible to specify placeholders, and then
to connect the required data with each placeholder.
The object is created by calling prepareStatement() on
behalf of the same Connection object. As a parameter to
the prepareStatement() method, you must pass a query string,
in which instead of each input value you can specify a place-
holder “?”. Then, taking into account the value type, by calling
the setBoolean(), setString(), setDouble(), setInt() and other

63
Lesson 6

similar methods, you need to bind the value for each place-
holder, specifying the placeholder number (starting with 1)
as the first parameter.

String s2_name="Han Solo";


double s2_rate=180;
PreparedStatement statement2 = conn.prepareStatement
("insert into Student(name,rate) values(?,?)");
statement2.setString(1, s2_name); //first value is of
//type String
statement2.setDouble(2, s2_rate); //second value is
//of type Double
statement2.executeUpdate();

You may wonder what PreparedStatement is different


from Statement. There are differences and they are significant:
■■ PreparedStatement runs much faster than Statement, be-
cause such queries are compiled;
■■ The data for the Statement is static, while for Prepared-
Statement they can be added dynamically;
■■ PreparedStatement automatically performs SQL injection
protection;
■■ queries that use PreparedStatement look much simpler.
Therefore, it is recommended that you always use
­PreparedStatement.
If you execute now our application, you will find insert-
ed strings in the table. To ensure that these strings are not
added every time the application is started, comment out
the calls to the execute() method that perform insert queries.
Now we are faced with the task of reading the data from
the table and outputting them to the console window. For

64
Data sources

this we will work with the ResultSet type. This is the analog
of SqlDataReader in ADO.NET. ResultSet should be used
when executing SQL select queries. The data returned by
the select query is inserted into the ResultSet type, where
they can then be retrieved in a loop. Note the getString(),
getDouble() and other similar methods, which allow you
to retrieve the read data according to their type. We pass
the string field names from the table to these methods, but
we could specify the sequence numbers of the required fields
(the numbering starts with 1):

String sel="select * from Student";


ResultSet set=db.getSelectQuery(sel, conn);
while(set.next()){
System.out.println(set.getInt("id")+" "+
set.getString("name")+" "+
set.getDouble("rate"));
}

Add this code and run the application. My output was as


follows:
1 Corwin of Amber 190.0
2 Han Solo 180.0

As you can see, the data from our form is read and dis-
played in the console window. Note the finally block, in which
the created connection is closed.
To get to know JDBC, this example is enough. Next in
the lesson, we’ll look at some examples of using JDBC, but
already in a web application. Leave the created jtest database,
we will work with it.

65
Lesson 6

Example of using Hibernate


Now we can consider an example of using Hibernate.
In this example, consider the connection to the database,
setting the ORM mapping between the database table and
the class in the application, and implement the addition
of data to the table. To create a user interface, we use one
more important component of Java EE — Java Server
Faces (JSF).
JSF is an MVC web framework designed to create a user
interface in web applications. This framework provides the user
with a set of convenient, reusable components for a web page.
JSF creates a connection between such components (which
are often called widgets) with data sources, on the one hand,
and server-side events on the other. JSF greatly simplifies

Figure 28. Creating a web application with Hibernate

66
Data sources

the development of the user interface and is widely used in


modern web applications.
Create a new web application in Netbeans called My­Hibernate.
Select Tomcat as the server (although you can select another
application server, for example, GlassFish). In the next window,
after selecting the server, check the Java Server Faces and Hibernate
options, and in the Database Connection field, select the New
Database Connection option a bit lower (Fig. 28).
In the next window, click the Add button and add the JDBC
driver for MySQL to the project. In this application we will
work with the database jtest, created earlier in this lesson.

Figure 29. Adding a JDBC driver


After selecting the driver, click Next and go to the next
window, and specify there all the necessary data to connect to
the jtest database. Pay attention to the correctness of the port

67
Lesson 6

number for accessing the database, the user name and pass-
word for accessing the server. After you specify all the data, it
is useful to click the Test Connection button and test the con-
nection that was created.

Figure 30. Creating a connection to the database


After filling this window, you can click Next, Next and
Finish. Note that when you move on to the next step in cre-
ating an application, Netbeans may lag. This is normal. You
just have to wait a little, so that all the necessary components
are found and loaded into the project. If Netbeans reports
a problem due to the lack of a JDBC driver, click the Resolve
button and specify the path to the mysql-connector-java-
5.1.42-bin.jar file again.
When the project is created, Netbeans will open its con-
figuration file with the name hibernate.cfg.xml. Remember,

68
Data sources

this file must be located in the src folder of the created proj-
ect, so do not transfer it to any packages. And you do not
need to rename it. The file now describes the connection
to the database in accordance with the data specified when
creating the project:

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3307/
jtest?zeroDateTimeBehavior=
convertToNull
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
******
</property>
</session-factory>
</hibernate-configuration>

We will not change anything in this file, so you can just


close it.
Run the created project template, and you will see the wel-
come phrase Hello from Facelets in the browser. This phrase is
displayed by JSF by deafult. To see the origin of this greeting,
open the index.xhtml file located in the Web Pages project

69
Lesson 6

node. This is the start page for the server side of the application.
It is an xml file that hosts HTML markup represented by JSF
tags. These tags are defined in the namespace with the prefix h.
In this file we will create a form for our application, but
it will be a little later.
Create a new package in the project, for example, with
the name myclasses, in which we will need to create our own
classes. Select the created package, select the options New —
Other — Hibernate — HibernateUtil.java:

Figure 31. Creating HibernateUtil.java


When you add this class, you can give it an arbitrary name.
Usually it is called HibernateUtil.java. After adding, open this
class and make sure that the AnnotationConfiguration type and
the buildSessionFactory() method are not striked throught in
the code given. Striking through indicates that these tools are
already out of date, and your Netbeans still works according
to the old scheme. There is nothing to worry about. Just bring
the class code HibernateUtil.java to this form:

70
Data sources

package myclasses;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.
StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {


private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {

if (sessionFactory == null) {
// loads configuration and mappings
Configuration configuration =
new Configuration().configure();
ServiceRegistry serviceRegistry =
new StandardServiceRegistryBuilder().
applySettings(configuration.
getProperties()).build();
//builds a session factory from the service
//registry
sessionFactory = configuration.
buildSessionFactory(serviceRegistry);
}
return sessionFactory;//return sessionFactory;
}
}

The task of this class is to create a SessionFactory object.


This object is created based on the configuration file hibernate.
cfg.xml and is intended for servicing communication between
the client and the server.
In the jtest database to which we connected in this proj-
ect, there is a single Student table with the id, name and rate
fields. To create an object-relational mapping (ORM) between

71
Lesson 6

our application and the jtest database, we will create a class


corresponding to the Student table in the application.
Again, select the myclasses package in the project and add
the Student class to it. In this class, you need to create fields
that match the type and names with the fields of the Student
table. Do not forget to formalize the class as a Java bean. Bring
the added class to this form:

public class Student {


private int id;
private String name;
private double rate;

public Student(String name, double rate){


this.name=name;
this.rate=rate;
}

public Student(){
this.name="";
this.rate=0;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

72
Data sources

public double getRate() {


return rate;
}

public void setRate(double rate) {


this.rate = rate;
}
}

Now we need to explain to Hibernate that it should link


the Student DB table with the created Student class. To do this,
we will create a special xml-file in the same package. Again,
select the myclasses package and select the options New –
Other – Hibernate – Hibernate Mapping Wizard:

Figure 32. Selecting the Hibernate Mapping Wizard


Specify the name for the student.hbm (hbm — Hiber-
nate mapping) file to be created, and go to the next win-
dow, indicating that you want to establish a link between

73
Lesson 6

our Student class and the Student table. Be careful when


entering the class name. If other downloaded Netbeans
projects have classes named Student, you will see them
in this window. Therefore, select the class Student from
the current project.

Figure 33. Running the Hibernate Mapping Wizard


Open the created file student.hbm.xml and bring its mark-
up to this form:

<hibernate-mapping>
<class catalog="jtest" name="myclasses.Student"
table="student">
<id column="id" name="id" type="java.lang.Integer">
<generator class="identity"/>
</id>
<property column="name" name="name" type="string"/>
<property column="rate" name="rate" type="double"/>
</class>
</hibernate-mapping>

74
Data sources

The description is quite simple. We specify the class de-


scription in the paired element class. Note that the class name
is specified with the package name. Then inside, we describe
the primary key id and, in the property elements, describe
the properties of our class.
Now look again at the configuration file hibernate.cfg.
xml and make sure that you added one more string with
the mapping element, which indicates the correspondence
that we created:
<mapping resource="myclasses/student.hbm.xml"/>

At this stage, you can say that all the settings are done and
we can proceed to programming. Now we will create a class
that will describe the interaction of application classes with
the database. This class should also be designed as a Java bean.
Its name can be arbitrary. In our case, let’s call it StudentDb.
Bring the code of this class to this form:

import javax.faces.bean.ManagedBean;
import myclasses.Student;
import javax.faces.bean.SessionScoped;
import org.hibernate.Session;

@ManagedBean
@SessionScoped

public class StudentDb {


private Student s;
private HibernateUtil helper;
private Session session;
private int id;
private String name;
private double rate;

75
Lesson 6

public StudentDb(){}

public void addStudent(){


if(this.name != ""){
s.setName(this.name);
s.setRate(this.rate);
session = helper.getSessionFactory().
openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
}
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getRate() {


return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
}

76
Data sources

This class is decorated with mandatory annotations. Be


careful when importing packages for these annotations and for
the Session object, because there are types with the same names,
but described in other packages. In this class, the addStudent()
method has special significance for us. It will be the form
handler, which we will now create on the main page. In this
method, a connection to the database via the Session object
occurs, then a Student object is created, which is initialized
with values ​​taken from the form, and stored in the database.
Please note that work with the database is in the form of
a transaction.
Now we need to add the form to the index.xhtml file. Open
it and add such a markup to the <h:body> element:

<h:body>
<h:outputLabel value="Add new student"/>
<h:form>
<h:inputText value="#{studentDb.name}" />
<h:inputText value="#{studentDb.rate}" />
<h:commandButton value="Add Student"
action="#{data.addStudent()}" />
</h:form>
</h:body>

Launch the created application. This time, instead of


a welcome phrase, you will see our simple form. Fill it in and
press the button:

Figure 34. Running the application

77
Lesson 6

After that, run phpmyadmin again, go to the jtest da-


tabase and make sure that a new record has been added to
the Student table:

Figure 35. A new entry in the Student table


If after clicking the button in our form the application
throws an exception org.hibernate.exception.JDBC­Connection
­Exception, run the addition to the JDBC driver project again.

78
Homework Assignment

Homework Assignment
As a homework assignment, you are invited to create
a web application. This application should use servlets, which
in turn should work with our jtest database.
On the application main page, create a form with the Add
button to add new entries to the Student table, similar to how
it was done in the last application. In addition, on the main
page, create another Show button. When you click this but-
ton, all the records in the Student table should be displayed
on the page.
The Add and Show button handlers must be servlets. It
can be two different servlets or the same. Come up the format
of data output from the table by yourself.

79
Lesson 6
Introduction to the de­velopment
of server-based solutions using Java,
Interaction with data sources

© Aleksander Gevorkyan.
© STEP IT Academy.
www.itstep.org

All rights to protected pictures, audio, and video belong to their authors or
legal owners.
Fragments of works are used exclusively in illustration purposes to the extent
justified by the purpose as part of an educational process and for educational
purposes in accordance with Article 1273 Sec. 4 of the Civil Code of the
Russian Federation and Articles 21 and 23 of the Law of Ukraine “On Copyright
and Related Rights”. The extent and method of cited works are in conformity
with the standards, do not conflict with a normal exploitation of the work, and
do not prejudice the legitimate interests of the authors and rightholders. Cited
fragments of works can be replaced with alternative, non-protected analogs,
and as such correspond the criteria of fair use.
All rights reserved. Any reproduction, in whole or in part, is prohibited.
Agreement of the use of works and their fragments is carried out with the
authors and other right owners. Materials from this document can be used
only with resource link.
Liability for unauthorized copying and commercial use of materials is defined
according to the current legislation of Ukraine.

You might also like