Preface
This is a condensed version of Chapter VI (Web Application with Java and Eclipse)
from the book Web Programming in Java (Italian Edition Programmazione per il
Web publisher ARACNE).
This book has been written for students and for the professional, and it can serve as a
starting point for anyone who is beginning the study of Web Application in Java for the
first time. In the following text, Servlet, JSP, JavaBean and simple DAO are accurately
analyzed and implemented in Java, with a clear project evolution: from the configuration
of Eclipse Mars, JDK, MySQL and Tomcat to the execution and the testing on a browser
and the creation of the final package for the distribution on other machines. Everything is
integrated with explanations, java codes and screenshots to have a step by step evolution
of the web application. Let us try to do this in a day!
I think that everyone has to always follow their own dreams and fight for them
Figure 2. MySQL Server Installation, licence.
The wizard asks for the administrator password setting. We shall use simply root for
development environment.
Figure 7. MySQL Server Installation password setting.
The end.
Figure 12. MySQL Server Installation end.
The end.
Figure 16. MySQL Workbench Installation - end.
Afterwards, the screen will show the standard parameters for connection. Click okay!
Figure 19. Parameters for connection.
Now we shall create a new schema. Go to SCHEMAS area, and click the right
mouse button.
Now, we shall select Create Schema on the context menu.
Figure 22. Workbench, how to create a new Schema.
Figure 23. Workbench, how to create a new Schema creation script execution.
Once we create the DB, we shall create the tables, which are:
Company table;
Employee table.
The simplified design will be done in tabular form according to the conceptual and
logical design (not detailed in the text).
Schema: company_management
Now we shall create the tables.
Select our schema, then click the right mouse button on the tables.
Now, we shall select Create Table on the context menu.
Insert company in the Table Name!
Now, we shall create fields and define key fields (PK) and non-zero fields (NN). At
first, we can create the key field idcompany and the field company_name.
Figure 25. Workbench, Table name e field insertion.
Figure 26. Workbench, how to create a Table creation script execution.
Once the table is created, we can edit it using the screwdriver right icon from the left
menu of the table.
Figure 27. Workbench, how to modify a Table.
You can also display a table with its values and run queries, using the table right icon
from the left menu of the table.
Figure 28. Workbench, how to analyze a Table (query).
Now, we can complete the table defining all fields (idcompany, company_name, email,
phone, date_ins). The following figure shows the table company.
Now, we can create the table employee defining all fields defined in conceptual
design (idemployee, name, surname, badge, date_ins and the foreign key to the company
FK_company). The following figure shows the table employee.
Figure 30. Workbench, employee table.
Now, it is necessary to define constraints between the employee and his company.
Define then the FK_company as a foreign key, setting the tab Foreign Keys!
Figure 33. Workbench, how to create a Foreign Key creation script execution.
If we wanted, we could also export scripts for creating diagrams and tables with a
simple operation (right click on the schema or table, Copy to Clipboard, Create
Statement).
Figure 34. Workbench, how to export a creation schema script.
After selecting the DB, enter user / password, and, finally select the scheme.
Figure 38. Workbench, reverse engineer: user/password.
The system also automatically inserts the default indexes (primary and foreign keys).
Figure 41. Workbench, Workbench, tables schema of reverse engineering with indexes.
As soon as we start the executable file, the IDE asks what is the workspace (i.e. the
project folder): I usually change the standard directory and choose the directory C: /.
Now, install the executable file! Then we shall configure the IDE, from window -
preferences - JAVA / Installed jre and select (or search on the PC) the downloaded jdk.
Figure 48. Eclipse, Tomcat selection.
Figure 49. Eclipse, Tomcat server and installed JRE.
After configuring the server, we can go on the tab server, the server will appear just
configured. We shall now click the right mouse button, open the context menu and start
the server.
Figure 51. Eclipse, how to start the selected server.
If we go on the browser, we can see the Tomcat server that is activated by typing the
following URL in the address bar (URL of the server followed by the name of the
application):
http://localhost:8080/ Web_Application_name
6. How to create a Dynamic Web Project in Eclipse
It is about ten thirty am!
Now we shall start the steps for creating a Java web application.
Go on the File menu and select New and then Dynamic Web Project.
The related wizard starts. We shall enter the name of the project
company_management and leave unchanged the other parameters.
Figure 53. Eclipse, configuration of a web project.
In particular:
Project name: it must be a valid identifier of the project for cross-platforms, so it is
advisable using lower-case name, with alphanumeric elements;
Use default location: it defines a directory where creating the web project (we
can leave to default, or specify a new folder);
Target Runtime: defines the application server to be used where deploying the
application (e.g. Tomcat);
Configuration: select the configuration to use, which usually is the used
application server (e.g. Tomcat). The Servlet 3.X uses @WebServlet deployment,
while the Servlet 2.5 uses web.xml deployment.
Then, we shall define the folders for source files (src) and compiled files (classes).
Figure 54. Eclipse, configuration of src e classes folder for a web project.
Finally, we shall define the context root of the application and the context directory.
For simplicity, we associate the same name in all the elements of configuration.
Figure 55. Eclipse, context root and context directory configuration.
In particular:
Context Root: it identifies access URL of the web application. In this case it will
be http://localhost:8080/company_management.
Content Directory: it is the directory that contains all components of the Web
Application, which will be deployed into the server, and it is the root of the
project.
Note that in this passage the creation of web.xml is checked. The automatic creation of
the deployment descriptor is deprecated because the descriptor is no longer necessary for
the latest applications (Servlet 3.X). The issue is related to the ability of working with
legacy applications developed with Servlet 2.X. never.
Below, the created project.
Figure 56. Eclipse, created web project.
6.1. How to create a JSP and run a project in Eclipse
The first step for working with Java and Eclipse is the creation of a JSP (Java Server
Page). We can just go to the File menu - New - JSP files.
Eclipse creates the following jsp page, automatically inserted in the created project.
Now we shall get to work by inserting the text HELLO WORLD! in the body and in
the title of the created JSP.
Figure 60. Eclipse, how to modify a JSP script.
In order to see the results of the web page it is enough to start the server. We can select
the server, click the right mouse button and, at last, click the green play button located on
the context-menu.
We can also select run from the menu, then select Run As and then Run on
Server from the context-menu.
Further, we can select the green button play from the menu, and then Run As e
Run on Server.
Finally, we can select the project, click the right mouse button and, from the context-
menu Run As and Run on Server.
Figure 65. Eclipse, Run from project.
If the server is yet not set, we can choose it from the context-menu.
Figure 66. Eclipse, selection of the server.
The last step is the configuration of the project company_management on the selected
server.
Figure 67. Eclipse, web application configuration on the server.
If we see the web.xml file, we can fill the file hello.jsp between the welcome-file-list: in
this way, the first page, that we see when we open the application, is one of those on the
list of the welcome-file-list.
Now, we shall consider index.jsp the welcome page, and then every time we open the
application at its URL (http://localhost:8080/company_management/) the index.jsp page
will be called.
6.2. How to create a Servlet 3.X in Eclipse
Now, we shall create a new Servlet! We can just go to the File menu - New - Servlet.
We can see the just created Servlet with the main methods in the following screen.
Figure 74. Eclipse, Servlet script.
We can see the just created empty Class in the following screen.
Figure 77. Eclipse, Class script.
7. Implementation of the Java Project for Web Application
It is about eleven am!
7.1. How to write and manage forms: the Eclipse Java Project runs on a browser!
We shall start to manage a form and, then, its control in a Servlet. Now, create the jsp
page with the following fields: name and idemployee. We shall create the formExample.jsp
by clicking the right mouse button on our project, then New, and JSP File.
Figure 78. Eclipse, how to create a JSP for our web application.
Figure 79. Eclipse, name of JSP.
There are two forms, characterized by two methods (POST and GET), two different
input fields and two submit buttons.
The Servlet works with two methods: doGet and doPost, which manage messages
coming from the request (HttpServletRequest), using the method:
request.getParameter(idemployee). If we want to see the data successfully processed by
the Servlet, we can simply use the command System.out.println, that allows us to view
data on the Eclipse console. In the following example it is also used a method of the
Response to display on the browser the sent parameters: response.getWriter(). See the
following Java code of FirstServlet.java.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
If we click the first submit button POST SUBMIT Figure 81 (which sends a POST
message to the servlet), we get the following result on the Eclipse browser and on the
browser.
Figure 83. Eclipse, POST result on the Eclipse browser and on the browser.
If we click the second submit button GET SUBMIT Figure 81 (which sends a GET
message to the servlet), we get the following result on the Eclipse browser and on the
browser.
Figure 84. Eclipse, GET result on the Eclipse browser and on the browser.
Now we shall create the two JSP form (without considering the layout of the html
page)!
The company fields are:
idcompany [varchar(16)];
company_name [varchar(45)];
phone [varchar(16)];
email [varchar(45)];
date_ins [date].
The employee fields are:
idemployee [varchar(16)];
name [varchar(45)];
surname [varchar(45)];
badge [int(10)];
FK_ company [varchar(16)];
date_ins [date].
Note that the date is important for the system administrator and it is not present in the
form!
Moreover, the maximum length of strings requires a control, which can be done in the
html form through the use of maxlength attribute. This attribute specifies the maximum
number of characters which can be filled in an form input field.
Finally, we shall use the POST method to send the form.
Now create two new jsp pages and the Servlet (we know how to do it!):
formCompany.jsp;
formEmployee.jsp;
CompanyManagement.java.
The following screenshot is for the Eclipse form of the Company.
Figure 85. Eclipse, form companyForm.jsp.
The following screenshots are for the browser form of the Company (empty and filled
in).
We can see that the employee presents a hidden field named FK_company. This field is
filled in by the idcompany of Company Entity once inserted the company. We shall fill in
this value when the company form is completed and sent to the servlet.
We shall do this with implementing a system of sessions.
See the following piece of Java code of the Servlet: in console, we can view the
parameters.
In order to distinguish the two entries from two different forms, from server side it is
possible to insert a hidden field (in a very simply way!) to understand if the submit form
comes from the company form or from the employee form and then manage it accordingly
by saving its fields. This operation is clear observing the console results!
We shall use the field whatsend, which helps us to establish the behavior in the servlet,
as we decided to use a single servlet. So, we shall have several whatsend hidden fields, in
our case:
company;
employee;
savecompany.
Figure 90. Servlet CompanyManagement.java and console.
7.2. JavaBean
It is twelve oclock!
Once we have taken values from the form, we need to manage them saving them into
Database. Therefore, according to the MVC pattern, it is necessary to create and use an
object which will be passed to a DAO (Data Access Object) class for saving data into
Database. This object can encapsulate many objects into a single object, which can be
serialized.
Now, we need to create and instantiate a new object (JavaBean), which sets and
maintains the status of its variables during the time of use. This class presents only the get
and set methods of its variables (pattern of data encapsulation).
We shall start with the creation of a new class.
Now, we shall enter all fields of the company and the Eclispe IDE helps us to
automatically generate the get and set methods (click the right mouse button class, then
Source, and Generate Getters and Setters..).
Figure 94. How to Generate Bean Getters and Setters step 1.
Figure 95. How to Generate Bean Getters and Setters step 2.
Then, we shall get the class with the get and set methods showing in the following Java
code and screenshot:
package company_management.bean;
/**
* @author manelli
*
*/
public class EmployeeBean implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -1549250885233338087L;
private String idemployee ;
private String name;
private String surname ;
private String badge ;
private String fk_company;
public String getIdemployee() {
return idemployee;
}
public void setIdemployee(String idemployee) {
this.idemployee = idemployee;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getBadge() {
return badge;
}
public void setBadge(String badge) {
this.badge = badge;
}
public String getFk_company() {
return fk_company;
}
public void setFk_company(String fk_company) {
this.fk_company = fk_company;
}
Figure 96. Eclispe, CompanyBean.java.
Now we need to link the two beans. The employee is part of the company and the
company can have from 1 to n employees.
How can they be related each other?
Obviously, it is sufficient adding an additional variable to the company bean, which
identifies the set of employees!
We shall use an ArrayList of EmployeeBean objects in the Company bean as shown
below:
private ArrayList< EmployeeBean > companyEmployees;
Then, it is necessary to generate the get and set method.
The java code into quotation marks (<>) represents the use of java generics.
7.3. Request Redirect vs Dispatcher
It is about ten past one! Five minute for a sandwich!
We shall use another object to return and maintain an object (with state!) from the
Servlet to the JSP. The server side presents two main method: redirect and dispatch. The
first is the following code:
response.sendRedirect(http://www.aracneeditrice.it/);
In such case, the Servlet does a redirect to a specific URL without taking memory of the
current state of its parameters (an example is the return to the home page of a site).
In the case of dispatch, it is assumed that the server does something else; in fact, the
browser displays a particular JSP and passes some parameters (such as those in session or
request); and the end-user does not know that the content of a JSP page is rendered in the
browser. In this case, the standard syntax is:
ServletContext sc = request.getSession().getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(/company.jsp);
rd.forward(request, response);
The servlet uses the application context and then transfers control to the JSP. In the
following text, we shall use mainly the dispatching method.
For example, we shall insert two new links: one to the home page and the other to the
employee page. We shall link the home page with a redirect and the JSP employee page a
dispatcher. In the following screenshot, it is possible to see the two links.
In the Servlet we shall use the doGet method to manage the request, as the Servlet is
called via a direct link (the html form GET method) and not via the submit form (the html
form POST method).
Figure 99. JSP links - employeeForm.jsp.
Then, change the jsp name in formCompanyFull.jsp: it will use the session.
As soon as we arrive at the page of the company, for the first time, the boolean variable
(companyFilled) is not used, since in the session object COMPANY is empty, so we can
not see the link to the employee JSP page. The companyid field is also empty! We can
digit this field!
Figure 102. Browser, empty formCompanyFull.jsp.
If the session is not null, the bean fields are taken from the session bean and set into JSP
variables, which dynamically pre-populate form elements with the data originally entered
in the form by the user, using the following java code (for example, for to the idcompany
field).
Fof idcompany variable:
String idcompany=;
Bean:
CompanyBean company = new CompanyBean();
Test of session:
if (request.getSession()!=null &&
request.getSession().getAttribute(COMPANY)!=null){
Below you can see the changes made to links and input fields.
Now we shall populate the form input fields and submit the form of the
formCompanyFull.jsp JSP page!
After populated and submitted the company form, in the Servlet, the company bean is
populated (with sets) and is put in the session with the attribute COMPANY. The
Servlet manages the fields, and dispatches to the formCompanyFull.jsp JSP page.
Now, we can note that the Company ID (idcompany) field is no longer editable (key
field con Company and foreign key for Employee).
It is possible also to note the activation of the employee link!
We need to set the company foreign key of the employee. We can choose to:
use a Request variable (from company JSP to employee JSP through Servlet),
which fill in the hidden field of employee JSP;
use a Session variable (from company JSP to employee JSP through Servlet),
which fill in the hidden field of employee JSP;
use the company Session bean (already set in session through Servlet), which fill
in the hidden field of employee JSP;
use no hidden field for employee, and set the foreign key only in Servlet.
Now, we shall use the companyid field of the company Session bean!
By clicking on the button Insert Employee, we get to the page of the employee, also
managed by the sessions, as we can show in the following screenshot.
Figure 108. JSP - formEmployeeFull.jsp.
After populated and submitted the employee form, the idemployee field is no longer
modifiable and the link appears for the insertion of a further employee.
Finally, we shall manage the servlet side linking the company to the employee (using
the command whatsend) with GET method. If we decide to enter an additional employee,
the Servlet removes the attribute EMPLOYEE from session.
Figure 112. Servlet, link GET.
If we click on Insert Another Employee, we view the same empty page again, we can
insert and save a new employee: this operation lead to the increase of the employees
arraylist associated with the company.
We must modify the servlet Java code to increment employees ArrayList, as shown
below.
Figure 113. Servlet, employees ArrayList.
Now the company object (with its employees) is ready to be stored on the just created
database.
Now try to insert an additional employee!
If we want to see employees, we can use a for each loop that displays the employees
to console.
We shall click on home page to remove session objects: in this way, we return to the
jsp corresponding to the insertion of a new empty company. The Servlet java code is
shown below.
The driver is related to the Java Connector. The other parameters specify the host
credentials to access DataBase.
Within a try considering the SQLException error in the DB, we are now connected to
the DB:
conn = getDBConnection();
Then set AutoCommit to false (so, we shall set when commit!):
conn.setAutoCommit(false);
This setting allows the final commit, only if all operations were successful.
conn.commit();
If any transaction does not go well, it will be made a rollback with error (which in this
case is returned to the Servlet, using the element throw):
conn.rollback();
System.out.println (INSERT ERROR:Transaction is being rolled back);
throw new SQLException(sqle.getErrorCode()+:+sqle.getMessage());
Now, it is possible to create the insert SQL script for the company:
String insertCompany = INSERT INTO COMPANY
(idcompany,company__name,phone,email,date_ins) ;
insertCompany += VALUES (
+ company.getIdcompany () + ,
+ company.getCompany_name + ,
+ company.getPhone () + ,
+ company.getEmail() + ,
+ SYSDATE());
System.out.println (INSERT QUERY:+ insertCompany);
int resultInsertCompany = stmt.executeUpdate(insertCompany);
System.out.println (resultInsertCompany: + resultInsertCompany);
We can use a simple log-like with the System.out.println command, which write on
console.
Then, it is possible create the insert SQL script for the employees (if present):
ArrayList<EmployeeBean> employees = company.getCompanyEmployees();
for (EmployeeBean employee:employees)
{
String insertEmployee = INSERT INTO EMPLOYEE
(idemployee,surname,name,badge,FK_company,date_ins) ;
insertEmployee += VALUES (
+ employee.getIdemployee() + ,
+ employee.getSurname() + ,
+ employee.getName() + ,
+ employee.getBadge() + ,
+ employee.getFk_company() + ,
+ SYSDATE());
System.out.println(INSERT EMPLOYEE:+insertEmployee);
int resultInsertEmployee = stmt.executeUpdate(insertEmployee);
System.out.println(result Insert QUERY:: +resultInsertEmployee);
}
In this case, employees are gotten from the company bean and cycled in a for-each loop.
At the end, the connection is closed:
finally {
if (stmt != null ) stmt.close();
if (conn != null ) conn.close();
}
The following screenshot shows the java code.
The Connection String.
We have to change the Servlet for saving data on the DB (SaveMySQL.java) and then
dispatching to the search page.
Figure 121. Servlet for saving on DataBase.
Now, we shall see also the DB, and check the inclusion of the company and employees
into the DB.
We can see the ERROR:
Row 55 of SaveMySQL.java (SQLException):
INSERT ERROR: Transaction is being rolled back
We can see how the class leave the error management to the Servlet (throw):
Row 58 of SaveMySQL.java:
throw new SQLException(sqle.getErrorCode()+:+sqle.getMessage());
Console Log of SaveMySQL.class:
ERROR:0:1054:Unknown column companyname in field list
Row 210 of CompanyManagemet.java:
System.out.println(ERROR:+e.getErrorCode()+:+e.getMessage());
The error of SQLException type is catched in the block of competence and, in the
DAO class the operation is rolled back. In such a case it can be sufficient an elementary
manage of the error with a simple jsp. The servlet redirects, in case of error, the request on
an error page. We shall create a boolean variable inside the catch: according to this
variable value, we can display the error page or continue with the execution of the servlet.
Figure 129. Boolean variable in Servlet error management.
In the following screenshot, we can see the simple error.jsp JSP page.
If we open the zipped file, we can see the company_management folder tree project.
In the WEB-INF folder, there is the classes folder with compiled java files (.class). We
shall insert the war project under the server, Tomcat 8, in the webapps folder (C:\apache-
tomcat-8.0.14\webapps).
Tomcat starts from the bin folder (C:\apache-tomcat-8.0.14\bin):
startup.bat/shutdown.bat under Windows environment.
Figure 133. Tomcat bin folder.
Attention! Set the JAVA_HOME Tomcat in the catalina.bat file, indicating the JDK used
for application development. We shall add the line:
set JAVA_HOME=C:\Program Files\Java\jdk1.8_065
The Tomcat startup opens a DOS window.
Finally, you can see that the web application will be unzipped in the webapps folder
(C:\apache-tomcat-8.0.14\webapps).
Figure 135. Tomcat webapps folder.
Viel mehr als nur Dokumente.
Entdecken, was Scribd alles zu bieten hat, inklusive Bücher und Hörbücher von großen Verlagen.
Jederzeit kündbar.