Java Lessons
Java Lessons
Lesson 6
Introduction to
the development
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
5
Lesson 6
6
Frameworks and Libraries
7
Lesson 6
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>
9
Lesson 6
10
Frameworks and Libraries
package com.mycompany.app;
/*
* Hello world!
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
@Override
public String toString()
{
13
Lesson 6
package com.mycompany.app;
/**
*
* Hello world!
*
*/
14
Frameworks and Libraries
15
Lesson 6
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:
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.
18
Frameworks and Libraries
19
Lesson 6
20
Frameworks and Libraries
21
Lesson 6
22
Frameworks and Libraries
23
Lesson 6
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
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
28
Frameworks and Libraries
29
Lesson 6
30
Frameworks and Libraries
public Student() {
}
@Override
public String toString() {
return "Student{" + "name=" + name + ",
rate=" + rate + '}';
}
31
Lesson 6
<bean id="student">
</bean>
32
Frameworks and Libraries
33
Lesson 6
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}
34
Frameworks and Libraries
public Group()
{
this.students=new ArrayList<>();
this.name="noname";
}
35
Lesson 6
@Override
public String toString()
{
String str="";
str+="Group:\t"+name+"\n\n";
for (Student s:students)
{
str+=s+"\n";
}
str+="\n\n";
return str;
}
}
36
Frameworks and Libraries
37
Lesson 6
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}
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
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
41
Lesson 6
42
The Concept of a Servlet
<body>
<h1>Hello World!</h1>
<form action="GreetingServlet" method="POST">
Login: <input type="text" name="login"
size="20"> <br/>
Password:
<input type="password" name="pass" size="20">
43
Lesson 6
44
The Concept of a Servlet
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:
46
The Concept of a Servlet
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
)
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
}
49
Lesson 6
this.doUploud(request);
}
processRequest(request, response);
}
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();
}
51
Lesson 6
//
String btn1=request.getParameter("showImages");
String select=request.getParameter("lImages");
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);
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:
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);
55
Lesson 6
Connection connection =
DriverManager.getConnection(driverUrl);
56
Data sources
57
Lesson 6
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).
58
Data sources
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);
}
}
60
Data sources
Logger.getLogger(DbManager.class.getName()).
log(Level.SEVERE, null, ex);
}
return set;
}
}
"jdbc:mysql://host/dbName?useUnicode=
true&characterEncoding=utf-8"
where:
■■ host — server address;
■■ DbName — database name;
61
Lesson 6
62
Data sources
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.
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):
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
66
Data sources
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.
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>
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:
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;
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;
}
}
71
Lesson 6
public Student(){
this.name="";
this.rate=0;
}
72
Data sources
73
Lesson 6
<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
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
75
Lesson 6
public StudentDb(){}
76
Data sources
<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>
77
Lesson 6
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 development
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.