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 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.
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.
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.
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.
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.
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
Choose the “Full Profile” variant.
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.
JDK 8 is a requirement for GlassFish 5.1. You cannot use a later version and you should not use an earlier version.
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.
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 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).
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.
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.
Where you substitute the name of the subcommand for <SUB-COMMAND>.
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.
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 -?.
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. |
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.
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.
where the database port by default reads 1527.
GlassFish 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.
Many asadmin operations that you can enter in a terminal have their counterparts in the admin GUI.
GlassFish REST Interface Administration
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.
(Remove the backslash if you enter this on one line.)
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.
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.
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
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).
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.
The @Path annotations merge, so in the end, we get an endpoint URL such as http://localhost:8080/theAppName/d/date.
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.
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 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.