© Peter Späth 2021
P. SpäthBeginning Java MVC 1.0https://doi.org/10.1007/978-1-4842-6280-1_2

2. Prerequisite: Jakarta EE/Java EE

Peter Späth1 
(1)
Leipzig, Sachsen, Germany
 

You can’t run Java MVC in a standalone mode. Instead, it must be accompanied by the infrastructure a Java Enterprise Edition Server (Java EE or Jakarta EE) provides. We talk about what this means in this chapter.

The Nature of Java for Enterprise Applications

In a corporate environment, a programming language and software platform like Java has to cover a couple of needs that are important to run a business. It has to be able to connect to one or more databases, reliably establish communication with other IT-based systems in the same company or with connected businesses, and it has to be powerful enough to reliably handle input and perform calculations based on input and database data, and present the appropriate output to clients. As a cross-concern, security also plays an important role. An authentication process needs to be established that forces the users to identify themselves, and an authorization needs to be achieved to limit the amount of resources a particular user is allowed to access. In addition, activities need to be logged for technical maintenance and auditing purposes, and the platform should be able to present monitoring data for technical sanity checks and performance-related investigations.

For all these to work in a desired way, a language and platform must be stable with respect to future changes and enhancements. This has to happen in a way that new language and platform versions can be appropriately handled by the IT staff. Java EE/Jakarta EE follow this trail and thus are very useful in corporate environments.

The Jakarta EE 8 server entirely runs on and depends on Java. Java was invented in 1991 but was first publicly released under version 1.0 by Sun Microsystems in 1996. Java has since played an important role as both a language and a runtime environment or platform. There are several reasons that Java became so successful:
  • The same Java program can run on different operating systems.

  • Java runs in a sandboxed environment. This improves execution security.

  • Java can be easily extended with custom libraries.

  • The Java language was extended only slowly. While a slow evolution means new and helpful language constructs may be missing in the most current version, it helps developers easily keep track of new features and thoroughly perform transitions to new Java versions in longer running projects. Furthermore, with only a small number of exceptions, Java versions were backward-compatible.

  • Java includes a garbage collector that automatically cleans up unused memory.

Since 1998 and the major rebranding as Java 2, the platform was made available in different configurations:
  • The standard edition J2SE for running on a desktop. It was further separated into JRE (Java Runtime Environment) for running Java, and JDK (Java Development Kit) for compiling and running Java.

  • The micro edition J2ME for mobile and embedded devices.

  • The enterprise edition J2EE with enterprise features added to J2SE. Each J2EE configuration includes a complete J2SE installation.

For marketing purposes, the “2” was removed in 2006 and the configurations were named JSE (or JDK, which is JSE plus development tools), JME, and JEE, respectively. In 2018, JEE was moved to the Eclipse foundation and renamed Jakarta EE. The Java language substantially changed from Java 7 to Java 8. We will be using all the modern features of Java 8 in our explanations and code examples.

Java of course continues to be developed. While the latest version of Jakarta EE was 8 while writing this book, and the underlying Java standard edition was version 8 as well, the latest JavaSE (JSE) version you could download was 13. We won’t be talking about JavaSE versions 9 or higher in this book.

While knowledge of the Java standard edition JSE version 8 is considered a prerequisite in this book, for readers who are only partly familiar with Java 8, the following new features are worth an investigation before you move to subsequent chapters:
  • Functional interfaces

  • Lambda calculus (unnamed functions)

  • The streams API for working with collections and maps

  • The new date and time API

We will be using these where appropriate in the book’s examples.

The specifications that describe the parts of Java EE/Jakarta EE tell what each part can do and how it does it, and they keep track of new versions. Java EE/Jakarta EE 8 includes sub-technologies also closely described by exact version numbers. We list them here and include a short description of what each technology does. Note that the list is not exhaustive—it does not include some more advanced APIs, which you can learn about if you look at the official documentation.
  • Java MVC 1.0 - JSR-371: This is our main concern in this book.

  • Enterprise Java Beans EJB - Version 3.2: EJBs represent entry points for business logic. Each EJB plays the role of a component in the overall Jakarta EE architecture and is responsible for a dedicate business task. EJBs allow developers to add security, transactional features, JPA features to communicate with databases, and web services functionality, and they can also be entry points for messaging.

  • Java Server Faces JSF - Version 2.3: JSF is the component-based dedicated primary web frontend technology to be used for browser access. Using Java MVC is somewhat an alternative approach, and nobody hinders you from mixing them freely. JSFs usually communicate over EJBs with the business logic.

  • RESTful Web-Services JAX-RS - Version 2.1: REST (REpresentational State Transfer) is the original HTTP protocol that defines reading and writing resources. It recently gained increased attention for single page web applications, where the frontend page flow is completely handled by JavaScript running in the browser.

  • JSON Processing JSON-P - Version 1.1: JSON (JavaScript Object Notation) is a lean data-format particularly useful if a considerable amount of the presentation logic gets handled by JavaScript running in the browser.

  • JSON Binding JSON-B - Version 1.0: This technology simplifies mapping between JSON data and Java classes.

  • Web Sockets - Version 1.1: Provides a full-duplex communication between web clients (browsers) and the Jakarta EE server. Other than “normal” access via HTTP, web sockets allow for the server to send messages to a browser client as well!

  • JPA - Version 2.2: The Java Persistence API provides high-level access to databases.

  • Java EE Security API - Version 1.0: A new security API that didn’t exist prior to Jakarta EE 8. It includes an HTTP authentication mechanism, an identity store abstraction for validating user credentials and group memberships, and a security context API that programmatically handles security.

  • Java Messaging Service JMS - Version 2.0: This is about messaging, which means messages can be produced and consumed asynchronously. A message sender produces and issues a message and can instantaneously continue its work, even when the message gets consumed later.

  • Java Transaction API (JTA) - Version 1.2: JTA makes sure that processes that combine several steps acting as a unit can be committed or rolled back as a whole. This can become tricky if distributed partners are involved. JTA helps a lot here to ensure transactionality even for more complex systems.

  • Servlets - Version 4.0: Servlets are the underlying technology for server-browser communication. You usually configure them only once at the beginning of a project. We describe servlets where necessary to get other technologies to run.

  • Context And Dependency Injection CDI - Version 2.0: CDI allows developers to bind contexts to elements that are governed by a dedicated lifecycle. In addition, it injects dependencies into objects, which simplifies class associations. We will use CDI to connect JSF elements to the application logic.

  • JavaMail - Version 1.6: Provides facilities for reading and sending email. This is just an API. For an implementation, you can for example use Oracle’s reference implementation: https://javaee.github.io/javamail/

  • Bean Validation - Version 2.0: This allows developers to restrict method call parameters to comply with certain value predicates.

  • Interceptors - Version 1.2: Interceptors allow you to wrap method calls into invocations of interceptor classes. While this can be done by programmatic method calls as well, interceptors allow developers to do it in a declarative way. You typically use interceptors for crosscutting concerns like logging, security issues, monitoring, and the like.

  • Java Server Pages JSP - Version 2.3: JSPs can be used to establish a page flow in server-browser communication. JSP is an older technology, but you still can use it if you like. You should however favor JSFs over JSPs, and in this book we don’t handle JSPs.

  • JSP Standard Tag Library JSTL - Version 1.2: Tags used in conjunction with JSPs for page elements.

Java EE/Jakarta EE runs on top of the Java Standard Edition (SE), so you can always use any classes and interfaces of the Java SE if you program for Java EE/Jakarta EE. A couple of technologies included within the Java Standard Edition SE play a prominent role in a Java Enterprise Edition environment:
  • JDBC - Version 4.0: An access API for databases. All major database vendors provide JDBC drivers for their product. You could use it, but you shouldn’t. Use the higher-level JPA technology instead. You’ll get in contact once in a while, because JPA under-the-hood uses JDBC.

  • Java Naming and Directory Interface JNDI: In a Jakarta EE 8 environment, objects will be accessed by other objects in a rather loose way. In modern enterprise edition applications, this usually happens via CDI, more precisely, via dependency injection. Under the hood, however, a lookup service plays a role, governed by JNDI. In the past, you’d have to directly use JNDI interfaces to programmatically fetch dependent objects. You could use JNDI for Jakarta EE 8, but you normally don’t have to.

  • Java API for XML Processing JAXP - Version 1.6: A general-purpose XML processing API. You can access XML data via DOM (complete XML tree in memory), SAX (event-based XML parsing), or StAX. This is just an API. Normally you’d have to also add an implementation, but the Jakarta EE server does this automatically for you.

  • Streaming API for XML StAX - Version 1.0: Used for streaming access to XML data. Streaming here means you serially access XML elements on explicit demand (pull parsing).

  • Java XML Binding JAXB - Version 2.2: JAXB connects XML elements to Java classes.

  • XML Web Services JAX-WS - Version 2.2: Web services remotely connect components using XML as a messaging format.

  • JMX - Version 2.0: JMX is a communication technology you can use to monitor components of a running Jakarta EE application. It is up to the server implementation what information is available for JMX monitoring, but you can add monitoring capabilities to your own components.

The specifications are handled by a community process, and vendors have to pass tests if they want to be able to say their server products conform to a certain version of Jakarta EE (or one of its predecessors, JEE or J2EE). If you are interested, the corresponding online resources provide information about it. As a start, enter “java community process jcp” or ”java eclipse ee.next working group” into your favorite search engine.

The Java Enterprise Edition was initially developed by Sun Microsystems and was called J2EE. In 2006, the naming and versioning schema was changed to JEE, and after J2EE version 1.4 came JEE version 5. Since then, major updates happened and versions JEE 6, JEE 7, and JEE 8 were released. In 2010, Sun Microsystems was acquired by Oracle corp. Under Oracle, versions JEE 7 and JEE 8 were released. In 2017, Oracle Corporation submitted Java EE to the Eclipse Foundation, and the name was changed to Jakarta EE 8.

As of the beginning of 2020, the transition from JEE 8 to Jakarta EE 8 was an ongoing process. So depending on when you read this book, it still could be that for online research about Jakarta EE 8, you have to consult pages about both JEE 8 and Jakarta EE 8. This is something you should keep in mind. To keep things simple in this book, we will only talk about Jakarta EE.

When this book was written, there were not many Jakarta EE 8 servers released. There are basically the following:
  • GlassFish Server, Open Source Edition, from Oracle Inc.

  • WildFly Server, from Red Hat

  • JBoss Enterprise Application Platform, from Red Hat

  • WebSphere Application Server Liberty, from IBM

  • Open Liberty, from IBM

These servers have different licensing models. GlassFish, WildFly, and Open Liberty are free. This means you can use them without charge, both for development purposes and for production. To run the JBoss Enterprise Application Platform, you need a subscription, although the sources are open. WebSphere Application Server Liberty is proprietary.

In this book, we will talk about running Java MVC inside the GlassFish server, open source edition, version 5.1. Due to the nature of Jakarta EE 8, a transition to other servers is always possible, although you’ll have to spend a considerable amount of time changing the administration workflow.

GlassFish, a Free Java Server

There are several free Java EE/Jakarta EE servers you can use for evaluation and development. The GlassFish server is a particularly good choice, especially for learning purposes, because it is open source.

Getting GlassFish

The latest version as of the writing of this book is 5.1, and you can download it from the following:
https://projects.eclipse.org/
      projects/ee4j.glassfish/downloads

Choose the “Full Profile” variant.

Note

At the time this book is published, there are likely later versions for GlassFish available. You could try versions greater than 5.1 and you might not have any problems installing and using them with this book. But to avoid any chance of problems, it will always be possible to use an archived GlassFish 5.1 installer.

After you download the ZIP file, extract it anywhere on your file system. We will henceforth call the installation folder GLASSFISH_INST_DIR. Before GlassFish can be started, you must make sure you have Java 8 JDK installed on your system.

Note

JDK 8 is a requirement for GlassFish 5.1. You cannot use a later version and you should not use an earlier version.

Get the JDK from one of the following links (for the www.oracle.com variant, you must get a paid subscription for commercial projects):
https://www.oracle.com/java/technologies/javase/
      javase-jdk8-downloads.html
https://jdk.java.net/java-se-ri/8-MR3

The jdk.java.net variant points to the OpenJDK distribution. For Linux, chances are good your distribution’s package provider has a pre-built Java installation package for you.

If JDK 8 is not your system default, you can check by entering java -version in a console window. You must add the following line
REM Windows:
REM Note, if the JDK_INST contains spaces, wrap it
REM inside "..."
set AS_JAVA=JDK_INST
# Linux:
AS_JAVA="JDK_INST"

inside the GLASSFISH_INST_DIR/glassfish/config/asenv.conf (Linux) or GLASSFISH_INST_DIR/glassfish/config/asenv.bat (Windows) file, where you must replace JDK_INST with the installation folder of the JDK 8 installation.

You can now check the installation in a console window. Change the user directory (current directory) to the GlassFish installation folder and then use asadmin to start the server:
REM Windows:
chdir GLASSFISH_INST_DIR
binasadmin start-domain
# Linux:
cd GLASSFISH_INST_DIR
bin/asadmin start-domain
The output should be something like this:
Waiting for domain1 to start .
Successfully started the domain : domain1
domain Location: [...]/glassfish/domains/domain1
Log File: [...]/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.

You can also check the indicated log file to see whether the startup worked correctly. You can open your browser at http://localhost:4848 to see whether the web administrator is available (it should be).

Once you verify that the server started up correctly, you can stop it if you like. To do so, enter the following:
REM Windows:
binasadmin stop-domain
# Linux:
bin/asadmin stop-domain
Note

In the rest of this chapter, we assume that you entered cd GLASSFISH_INST_DIR to change to the GlassFish installation directory. I will also stop distinguishing between Windows and Linux and write bin/asadmin, which on Windows should be binasadmin.bat.

The GlassFish server has three administrative frontends:
  • A shell (or windows command prompt) frontend

  • A GUI frontend for browser access

  • A REST HTTP frontend

GlassFish Shell Administration

The shell frontend works via the bin/asadmin script, which you can call from a shell (or a windows command prompt). This command is extremely powerful; it contains hundreds of options and subcommands. We do not list them all here, so for a complete online list, enter “oracle glassfish server administration guide” in your favorite search engine.

As a starting point, the asadmin command also provides a “help” functionality. To see it, enter one of the following:
bin/asadmin help
bin/asadmin -?
Where the first variant (help) opens a MORE pager. To list all the subcommands, enter the following:
# Note: server must be running!
bin/asadmin list-commands
To see the help for a particular subcommand, you can write one of the following:
bin/asadmin help <SUB-COMMAND>
bin/asadmin -? <SUB-COMMAND>

Where you substitute the name of the subcommand for <SUB-COMMAND>.

Note

In order for many subcommands to run properly, the server must be running as well. In the following discussion, we assume that the server has started before you issue any subcommands.

There is also a multimode session, where a special subshell is opened. In this subshell you can enter subcommands directly without prepending the bin/asadmin. To start a multimode session, enter the following without arguments:
bin/asadmin
You can also use the multimode subcommand to start a multimode session:
bin/asadmin multimode
The subcommand allows for an optional --file <FILE_NAME> argument, which causes the specified file to be read in as a list of subcommands to be executed sequentially:
bin/asadmin multimode --file commands_file.txt
The file path is relative to the current working directory. In the following paragraphs, we show a list of the most useful options and subcommands. The most useful general options are shown in Table 2-1. You add them as in bin/asadmin --host 192.168.1.37 list-applications .
Table 2-1

General Options

Option

Description

--host <HOST>

Specifies the host where the server is running. If you don’t specify it, localhost will be used.

--port <PORT>

The administration port. The default is 4848

--user

<USER_NAME>

Uses the specified user to authenticate to the server. Use this if you restricted access to the asadmin utility. The default is the admin user.

--passwordfile

<FILE_NAME>

If you restricted access to the asadmin utility, and you want to prevent a user password from being prompted, you can specify a file with password information instead. For details, see the output of bin/asadmin   -?.

For a complete list of the options you can add to the asadmin command, see the output of bin/asadmin -?.

Subcommands used to inquire various types of information from the server are shown in Table 2-2. You enter them as in bin/asadmin list-applications (obviously, the list will be empty if you haven’t installed any applications yet).
Table 2-2

Inquiring Information

Subcommand

Description

version

Outputs the GlassFish server version.

list-applications

Lists all applications deployed and running on the server.

list-containers

Containers embrace components (modules, if you like) of a certain type. Use this subcommand to list all the containers running in the server.

list-modules

Lists all OSGi modules running in the server. We won’t be talking about OSGi in this book, but in case you are interested, GlassFish incorporates an Apache Felix OSGi module management system. You can administer GlassFish components also via an OSGi shell named “Gogo,” which needs more configuration work to run.

list-commands

Lists all the subcommands. If you add --localonly the server doesn’t have to be running and only subcommands that can be issued with the server not running will be listed.

list-timers

Shows all timers. We don’t talk about timers in this book.

list-domains

Lists all domains. In this book, we will be using the preinstalled default domain, called domain1, so this will be the only entry showing up here.

After you perform the installation of the GlassFish server, there will be one administration user named admin without a password. Not having a password makes administrative tasks easy, but it will also leave your server insecure. To remedy that and give the admin user a password, enter the following:
bin/asadmin change-admin-password

You will then be asked for the actual password, which is empty so just press Enter. Then enter the new password twice.

Once the admin user has a password, you will have to enter the password for most asadmin subcommands.

To start a domain means to start the GlassFish server. We could have several domains in one GlassFish server, but a multi-domain setup is left for advanced users, so we’ll go with the single domain1 domain, which is installed by default.

To start, stop, or restart the GlassFish server, enter one of the following commands:
bin/asadmin start-domain
bin/asadmin stop-domain
bin/asadmin restart-domain

All three subcommands take an optional domain name as a parameter (for example, domain1 or domain2), but since we have only one default domain, it can be left off here.

To see the uptime of the server, which is the time that has elapsed since the default domain started, enter the following:
bin/asadmin uptime
The Jakarta EE GlassFish server comes with a built-in database. This comes in handy for development purposes, although you probably won’t use this database for production setups. This database is an Apache Derby database. It does not run by default when the GlassFish server is started. Instead, to start and stop the database, enter the following:
bin/asadmin start-database
bin/asadmin stop-database

where the database port by default reads 1527.

GlassFish GUI Administration

After you start the GlassFish server, a GUI console is provided and you should use it to open the following URL in a browser:
http://localhost:4848
The GUI will then show up, as seen in Figure 2-1.
../images/499016_1_En_2_Chapter/499016_1_En_2_Fig1_HTML.jpg
Figure 2-1

Browser GUI administration

We don’t talk about details of the GUI administration here. We will, however, use and describe it once in a while in this book, and the help button on the top-right corner is a good starting point for your own experiments and investigations.

Note

Many asadmin operations that you can enter in a terminal have their counterparts in the admin GUI.

GlassFish REST Interface Administration

The GlassFish Jakarta EE 8 server provides a REST interface that you can use to investigate and control the server. You can issue the following to see the domain logs via REST for example:
curl -X GET -H "Accept: application/json"
http://localhost:4848/monitoring/domain/view-log/details
Note

For this to work, the curl utility must be installed on your system. Alternatively, you can use any other REST client (Firefox REST-client add-on, REST Client for Eclipse, and others).

We investigate a couple of examples. To find more in-depth information about this interface, enter “rest interface administer glassfish” in your favorite search engine. Also, we use the jq tool to provide a pretty format output of the generated JSON data. For jq, there are installers for Linux and Windows.

The administrative REST interface is subdivided into two parts for configuration and monitoring:
http://host:port/management/domain/[path]
http://host:port/monitoring/domain/[path]
For a vanilla GlassFish installation, the host is localhost and the port is 4848. For [path], you must substitute a resource identifier. For example, to see the log entries, you enter the following:
curl -X GET -H "Accept: application/json"
http://localhost:4848/management/domain/view-log

(Remove the backslash if you enter this on one line.)

The REST interface is very extensive. You can query a lot of properties using REST’s GET verb, and you can alter resources using POST or PUT. As a starting point, you can investigate the verbose output of REST capabilities you will get once you enter the following:
curl -X GET -H "Accept: application/json"
http://localhost:4848/management/domain
The output will for example include the following:
"commands": [
  ...
  {
    "path": "list-commands",
    "method": "GET",
    "command": "list-commands"
  },
  {
    "path": "restart-domain",
    "method": "POST",
    "command": "restart-domain"
  },
  {
    "path": "uptime",
    "method": "GET",
    "command": "uptime"
  },
  {
    "path": "version",
    "method": "GET",
    "command": "version"
  }
  ...
]
There are lots of others. To see version and uptime, you enter the following:
curl -X GET -H "Accept: application/json"
   http://localhost:4848/management/domain/version | jq .
curl -X GET -H "Accept: application/json"
   http://localhost:4848/management/domain/uptime | jq .

If you use a browser and enter REST URLs there, you get more information about REST resources. If you open a browser and enter http://localhost:4848/management/domain/version, you will get an HTML variant of this CURL output. Both also tell us about child resources.

So this code, for example, shows us about commands referring to installed application:
curl -X GET -H "Accept: application/json"
  http://localhost:4848/management/domain/applications |
jq .
It tells us that, for the actual list, we have to enter the following:
curl -X GET -H "Accept: application/json"
  http://localhost:4848/management/domain/applications/ list-applications |
 jq .
(No line break after applications/.) It tells us about attributes. To get more verbose output, we can add a ?long=true, as in:
curl -X GET -H "Accept: application/json"
  http://localhost:4848/management/domain/applications/
  list-applications?long=true | jq .

Using a Preinstalled Java Server

Java MVC applications usually reside in WAR files (ZIP files ending with .war), so they may be installed on any Jakarta EE compliant server.

For this reason, you don’t have to use GlassFish. In this book, we will use GlassFish, but if you prefer a different Jakarta EE 8 server, you may use it. Of course, you have to learn how to administer that server by consulting its manual.

Note

If you target a proprietary server, it is generally not recommended to start development with a different product from a different vendor. You should at least try to develop with a free variant of the same server, or try to get a developer license. To learn Jakarta EE 8 first using GlassFish and later switching to a different product or vendor is a reasonable approach, though.

Learning Java for Enterprise Applications

In order to learn the Java language (or the standard edition APIs) or improve your skills, you can choose among a wealth of books and online resources. A good place to start looking is the official Java tutorial from Oracle, found at
https://docs.oracle.com/javase/tutorial/
Real-world corporate projects may require you to look at other technologies from the Java EE/Jakarta EE technology stack. There is also a tutorial for the enterprise edition Java EE/Jakarta EE, which you can find at:
https://javaee.github.io/tutorial/toc.html

You may also want to consult the book Beginning Jakarta EE: Enterprise Edition for Java: From Novice to Professional (ISBN: 978-1484250785) from the same author. Here, we mainly talk about Java MVC and handle other Java EE/Jakarta EE technologies only where appropriate and needed.

RESTful Services

There is a good reason to also briefly talk about JAX-RS, even though it’s an exception to the limitation of this book’s scope to Java MVC. JAX-RS is the subtechnology of Java EE/Jakarta EE handling RESTful services. As a matter of fact, Java MVC sits on top of JAX-RS, which was a clever decision of the framework programmers. Not only does it allow developers to let Java MVC very cleanly integrate with the rest of the Java EE/Jakarta EE framework, it also gives a straightforward clue as to how to mix Java MVC development techniques and more fine-grained client-server communication using AJAX and JSON data snippets.

REST is an acronym for representational state transfer . It is an architectural style for web related operations. Clients use a predefined set of operations or HTTP methods on data—GET, POST, PUT, and DELETE (and a few more) for communicating with servers. As no state is involved, the client communicates using one of the verbs GET, DELETE, POST, PUT, and so on, and immediately after the server has performed the operation and/or returned data, the server forgets about the communication step. The name “representational state transfer” stems from the fact that, from the client’s point of view, the representation of data inquired from the server changes between communication steps (or might change).

The communication verbs have been part of the HTTP specification since the infancy of the web. In more detail, we have the following verbs:
  • GET: Used to retrieve a resource. Resources are identified by URIs, so the communication might be described by something like GET http://some.server.com/myclub/member/37. A GET operation is not allowed to change any data (except for access statistics and the like), and it must be idempotent. That means a second GET using the same URI with no intermediate operations between those two GETs must return exactly the same data. Note that GET operations were widely abused for any kind of operations, including changing data. With REST we return to the roots and data must not be changed.

  • DELETE: Used to delete information. Again the resource in question gets addressed by an URI, so you write DELETE http://some.server.com/myclub/member/37. A DELETE must be idempotent, which means deleting again using the same URI must not change the data. In this case, the second DELETE is of course superfluous; deleting what was already deleted is not supposed to do anything. As a characteristic of REST concerning a second DELETE, the server must not return an error message, but just ignore the request instead.

  • POST: Used to post new information. POSTs commonly happen when the user submits a form. POSTs are not idempotent, so a second post using the same data will lead to a second data set on the server side. A post might be described by POST http://some.server.com/mycl ub/member/37 [data], where [data] stands for the transmitted data, usually in the form of XML or JSON, passed over in the transmitted message body.

  • PUT: Used to store data. If the resource described by the data already exists, the resource will be altered according to the data. If it does not exist, the server might decide to act as if a POST were specified. A PUT is idempotent, PUTting again using the same input data will not change the data on the server.

The other verbs are less frequently used in real-world applications. HEAD is for retrieving metadata about a resource (information about it, but not the resource itself). Using a TRACE , you can see what happens to the data on the way to the server. This is more a technical operation and does not pay particular attention to the data payload. A PATCH is like a PUT with partial data. PUTs, with the complete information, are more frequently used over PATCHs. The OPTIONS verb requests the server’s capability for a dedicated resource (like telling what can be done with the resource). A CONNECT is used to establish transparent tunnels on the server side. Again this is more a technical facility and does not reveal anything about the transmitted data.

To define a REST endpoint, you write a Java class with annotation javax.ws.rs.Path added at class and/or method level. For example, consider a REST controller that returns the current date and time as JSON:
package book.javavmc.restdate;
import java.time.ZonedDateTime;
import javax.ws.rs.*;
/**
 * REST Web Service
 */
@Path("/d")
public class RestDate {
    @GET
    @Path("date")
    @Produces("application/json")
    public String stdDate() {
        return "{"date":"" + ZonedDateTime.now().toString() +
        ""}";
    }
}

The @Path annotations merge, so in the end, we get an endpoint URL such as http://localhost:8080/theAppName/d/date.

You will start developing your first Java MVC application soon. This is why I show you this first code snippet without explaining how to build and deploy it. A Java MVC controller looks very similar:
package book.javavmc.somecontroller;
import java.util.List;
import javax.inject.Inject;
import javax.mvc.Controller;
import javax.mvc.Models;
import javax.ws.rs.*;
@Path("/pets")
@Controller
public class PetshopController {
    @Inject
    private Models models;
    @GET
    public String showIndex() {
         final List<Pet> pets = ...;
         models.put("pets", pets);
         return "index.jsp";
    }
}

You can see that we again use javax.ws.rs.Path to define an endpoint. We will later see that the main differences between Java MVC and JAX-RS are the @Controller annotation and that the action method returns the name of the next view page instead of data.

Note

You will find more online information about JAX-RS, including the official specification, if you enter “jax-rs” in your favorite search engine.

Exercises

  • Exercise 1: Describe the relationship between JSE and Java EE/Jakarta EE.

  • Exercise 2: True or false? Java MVC can run directly inside a PC’s or server’s operating system.

  • Exercise 3: True or false? Java MVC is a Jakarta EE server.

  • Exercise 4: True or false? Jakarta EE is a competitor of Java EE.

  • Exercise 5: True or false? There is no difference between OpenJDK 8 and Oracle’s JSE 8.

  • Exercise 6: True or false? GlassFish can be used for commercial products without paying for a license.

  • Exercise 7: Why do we use GlassFish in this book?

  • Exercise 8: True or false? PURGE is an HTTP verb.

  • Exercise 9: Describe the relationship between Java MVC and JAX-RS.

Summary

Java MVC is accompanied by the infrastructure that a Java Enterprise Edition server (Java EE or Jakarta EE) provides. In a corporate environment, a programming language and software platform like Java has to cover a couple of needs that are important to run a business. It has to be able to connect to one or more databases, reliably establish communication with other IT-based systems in the same company or with connected businesses, and it has to be powerful enough to reliably handle input and perform calculations based on input and database data, and present the appropriate output to clients.

The Jakarta EE 8 server runs on and depends on Java. There are several reasons that Java became so successful:
  • The same Java program can run on different operating systems.

  • Java runs in a sandboxed environment. This improves execution security.

  • Java can be easily extended with custom libraries.

  • The Java language was extended only slowly. While a slow evolution means new and helpful language constructs may be missing in the most current version, it helps developers easily keep track of new features and thoroughly perform transitions to new Java versions in longer running projects. Furthermore, with only a small number of exceptions, Java versions were backward-compatible.

  • Java includes a garbage collector that automatically cleans up unused memory.

Java continues to be developed. While the latest version of Jakarta EE was 8 while writing this book, and the underlying Java standard edition was version 8 as well, the latest JavaSE (JSE) version you could download was 13. We won’t be talking about JavaSE versions 9 or higher in this book.

The specifications that describe the parts of Java EE/Jakarta EE tell what each part can do and how it does it, and they keep track of new versions. Java EE/Jakarta EE 8 includes sub-technologies, which are also closely described by exact version numbers. The specifications are handled by a community process, and vendors have to pass tests if they want to be able to say their server products conform to a certain version of Jakarta EE (or one of its predecessors, JEE or J2EE).

The Java Enterprise Edition was initially developed by Sun Microsystems and was called J2EE. In 2006, the naming and versioning schema was changed to JEE, and after J2EE version 1.4 came JEE version 5. Since then, major updates happened and versions JEE 6, JEE 7, and JEE 8 were all released. In 2010, Sun Microsystems was acquired by Oracle corp. Under Oracle, versions JEE 7 and JEE 8 were released. In 2017, Oracle Corporation submitted Java EE to the Eclipse Foundation, and the name was changed to Jakarta EE 8.

In this book, we will talk about running Java MVC inside the GlassFish server, open source edition, version 5.1. Due to the nature of Jakarta EE 8, a transition to other servers is always possible, although you have to spend a considerable amount of time changing the administration workflow. GlassFish provides three administrative interfaces—command-line tools for a shell or console, a web administrator GUI, and an administrative REST interface.

Java MVC sits on top of JAX-RS, which was a clever decision of the framework programmers. Not only does it allow Java MVC to very cleanly integrate with the rest of the Java EE/Jakarta EE framework, it also gives a straightforward clue as to how to mix Java MVC development techniques and more fine-grained client-server communication using AJAX and JSON data snippets. REST controllers and Java MVC controllers look very similar.

In the next chapter, we handle the development workflow suitable for this book and other Java MVC projects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.163.58