Java Advanced Features and Programming Techniques (Step-By-Step Java Book 3)
Java Advanced Features and Programming Techniques (Step-By-Step Java Book 3)
Nathan Clark
© Copyright 2018 Nathan Clark. All rights reserved.
No part of this publication may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or other
electronic or mechanical methods, without the prior written permission of
the publisher, except in the case of brief quotations embodied in critical
reviews and certain other noncommercial uses permitted by copyright law.
Every effort has been made to ensure that the content provided herein is
accurate and helpful for our readers at publishing time. However, this is not
an exhaustive treatment of the subjects. No liability is assumed for losses or
damages due to the information provided.
Any trademarks which are used are done so without consent and any use of
the same does not imply consent or permission was gained from the owner.
Any trademarks or brands found within are purely used for clarification
purposes and no owners are in anyway affiliated with this work.
Books in this Series
Table of Contents
Introduction
1. Collections
2. Controlling the App Execution
3. Packages in Java
4. Multithreading
5. Java Annotations
6. Reflection
7. Java Properties
8. Serialization
9. What is Java EE?
10. Java Servlets
11. Java Server Faces
12. Java Database Connectivity (JDBC)
13. Android and Java
Conclusion
About the Author
Introduction
Collections are special classes in Java that makes working with special data
classes much easier. For example, imagine we have a collection called the
ArrayList collection, and we want to find out the size of the array. Instead
of writing special code to find out the size, we can use a built-in function of
the collection called size() to get the size of the array.
Some of the notable advantages of collections are:
It reduces the programming effort required by the developer, since
these are built-in available data structures and algorithms that don't
have to written from scratch.
It increases performance by providing high-performance
implementation of data structures and algorithms.
It provides interoperability between unrelated APIs, by establishing a
common language in order to pass collections back and forth.
It also reduces the effort required to learn APIs, by lessening the need
to learn multiple ad hoc collection APIs.
The following collections are present in Java:
ArrayList - The array container is used to store a contiguous set of
values of the same data type.
HashSet - This collection is used to store elements in such a way that
there are no duplicate elements.
ArrayDeque - This collection is similar to a queue, but here we can
add elements at both the beginning and end of the queue.
HashMap – This is a collection which is a set of key value pairs.
Let’s look at each collection in more detail.
1.1 ArrayList
The ArrayList container is used to store a contiguous set of values of the
same data type. Let’s look at the definition of an array container via a
sample code.
The syntax for defining an array container is as follows:
ArrayList variablename=new ArrayList():
Where ‘element’ is the value that needs to be added to the ArrayList. Let’s
now look at an example of how to use the ArrayList collection.
We can also store other data types, such as strings, in the array list. Another
example is shown below:
Example 2: The following program shows how to use array lists with
strings.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayList arr=new ArrayList();
arr.add("One");
arr.add("Two");
We can also store objects of defined classes in the array list. An example of
this is shown below:
Example 3: The next program is used to showcase array lists with classes.
import java.util.*;
class Person
{
public String Name;
}
arr.add(Per1);
arr.add(Per2);
Now let’s look at the other methods that are available for the ArrayList
class.
1.1.1 Size
This method returns the number of elements in the ArrayList. Let’s see an
example of this.
arr.add(1);
arr.add(2);
Example 5: The following program showcases the way to use the contains
method.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayList arr=new ArrayList();
arr.add(1);
arr.add(2);
1.1.3 Remove
This method removes the element at the specified position in the array list.
Let’s see an example of this.
Example 6: This program is used to showcase the way to use the remove
method.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayList arr=new ArrayList();
arr.add(1);
arr.add(2);
arr.add(3);
Example 7: The next program is used to showcase the way to use the add
at index method.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayList arr=new ArrayList();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(2,4);
int length=arr.size();
for(int i=0;i<length;i++)
System.out.println(arr.get(i));
}
}
1.2 HashSet
This collection is used to store elements in such a way that there are no
duplicate elements.
The syntax for defining an array container is as follows:
HashSet variablename=new HashSet():
In this code we need to specify the data type for the items in collection, as
well as the data type of the iterator object. The variable name is the
collection variable. We can then iterate through the elements using the
‘Next’ method.
while (itr.hasNext())
st.add(1);
st.add(2);
st.add(3);
Example 9: The following program shows the hash set collection with
strings as elements.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
Set st = new HashSet();
st.add("One");
st.add("Two");
st.add("Three");
Now let’s look at the other methods that are available for the HashSet class.
1.2.1 Size
This method returns the number of elements in the HashSet. Let’s see an
example of this.
Example 10: The next program showcases the size method of the hash set
collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
Set st = new HashSet();
st.add("One");
st.add("Two");
st.add("Three");
1.2.2 Contains
This method returns True if the HashSet contains the item we specify, else
it returns False. Let’s see an example of this.
st.add("One");
st.add("Two");
st.add("Three");
1.2.3 Removes
This method removes the specified element from the HashSet if it is
present. Let’s look at an example of this.
Example 12: This program is used to showcase the removes method of the
hash set collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
Set st = new HashSet();
st.add("One");
st.add("Two");
st.add("Three");
st.remove("Two");
System.out.println("Does the Hash Set contain the value Two "+st.contains("Two"));
}
}
1.3 ArrayDeque
This collection is similar to a queue, but here we can add elements at both
the beginning and end of the queue.
The syntax for defining an array container is as follows:
ArrayDeque<datatype> variablename=new ArrayDeque<datatype>():
arr.add(1);
arr.add(2);
arr.add(3);
arr.add("One");
arr.add("Two");
arr.add("Three");
1.3.1 Size
This method returns the number of elements in the HashSet. Let’s see an
example of this.
Example 15: The next program shows how to use the size method of the
ArrayDeque collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayDeque<String> arr = new ArrayDeque<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
1.3.2 Contains
This method returns True if the ArrayDeque contains a specified item,
otherwise it returns False. Let’s look at an example of this.
Example 16: The following program is used to showcase the contains
method of the ArrayDeque collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayDeque<String> arr = new ArrayDeque<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
1.3.3 Removes
This method removes the specified element from the queue, if it is present.
Let’s see an example of this.
arr.remove("Two");
System.out.println("Does the ArrayDeque contain the element "+arr.contains("Two"));
}
}
1.3.4 addFirst
This method adds an element to the beginning of the queue. Let’s see an
example of this.
Example 18: The following program shows how to use the addFirst
method of the ArrayDeque collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayDeque<String> arr = new ArrayDeque<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
arr.addFirst("Zero");
1.3.5 addLast
This method adds an element to the end of the queue. Let’s look at an
example of this.
Example 19: The next program showcases the addLast method of the
ArrayDeque collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayDeque<String> arr = new ArrayDeque<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
arr.addLast("Four");
1.3.6 getFirst
This method retrieves the element at the beginning of the queue. Let’s see
an example of this.
Example 20: The next program is used to show the getFirst method of the
ArrayDeque collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayDeque<String> arr = new ArrayDeque<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
1.3.7 getLast
This method fetches the element at the end of the queue. Let’s see an
example of this.
Example 21: This program shows how to use the getLast method of the
ArrayDeque collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayDeque<String> arr = new ArrayDeque<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
1.4 HashMap
This collection is used to store a collection of key value pairs. When we
retrieve a value, we can do it by specifying the key value.
The syntax for defining an array container is as follows:
HashMap variablename=new HashMap():
In this code, as shown previously, ‘variablename’ is the variable name to be
assigned to the HashMap. To add an element to the HashMap we use the
‘put()’ method as shown below.
Variablename.put(key,value)
In the above, ‘key’ and ‘value’ is the key and value pair to be added to the
HashMap. To get the value for a particular key, we can use the ‘get’
method. Let’s look at an example of how to use the HashMap collection.
mp.put(1,"One");
mp.put(2,"Two");
mp.put(3,"Three");
Now let’s look at some of the methods available for the HashMap class.
1.4.1 Size
This method displays the number of elements in the HashMap object. Let’s
see an example of this.
Example 23: This program is showcases the size method of the HashMap
collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
HashMap mp = new HashMap();
mp.put(1,"One");
mp.put(2,"Two");
mp.put(3,"Three");
1.4.2 containsKey
This method returns True if the map object contains a particular key we
specify, else it returns False. Let’s see an example of this.
Example 24: The next program is used to show the workings of the
containsKey method of the HashMap collection.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
HashMap mp = new HashMap();
mp.put(1,"One");
mp.put(2,"Two");
mp.put(3,"Three");
1.4.3 containsValue
Similar to containsKey, this method returns True if the map object contains
a particular value, rather than key. Let’s see an example of this.
mp.put(1,"One");
mp.put(2,"Two");
mp.put(3,"Three");
1.4.4 Removes
This method removes an object based on the key value we specify. Let’s
look at an example of this.
mp.put(1,"One");
mp.put(2,"Two");
mp.put(3,"Three");
mp.remove(2);
System.out.println("Does the map contain the value Two "+mp.containsValue("Two"));
}
}
2.1 Security
One of the most important aspects when it comes to running programs on
workstations is the security that is assigned to the program. Since there are
a lot of potentials threats in the industry, it becomes important to control the
security aspects of the program. On the Windows platform we have the Java
Control Panel, which can be used to control the different aspects of the
program.
Let’s look at some of the important features of the Java Control Panel.
Example 27: The following program shows how to work with arguments
in the main method.
public class Demo
{
public static void main(String[] args)
{
if(args.length<1)
System.out.println("No arguements");
else
{
for(String str:args)
System.out.println(str);
}
}
}
Most of the classes and interfaces in Java are organized in what is referred
to as ‘Packages’. When we worked with collections, we saw that we had to
import the java.util package. This is because the collection classes were
located in this package.
Java also gives us the ability to create our own packages, organize the class
files in these packages, and then access those packages and classes. To
ensure that a class is part of a package, we need to define the package
statement at the beginning of the class as shown below.
packge packagename
class Student
{
public String Name;
public void Display()
{
System.out.println(this.Name);
}
}
Where:
The ‘–d’ option means that a destination folder, with the same name
as the package, should be created.
The dot(.) indicates that we want to create this in the current folder.
So when we run the above command, we will get a ‘Student.class’
compiled file that will be in a folder called ‘person’.
Now let’s create another Java program called ‘Demo.java’, which will also
make use of this packaged class. To do this, let’s attach the following code:
import person.Student;
class Demo
{
public static void main(String[] args)
{
Student stud =new Student();
stud.Name="John";
stud.Display();
}
}
Note that even if we don’t use the import statement, we can use the fully
qualified name of the class as shown below.
class Demo
{
public static void main(String[] args)
{
person.Student stud =new person.Student();
stud.Name="John";
stud.Display();
}
}
We can also have a nested directory structure for our packages. An example
is shown below.
Example 29: This program shows how to use packages in Java with
nested directories.
First we will define a class called ‘Student’ as shown below:
package com.person;
class Student
{
public String Name;
public void Display()
{
System.out.println(this.Name);
}
}
Then we compile the program as follows:
java –d . Student.java
The compiler will create a folder called ‘com’. In that folder it will create a
subfolder called ‘person’, and it will place the class file in that folder. Now
we need to create the ‘Demo’ class as shown below:
import com.person.Student;
class Demo
{
public static void main(String[] args)
{
Student stud =new Student();
stud.Name="John";
stud.Display();
}
}
Threads are used for concurrent programming. All systems are designed to
run programs as threads, which can run concurrently. As a result,
programming languages also have the facility to support threaded
programming. By running threads, we can run multiple code side by side,
giving us more results in a shorter duration of time.
In Java, a thread can be in any one of the following states:
New - The thread is in the new state when we create an instance of
the ‘Thread’ class, but before the invocation of the ‘start()’ method.
Runnable - The thread is in the runnable state after invocation of the
‘start()’ method.
Running - The thread is in the running state if the thread scheduler
has selected it.
Non-Runnable (Blocked) - The thread is in this state when the thread
is still alive, but is currently not eligible to run.
Terminated - The thread is terminated or in the dead state when its
‘run()’ method exits.
All threads are created with the help of either extending the thread class, or
the Runnable Interface. Let’s look at some examples of threads.
We can also add more code to the run method, and we can create an array
of threads. Let’s look at an example of this.
Example 31: The next program shows how to create an array of threads.
class MyThread extends Thread
{
public static int count=0;
public void run()
{
count++;
System.out.println("Thread running" + count);
}
}
public class Demo
{
public static void main(String args[])
{
MyThread[] th=new MyThread[3];
for(int i=0;i<3;i++)
{
th[i]=new MyThread();
th[i].start();
}
}
}
Now let’s look at an example of how to work with threads using the
Runnable Interface.
We can also get the state of the thread at any point in time. This can be done
by using the ‘getState’ method on the thread. Let’s see an example of how
we can get the state of a thread.
Example 33: The following program is used to showcase how to get the
state of a thread.
class MyThread extends Thread
{
public static int count=0;
public void run()
{
count++;
System.out.println("Thread running" + count);
}
}
public class Demo
{
public static void main(String args[])
{
MyThread[] th=new MyThread[3];
for(int i=0;i<3;i++)
{
th[i]=new MyThread();
th[i].start();
System.out.println(th[i].getState());
}
}
}
In the above code line, the ‘@’ symbol indicates to the compiler that this is
an annotation. One of the most common annotations you would see is the
‘@Override’ annotation. This is used in the derived class whenever the
derived class method overrides the implementation in the base class.
Let’s look at an example of this annotation.
Step 1
First create the annotation type as shown below:
@interface annotationname
{
//Annotation members
}
Here the ‘annotationname’ is the name of the annotation. And then we can
have members for the annotation. For example, let’s say we want to create
an annotation called ‘Author’ and then have a name for the author. We can
then define ‘Author’ as the name of the annotation, and define a member of
the ‘String’ type with the ‘name’ value.
Step 2
Append the ‘@Retention(RetentionPolicy.RUNTIME)’ statement to the
annotation. This ensures that the annotation is available at runtime.
Step 3
The next step is to access the annotation through reflection. Reflection is
the process of gaining access to classes and methods at runtime. There is an
entire chapter dedicated to reflection later in this book. But for now, it’s
good to just know that the concept of getting the annotation values is called
reflection.
The best way to understand the entire process is with an example.
@Retention(RetentionPolicy.RUNTIME)
@interface Author
{
String name();
}
@Author(name="John")
class Person
{
void Display()
{
System.out.println("This is the Person class");
}
}
public class Demo
{
public static void main(String args[])
{
Class<Person> aClass = Person.class;
Annotation annotation = aClass.getAnnotation(Author.class);
@Retention(RetentionPolicy.RUNTIME)
@interface Author
{
String name();
}
class Person
{
@Author(name="John")
void Display()
{
System.out.println("This is the Person class");
}
}
public class Demo
{
public static void main(String args[])
{
Class<Person> aClass = Person.class;
Method[] method = aClass.getDeclaredMethods();
Now when we compile the above program, we will get the following
compile time error:
Warning:(15, 12) java: Display() in Person has been deprecated
We can still run the program, but we will get the warning every time. This
means that the method should be removed from the class in the future. On
the other hand, we can also suppress this warning by using the
‘@SuppressWarnings’ annotation. Let’s look at an example of this.
@SuppressWarnings(value = "deprecation")
Now when we compile the program we will not get any warnings, because
the ‘@SuppressWarnings’ annotation has been applied to the class that has
our main program.
6. Reflection
The above implementation retrieves the built-in methods for the class. Let’s
look at an example of how we can get the declared methods for the class.
Example 41: This program shows how to get the name of the class via
reflection.
import java.lang.reflect.Method;
class Person
{
public void Display(){}
public void Input(){}
}
public class Demo
{
public static void main(String args[])
{
Class cls = Person.class;
System.out.println("The class name is "+cls.getName());
}
}
Example 42: The next program shows how to get the constructors of a
class.
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
class Person
{
Person()
{
}
public void Display(){}
public void Input(){}
}
public class Demo
{
public static void main(String args[])
{
Class cls = Person.class;
Example 43: The following program shows how to get the fields of a
class.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Person
{
int ID;
Person()
{
}
public void Display(){}
public void Input(){}
}
public class Demo
{
public static void main(String args[])
{
Class cls = Person.class;
Step 1
First we need to create an object of the class through reflection. This is
done via the statements below. Here we need to mention the name of the
class.
Class<?> c = Class.forName(classname);
Object t = c.newInstance();
Step 2
Next we need to get the handle to the method by calling the
‘getDeclaredMethod’ reflective method.
Step 3
Then we use the ‘Invoke’ function to invoke the method.
Step 4
We also need to ensure that our main method makes an explicit declaration
to throw the possible exceptions below, when working with methods and
reflection.
NoSuchMethodException
InvocationTargetException
IllegalAccessException
ClassNotFoundException
InstantiationException
Now let’s look at an example of how to invoke methods via reflection.
Example 44: The following program shows how to invoke methods via
reflection.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Person
{
int ID;
Person()
{
}
public void Display()
{
System.out.println("This is the Display method");
}
public void Input(){}
}
public class Demo
{
public static void main(String args[]) throws NoSuchMethodException,
InvocationTargetException, IllegalAccessException, ClassNotFoundException,
InstantiationException
{
Class<?> c = Class.forName("Person");
Object t = c.newInstance();
class Person
{
int ID;
public void Display(int pid)
{
System.out.println("The id is "+pid);
}
public void Input(){}
}
public class Demo
{
public static void main(String args[]) throws NoSuchMethodException,
InvocationTargetException, IllegalAccessException, ClassNotFoundException,
InstantiationException
{
Class<?> c = Class.forName("Person");
Object t = c.newInstance();
Example 46: This program shows how to change the value of fields via
reflection.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Person
{
public int ID;
public String name;
public void Display()
{
System.out.println("The ID of the person is "+this.ID);
System.out.println("The name of the person is "+this.name);
}
public void Input(){}
}
public class Demo
{
public static void main(String args[]) throws NoSuchMethodException,
InvocationTargetException, IllegalAccessException, ClassNotFoundException,
InstantiationException, NoSuchFieldException
{
Class<?> c = Class.forName("Person");
Object t = c.newInstance();
Java properties are configuration values that are nothing more than key
value pairs. For each pair, the key and the value are both String values. To
manage properties, Java provides the ‘java.util.Properties’ class. This class
provides methods for the following:
Loading key/value pairs into a Properties object from a stream.
Retrieving a value from its key.
Listing the keys and their values.
Enumerating over the keys.
Saving the properties to a stream.
When we look at some of the use cases for properties, one clear example is
the storage of database properties in a file. For example, the properties file
can be used to store database values which can then be read from the
program.
Let’s look at an example on this.
Example 47: The following program showcases how to work with the
properties file.
First we create a file called ‘db.properties’ and we add the following key
value pairs to the file:
user=system
password=oracle
Example 48: The following program shows how to get system properties.
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
We can also create our own properties objects, and utilize them in a
program. Let’s look at an example of this.
Example 49: The program below shows how to set the properties object.
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
When we run the above program, the code will be written to a file called
‘db.properties’.
8. Serialization
When the program is executed, the object would be written in binary format
to the Sample.txt file. We can also read the object from the file with a
process called deserialization. Let’s look at an example of how this is done.
Example 53: This program shows how to use base and derived classes in
serialization.
import java.io.*;
Example 54: The following program showcases the use of the transient
keyword.
import java.io.*;
With this program, the output is as shown below. You will notice that the
value of ‘ID’ is defaulting to zero, because this value was not serialized.
The ID of the Student is 0
The name of the Student is John
The marks of the Student is 10
9. What is Java EE?
So far we have looked at how to work with the standard Java programming
language. Let’s quickly review what the Java world has available for
developers and enterprises. There are currently four platforms available:
Java SE - This is the Standard Edition, which contains all the core
Java libraries and the Java API's. Here you also get access to the Java
Virtual Machine that is used to run basic Java applications.
Java ME - This is the Micro Edition of Java. Here you get a subset of
features of the main Java Standard Edition. This is good for
developing applications on smaller devices such as mobile devices.
Java FX - This library is used for building rich internet based
applications. Here you can design a modern look and feel application
with a rich user interface.
Java EE - Finally you have the Enterprise Edition, which is used for
developing enterprise based applications.
Many organizations make use of the Java Enterprise Edition. This edition is
based on a set of specifications. For example, the web specification is used
for building web based applications. Let’s look at some of the components
of the Java Enterprise Edition in more detail.
try
{
out.println("<html><head>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
out.println("</body>");
out.println("</html>");
}
finally
{
out.close();
}
}
}
@ManagedBean(name="demo")
@SessionScoped
public class Demo implements Serializable
{
private String str = "Hello World!!";
The second part is the xhtml page that references the JSF object.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Example</title>
</h:head>
<h:body>
#{demo.str}
</h:body>
</html>
Alternatively if the class was going to work with the HttpServlet class, then
the syntax would be as follows:
public class Demo extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
}
}
Once the servlet has been created, the skeleton code below will be added
for you.
Example 58: The following program shows how to create a basic servlet
program.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Demo
*/
@WebServlet("/Demo")
public class Demo extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Demo()
{
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// TODO Auto-generated method stub
response.getWriter().append("Hello World");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// TODO Auto-generated method stub
doGet(request, response);
}
}
When we run the program in Eclipse, it will run in Apache in Eclipse and
we will get the following output:
Hello World
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Demo
*/
@WebServlet("/Demo")
public class Demo extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Demo()
{
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// TODO Auto-generated method stub
String id=request.getParameter("Id");
String name=request.getParameter("name");
PrintWriter out=response.getWriter();
out.println("<p> Id is "+id + "</p>");
out.println("<p> Name is "+name + "</p>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// TODO Auto-generated method stub
doGet(request, response);
}
}
The following things need to be noted about the modified program:
In the ‘doGet’ method, we now create a ‘PrinterWriter’ object to
write data back as a response.
We then use the ‘request.getParameter’ object to get the query string
parameters. Here we are assuming that we are passing an ‘ID’ and
‘Name’ as the query string parameters. We are then writing these
values back in the response.
Finally, we are embedding these values in html tags and then writing
the response back to the client.
When we refresh the browser window in Eclipse, we will get the following
output:
This is because we are not passing any Query String values, hence the
default value of the ID and Name is null. If we append the Query String to
the url, we get the following output:
So from the above output we can see that once we enter the Query String
parameters, we get the desired output.
11. Java Server Faces
Java Server Faces (JSF) is used to develop component based user interfaces
for web based applications. The Java Server Faces application runs on the
server that processes the Java Server based application. The program itself
can also contain JavaScript for client side interaction.
For the purpose of working with Java Server Faces, we need to use the
GlassFish tools. GlassFish is a reference implementation of the Java
Enterprise Edition and will help to build Java Server Faces programs. If we
are using an IDE such as Eclipse, we need to add the GlassFish Tools to it.
This can be done through the following steps:
Go to ‘Preferences’.
Choose ‘Server Runtime Environments’.
Choose to add a new runtime environment. Here under Oracle, we
can see the GlassFish Tools.
If you don’t have the GlassFish software, it can be downloaded from
the following link: https://javaee.github.io/glassfish/download
Once GlassFish has been installed, again go back to Preferences and
Server Runtime Environment. Choose to add a runtime environment
and ensure to choose ‘Create a new local server’.
Next we need to specify the location of the Java Runtime
Environment and GlassFish folder.
Once all this is done, we can start developing our first application.
In the above program, we need to add an annotation for the class to ensure
it is recognized as a ‘ManagedBean’. Then we define a property called
‘world’ and put the value as ‘Hello World’.
Step 3
In the ‘web.xml’ file, the following code should be present to ensure that
this becomes a Java Face application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Step 4
Create an xhtml file that will be used to render the application.
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelets Hello World</title>
</h:head>
<h:body>
#{hello.world}
</h:body>
</html>
In the above program, we are referencing the static property from our class
using the code line:
#{hello.world}
Once we run the application using the GlassFish Server, we will get the
following output:
localhost:8080/Demo/
Hello World!
12. Java Database Connectivity (JDBC)
Example 60: The following program shows how to read data from a
database table.
import java.sql.*;
public class Sample
{
public static void main(String args[]) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Person","admin","password");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from Per");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
}
}
We can also use JDBC to insert records into the database. Let’s look at an
example of this.
Example 61: The following program shows how to insert records into a
table.
import java.sql.*;
public class Sample
{
public static void main(String args[]) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Person","admin","password");
PreparedStatement stmt=con.prepareStatement("insert into per values(?,?)");
stmt.setInt(1,2);
stmt.setString(2,"Mark");
int i=stmt.executeUpdate();
System.out.println(" The number of records inserted is "+i);
con.close();
}
}
We can also get metadata about the table via JDBC. Let’s look at an
example of this.
Example 62: The following program shows how to get the table metadata.
import java.sql.*;
public class Sample
{
public static void main(String args[]) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Person","admin","password");
con.close();
}
}
Another thing we can do is use JDBC to get the metadata about the
database. Below is an example of this.
Example 63: The following program shows how to get the database
metadata.
import java.sql.*;
import com.mysql.jdbc.DatabaseMetaData;
con.close();
}
}
The Android Studio and SDK are available at the following link:
https://developer.android.com/studio/index.html
Once you download and install Android Studio, you go ahead and build a
new project. Make sure to choose the basic template to begin with. The
steps below show how to create a project in Android Studio.
First we start by giving our application a name.
Select the form factors for the application. The API level will
determine the compatibility of our app. The older we go, the more
compatible our app will be, but we will lose some key features.
Choose the type of activity. We will start with a basic activity for our
example.
The MainActivity class will contain the following boiler template code:
package com.example.techuser.myapplication;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
We have unfortunately reached the end of this guide. But as I always say, it
doesn’t mean your Java journey should end here. Practice as much as
possible. This book was written not only to be a teaching guide, but also a
reference manual. So remember to always keep it near, as you venture
through this wonderful world of programming.
If you enjoyed this guide, and this series, be sure to look into the other
programming languages I cover, such as Python. It is a high-level language
that is used in a variety of different applications. Python is best known for
the simplicity of its programs. It requires less code to create a similar
program in Python, compared to other languages. This makes it one of the
most popular languages available today.
About the Author