
Who is this course for? What are the prerequisites (software)? What will you learn?
The Jakarta Enterprise Edition 8 is a huge eco-system of interrelated API's and Technologies which we will review here.
As an expatriate living abroad I want to create an online database of all charities (non-profits) that operate in my “home country”.
Our example administration web-app will allow charities to "register" with our online DB and send us their official tax registration forms
Charities should be able to register their information online and provide attached files such as non-profit tax registration status and address details
Our specific example will have to use i8n and localization for specific language groups and regions
Because we handle sensitive information our project will have to be really secure
Installing Apache Maven
Downloading Apache Maven
Welcome to Apache Maven
Download MariaDB Server
Download Eclipse Technology that is right for you
Git Downloads
Git
Java Platform, Standard Edition 11 Reference Implementations
Production and Early-Access OpenJDK Builds, from Oracle
Download OpenJDK 11 zip
Unzip Archive
Setup JAVA_HOME environment variable
Add /bin directory to PATH
Confirm Java setup in command prompt
Download the Eclipse Installer
Start the Eclipse Installer executable
Select the package to install
Select your installation folder
Launch Eclipse & Confirm Eclipse setup with OpenJDK 11
Confirm Eclipse is set up for JEE 8
Go to Git Downloads page
Select and download Git for Windows 10
Run the executable (Setup)
Verify Git Bash in Windows 10
Prerequisite is that you have a Github account :
Go to github
Type a user name, your email address, and a password.
Choose Sign up for GitHub, and then follow the instructions.
Go to github new in Browser
Repository Name & Description
Add README, .gitignore (maven) , license
Do not select Azure Pipelines
Import the Github Repository into Eclipse
We will select the latest version of Maven
Download the zip file
Unzip it to our C:\ drive
Update our Windows Environment variables
Confirm Maven Setup through Command Line
Starting with our Github created project that we imported into Eclipse in one of our previous lessons
We will create a Maven POM Root Project Structure in Eclipse with the help of the root-pom Archetype stackoverflow how-to-create-an-empty-multi-module-maven-project and Eclipse
Look at Maven Settings in Eclipse (.m2 & settings.xml)
We will match Eclipse Maven with Command Line Maven so that we do not see differences when switching between command line and Eclipse execution of maven build scripts
Confirm Maven Setup through Command Line
We will select the Tomcat 9 release downloads page
We will choose the 64 bit zip core download
Unzip win64 zip file
Run Tomcat 9 from the command line
Confirm setup in the Tomcat Admin Web Page
Prerequisite is Java 8 or higher (JAVA_HOME) - OpenJDK 11 for us
Add Tomcat bin directory to PATH environment variable
Set CATALINA_HOME environment variable
Scripts: startup.bat and shutdown.bat
Set up a Tomcat Admin User through the web page Admin Install
Defining a Server in Eclipse
Configuring the Server
Adding Applications to the Server
Running the Server
We will select the latest stable MariaDB release:
We will choose Windows 10
We will choose the latest Stable Release
We will follow the instructions for MSI package installer Download .MSI
Run MSI in Windows Explorer
Confirm setup through command line
Windows -> Preferences -> Data Management
Driver Definitions -> Add Generic JDBC
Download MariaDB JDBC Drivers (jars)
Specify DB Connection Details
Create new DB Connection in Data Source Explorer & Test Connection
Update Maven Root POM project to use JEE 8
Create a new Jakarta JEE 8 Web App
Using Maven JEE Web Archetype to create a new maven module
External Resource Link
Notice the archetype is old and can be updated to the latest by open source volunteers
Update generated Web App to use JEE 8
Update the Maven Project using the Eclipse option
Update the Web App Natures in Eclipse
Update web.xml and all related Eclipse Facets
Add Tomcat 9 runtime in Facet
Run the Web App on Tomcat 9
Demonstrate that the JSP Hello Page Show
Jakarta JEE 8 Web app Git Finish Branch
Design a database that conforms to User Story
Build this database with SQL Scripts
Use JEE 8 to connect, access and manipulate the data in this database
Recreate application user and Charity DB
Create Charity Table
Create Charity Category Table and relationships
Create Charity Program Table and relationships
Populate Categories and Programs with scripts
Update our Maven archetype JEE 8 Web Application in Eclipse:
Update the generated JEE 8 WebApp Module
Introduce a “Hello World” Servlet
Mapping URLs to Web Components
Running the “Hello World” Servlet
Git Start Branch (External Resources)
Git Finish Branch (External Resources)
Use our Hello World Servlet App
Expand & Debug the JSP in Eclipse
Debug the back-end Java Servlet code in Eclipse
Add logging with Apache Log4J
Multiparameter Form
Here our servlet will “write” out multiple checkbox parameters to an input form.
See external resources
Walkthrough of Configuring our jee8 web application using INIT Parameters:
Configuration parameters
Servlet parameters
Annotations
See external resources
Uploading files with a JEE 8 Servlet:
Configure a Servlet for File Uploads - @MultipartConfig
Generated File Upload Input Form
We specify the location on the server where the file will be uploaded to
See external resources
Introducing Thread safety in JEE 8 Web Apps:
Volatile Fields
Synchronized Statements
See external resources
JSP is basically HTML:
Add JSP Maven Dependencies for JEE 8
Servlets should not build HTML Streams
JSP compile lifecycle
We learn about the JSP page directive at the top of the page
Directives, Declarations, Scriptlets and Expressions
JSP Code Comments
Java Package/Class imports in JSP
JSP directives in more detail
We learn how to use implicit variables (objects) in JSP
We translate our “Hello World” Servlet examples into JSP
Then we debug and step into these example JSPs
We learn why using embedded Java in JSP is a bad idea
See external resources
Move JSP properties to web.xml
Forward from the Controller Servlet using requestDispatcher
Remove all business logic in JSP and just have View Layer Logic
Run and debug our new MVC web app
See external resources
Bootstrap is a JavaScript Framework for the Client Presentation Layer released by Twitter
There are multitudes of client side JavaScript Frameworks and they come and go like fashion (every 6 months)
Bootstrap 3 and lower can be integrated with JQuery another popular older JavaScript framework for interactivity on the client
See external resources
Using Jakarta Expression Language 3.0 in JSP
Introducing The Jakarta EL 3.0 (Jakarta EE 8)
Understanding Jakarta Expression Language 3.0
A look at Evaluation Expressions (EL 4.0 documentation)
Writing (code) with the EL Syntax
See external resources
We start working with JSTL 1.2 Tags
We introduce Date Formatting in our Charity Registration Application
We replace embedded Java functionality with Core tags. (Loops, Conditionals, Iteration) in our Charity Registration Application
We look at the latest official Jakarta JSTL 2.0 Specification and compare it to the Oracle JSTL 1.2 documentation
We also delve deeper into the relationship between JSTL 1.2 and Tomcat 9.x
See external resource
JSF is a Java-based web framework for creating user interfaces (UIs) in web applications. (Struts, Spring Web)
It's a component-based framework that simplifies Java web app development.
JSF 2.3 is part of Jakarta EE, the successor to Java EE.
Developed as an open-source project under the Eclipse Foundation.
See external resource
Why sessions are necessary?
Working with cookies and URL parameters
How to store data in a session
See external resources
Storing complex data structures in sessions
Making sessions useful
We use the session activity example to look at storing a complex serializable class in the session
We look at the Internationalization Tags library official documentation
We also learn how to put Internationalization Library Tags to use in our example Charity Registration Application by adding an in memory Address DB
We introduce Date Formatting and Local Language Formatting in our country specific Charity Registration Address DB
Using the Java Standard Tag Library - Part 3
1. Creating Custom Tag Libraries
Simplify JSP code
Encapsulate functionality
Improve code organization
2. XML Processing Tag Library
Efficient XML handling
Transformations and manipulations
Enhance data presentation
Objective:
In this lesson, we will enhance our charity-registration module by implementing user authentication. This is a crucial step to secure our application and ensure that only authorized users can access it.
Key Steps:
Add a <session-config> entry to our web.xml.
Implement an in-memory database to store user credentials.
Create a login page and servlet for user authentication.
Adding custom login to our JEE 8 Web App Module
External resource
jee8-login-jstl git branch
External resource
Understand the concept of session listeners in Jakarta Servlet API.
See how listeners can detect various session activities.
Look at examples of listener interfaces, such as `HttpSessionAttributeListener`, `HttpSessionBindingListener`, and `HttpSessionIdListener`.
Look at how to implement session listeners through code and annotations
How to cluster an application that uses sessions
What is Clustering ?
Definition and purpose of clustering in Tomcat.
How Session Ids are used in Clustering
Explanation of how session IDs play a role in clustering.
Understanding how Sessions get replicated in a Cluster
Overview of the process of session replication in a Tomcat cluster
Learn more here:
See external resource link
Review our Session concepts
Sessions used to identify the Client on the Server
Major security concerns related to sessions as described by owasp.org
We learned how to use Sessions in our Charity Registration Web Application
We did this by adding a login page and an in-memory database of user sessions
Lastly we learned about the concept of server clustering in relation to the Tomcat web server that we are using
Tomcat 9 Clustering Course Documentation:
Tomcat 9 Clustering Git Branch
Leveraging Filters in Jakarta EE 8 Web Development
The Role of Filters : Understand the fundamental purpose of filters in web applications.
Creating and Configuring Filters: Learn how to create and configure filters to intercept
and process requests and responses.
Proper Filter Ordering: Discover the importance of ordering filters correctly to
ensure desired behavior.
Filter Ordering Example: Gain insight into filter order through a code example.
Practical Filter Applications: Explore real-world scenarios where filters
simplify tasks, such as streamlining authentication.
Making your Jakarta JEE8 Web Application interactive with WebSockets
1. Evolution from Ajax to WebSockets
- Dive into the transition from Ajax to WebSockets.
2. Understanding WebSocket API's
- Explore the WebSocket APIs in JavaScript and Java.
3. Creating Multi-player Games with WebSockets
- Learn how to build multiplayer games using WebSockets.
4. Using WebSockets to communicate in a Cluster
- Understand how WebSockets can enhance communication within a cluster.
5. Adding Chat Support to the Charity Registration Web App
- Enhance your Charity Registration Web App with WebSocket-powered chat support.
Jakarta JEE8 WeSockets Branch
Introduction to Logging - Logging Essentials:
Crucial for software development.
Records and monitors application behavior.
Frameworks in Focus:
Integration of Java logging frameworks: Apache Log4j and SLF4J.
Why Logging Matters:
Debugging, troubleshooting, and monitoring in production.
Valuable for tracking errors and gaining insights.
Introduction to Spring Framework
Overview:
Open-source framework for Java enterprise applications.
Known for flexibility, modularity, and scalability.
Evolution:
Early Days (2003): Alternative to Java EE complexity.
JEE and EJB Context (2004 - 2005): Addressed drawbacks of Java EE and EJB.
Spring 2.0 (2006): Supported Java EE 5 features.
Java EE 6 and Spring 3.0 (2009): Embraced annotations and simplified configurations.
Java EE 7 and Spring 4.0 (2013): Aligned with Java EE 7 release.
Current State (2023): Coexists with Jakarta EE, expanded beyond Java EE.
Key Concepts:
IoC and DI for flexible control flow.
AOP for modularizing cross-cutting concerns.
Data Access and ORM for clean database interactions.
Transaction Management for simplicity and control.
Application Messaging:
Messaging abstraction for event-driven apps.
Message-driven POJOs and integration with brokers.
MVC for Web Applications:
Controller handling user requests.
Model holding data and business logic.
View presenting data to users.
DispatcherServlet and HandlerMapping for request handling.
Configuring the Spring Framework involves setting up the various components and settings needed for your Spring-based application to function. Here’s a detailed explanation of the configuration process:
Setting Up a Spring Project:
Start by creating a new Spring project using a build tool like Maven or Gradle. Include the necessary Spring dependencies in your project configuration.
ApplicationContext:
The core of Spring configuration is the ApplicationContext. This container manages the beans (Spring-managed objects) and their dependencies. There are different ways to configure the ApplicationContext:
XML Configuration: Traditionally, Spring applications were configured using XML files. You can define beans and their relationships in an XML file.
Java Configuration: With the introduction of Java-based configuration, you can use @Configuration annotated classes to define beans and their relationships directly in Java.
Annotation-based Configuration: Utilize annotations like @Component, @Service, @Repository, and @Autowired to let Spring know about your beans and their dependencies.
Bean Definition:
A bean is a Spring-managed object. Define your beans in the configuration file or class. Specify the bean’s class, and optionally set properties or constructor arguments.
Dependency Injection:
One of the core features of Spring is dependency injection. This can be achieved through constructor injection, setter injection, or field injection. The @Autowired annotation is commonly used for injection.
Scope of Beans:
Beans in Spring can have different scopes, such as Singleton, Prototype, Request, Session, etc. Configure the scope of a bean based on your application’s requirements.
Autowiring:
Spring can automatically resolve and inject dependencies for you using autowiring. You can use @Autowired on fields, constructors, or methods to indicate the dependency injection points.
Externalizing Configuration:
Externalize configuration properties using properties files, YAML files, or environment variables. Spring provides the @Value annotation to inject property values into beans.
Web Application Configuration:
For web applications, configure the DispatcherServlet, view resolvers, and other web-related components. Use annotations like @Controller for request mapping.
Remember that the exact configuration steps may vary based on your specific use case and the version of the Spring Framework you are using. Always refer to the official Spring documentation for the most up-to-date information.
Spring Web Application Architecture
DispatcherServlet Overview:
Role
Front Controller for Web Applications
Receives and dispatches HTTP requests to controllers.
Configuration
Associated with a dedicated WebApplicationContext
Manages web components like controllers and view resolvers
Initialization
Initializes its context separately from the root application context
ApplicationContext and Hierarchy
Root ApplicationContext:
Manages core application components (services, business logic).
Loaded through ContextLoaderListener.
WebApplicationContext:
Child of the root context.
Manages web-specific components.
Hierarchy Relationship:
Root context is the parent for all WebApplicationContexts.
Promotes hierarchical structure for bean management.
Sharing Beans:
Beans from the root context can be accessed by all DispatcherServlets.
Configuration Management:
Profiles help manage different configurations for different environments (e.g., development, testing, production) within a single codebase. This enables easy switching between configurations without modifying the code.
Environment-specific Settings:
Profiles allow developers to define beans and configuration specific to a particular environment. For example, you might have different database settings or external service endpoints for development and production environments.
Feature Toggle:
Developers can use profiles to enable or disable certain features or components based on the active profile. This is useful for controlling experimental features or toggling functionality based on specific environments.
Customizing Bean Initialization:
Profiles enable developers to customize the initialization and configuration of beans based on the active profile. This flexibility is valuable when certain beans need to behave differently in different environments.
Testing Scenarios:
Profiles are beneficial for testing scenarios where specific beans or configurations are needed for testing purposes. This allows developers to isolate and configure components appropriately for different testing situations.
Third-Party Integrations:
When integrating with external services or APIs that have different configurations for various environments, profiles help manage these differences seamlessly.
Simplified Configuration:
Profiles contribute to cleaner and more maintainable configuration files. By organizing configurations based on profiles, developers can easily understand and manage the settings for different scenarios.
Reducing Code Duplication:
Profiles help reduce code duplication by allowing developers to specify only the differences between environments. This promotes a more modular and DRY (Don’t Repeat Yourself) approach to configuration.
Application Scaling:
In enterprise applications that may have multiple deployment scenarios, profiles facilitate the scaling of the application by providing a straightforward way to adjust configurations based on the deployment environment.
Security Configuration:
Security-related settings often vary between environments. With profiles, developers can tailor security configurations based on the specific requirements of each environment.
Migrating Jakarta EE 8 Servlets using the Command Pattern with switch statements to Spring Controllers with @RequestMapping involves several steps. Here’s a high-level overview of the migration process:
1. Setup Spring Framework:
Integrate Spring Framework into your project. This typically involves adding Spring dependencies to your project and configuring the Spring context.
2. Convert Servlets to Spring Controllers:
Identify the existing Servlets that you want to migrate.
Create corresponding Spring Controller classes. You can use the @Controller annotation on the class.
3. Replace Command Pattern with @RequestMapping:
In the existing Servlets, if you are using the Command Pattern with switch statements, identify the commands or actions that are handled in each case.
Create methods in your Spring Controller for each command or action.
Use the @RequestMapping annotation on these methods to map them to specific URLs or request patterns.
4. Handle Request Parameters:
Modify your methods in the Spring Controller to accept parameters using annotations like @RequestParam, @PathVariable, etc., based on the parameters passed to the Servlet.
5. Refactor Switch Statements:
Instead of using switch statements for flow control, leverage Spring’s declarative approach. Each method in your Spring Controller should focus on handling a specific request or action.
6. Handle Request and Response Objects:
Modify the code to utilize the HttpServletRequest and HttpServletResponse objects appropriately. In Spring, you can use method parameters or inject these objects directly.
7. Dependency Injection:
Utilize Spring’s dependency injection to inject services or other components needed by your controllers. You can use annotations like @Autowired for this purpose.
8. Update View Resolution:
If your Servlets were responsible for rendering views, update the logic to use Spring’s view resolution mechanisms. You can use annotations like @ResponseBody or ModelAndView to handle view responses.
9. Test and Debug:
Thoroughly test the migrated controllers to ensure they handle requests correctly.
Debug and resolve any issues that arise during the migration process.
10. Update Configuration:
If your application uses any configuration files specific to Jakarta EE, update or replace them with Spring configuration files (like applicationContext.xml or Java-based configurations).
11. Gradual Migration:
Consider a gradual migration approach if your application is large. You can start by migrating one Servlet at a time and ensuring that each one works as expected before moving to the next.
12. Documentation:
Update documentation to reflect the changes in the architecture and provide guidance for future development.
By following these steps, we can migrate Jakarta EE 8 Servlets using the Command Pattern to Spring Controllers with @RequestMapping in a systematic and organized manner. This process allows you to leverage Spring’s features and benefits while maintaining or improving the functionality of your web application.
The Controller-Service-Repository pattern:
Service:
In the Controller-Service-Repository pattern, the service layer sits between the controller and the repository.
The service layer contains the business logic of the application.
It orchestrates interactions between multiple repositories (data access objects) and performs any necessary processing on the data before passing it back to the controller.
Services are often implemented as Spring-managed beans, using annotations like @Service
Why Use Root Context?
Sharing Beans: Avoid duplication, share beans across multiple servlets.
Global Configuration: Non-web components belong here, ensuring initialization once.
Testability: Easier testing of non-web components in isolation.
Scalability: Better organization and maintainability as the application grows.
Promotes better organization, reusability, and maintainability of application code.
Spring i18n in Jakarta EE 8 Web Apps
Unified i18n Approach: Spring internationalization provides a consistent approach across application layers.
Advanced Features: Offers enhanced message formatting and locale management capabilities.
Integration and Ease of Use: Seamlessly integrates with other Spring components and simplifies i18n tasks.
Implementing Spring i18n in Jakarta EE 8
API Usage: Add Spring i18n dependencies and configure `MessageSource` and `LocaleResolver` beans.
Accessing Messages: Use Spring `MessageSource` to retrieve localized messages in controllers and services.
Transitioning to Spring i18n in Jakarta EE 8
Migrating Resource Bundles: Utilize existing resource bundles by configuring `ResourceBundleMessageSource` with the appropriate base names. (or create new ones)
Updating Application: Modify controllers and services to leverage Spring's `MessageSource` for localized messages retrieval.
Adapting Frontend: Explore integration with Spring's templating solutions such as Thymeleaf for enhanced frontend development experience.
What is Bean Validation?
Why use Hibernator Validator with Spring 5?
How to Configure Hibernate Bean Validation in a Spring 5 MVC Service Layer JEE8 Web App
How to add Constraint Validations to your Beans
Understanding SOAP Web Services
In this lesson, you will gain a comprehensive understanding of SOAP (Simple Object Access Protocol) Web Services and learn how to implement them using Spring Web Services. This course covers the following key topics:
[SOAP Web Services Overview]- An introduction to SOAP Web Services, including the basic principles and architecture.
[Using Spring Web Services for SOAP - XML, XSD, and WSDL]- Learn how to define XML schemas (XSD) and Web Services Description Language (WSDL) to structure and describe your SOAP messages.
[Using Spring Web Services for SOAP - Maven Archetype]- Discover how to use Maven Archetypes to quickly set up a Spring Web Services project for SOAP.
[Using Spring Web Services for SOAP - Maven Dependencies]
- Understand the necessary Maven dependencies required to build and run a SOAP-based Spring Web Services project.
[Using Spring Web Services for SOAP - Spring Configuration]
- Dive into the Spring configuration needed to set up SOAP endpoints and manage the application context.
[Testing our Spring SOAP Endpoints]
- Learn how to test your SOAP endpoints effectively to ensure they are functioning correctly.
By the end of this lesson, you will have the knowledge and skills to create, configure, and test SOAP Web Services using Spring Web Services. This will enable you to build robust and interoperable web services for enterprise-level applications.
Understanding REST Web Services
Introduction to REST Web Services: Explore how third-party clients interact with Spring Web MVC services for business logic, data retrieval, and persistence, focusing on service provision and implementation.
Modern Context: Understand the relevance of REST in the age of mobile and IoT, enabling real-time interactions via client-side JavaScript.
Goal: Learn how REST web services facilitate seamless, distributed system integration across diverse platforms for building robust applications.
REST Web Services Overview
Definition: REST is an architectural style for designing stateless, client-server applications using HTTP.
Key Characteristics: Stateless, client-server, cacheable, uniform interface, layered system.
History: Introduced by Roy Fielding in 2000, REST grew with the web’s expansion and is now widely used for APIs.
Advantages: Scalable, flexible, simple, and performance-optimized.
Use Cases: Web APIs, microservices, cloud services, third-party integrations.
REST Web Services Overview
Definition: REST is an architectural style for designing stateless, client-server applications using HTTP.
Key Characteristics: Stateless, client-server, cacheable, uniform interface, layered system.
History: Introduced by Roy Fielding in 2000, REST grew with the web’s expansion and is now widely used for APIs.
Advantages: Scalable, flexible, simple, and performance-optimized.
Use Cases: Web APIs, microservices, cloud services, third-party integrations.
REST Provides a Simpler Approach
REST Overview: REST offers a simpler alternative to SOAP with flexible data formats (JSON, XML, plain text) and uses standard HTTP methods for CRUD operations (POST, GET, PUT, DELETE).
Key Differences: REST does not require predefined resource formats and uses HTTP protocols directly, making it more adaptable.
HTTP Status Codes & MIME Types: REST uses HTTP status codes and MIME types to manage requests and responses, providing clear communication and flexibility.
Discoverability: REST's discoverability via HATEOAS supports dynamic client interactions, enhancing flexibility in agile and cloud-based environments.
Configuring REST using Spring MVC
Overview: Learn how to extend your existing Charity Registration Application to include RESTful web services using Spring MVC.
Key Steps:
Separate DispatcherServlet: Set up a dedicated DispatcherServlet for REST controllers to keep web UI and REST components distinct.
Segregate Controllers: Maintain separate contexts for web and REST controllers for cleaner architecture.
Develop REST Controllers: Implement REST controllers that handle JSON and XML requests.
Error Handling: Incorporate proper error handling for robust REST services.
Segregating Controllers with Stereotype Annotations
Overview: Learn how to separate REST and web controllers in Spring MVC using stereotype annotations and package organization.
Key Strategies:
Use Different Package Names: Organize web and REST controllers into separate packages to avoid DispatcherServlet overlap.
Spring Meta Annotations: Create custom annotations for web (@WebController) and REST (@RestApiController) controllers for cleaner segregation.
Configuration: Set up separate WebServletContextConfiguration and RestServletContextConfiguration for optimized, context-specific settings.
Handling Error Conditions in REST Web Services
Overview: Learn how to provide meaningful error responses in Spring REST services using modern error handling techniques.
Key Techniques:
Changing HTTP Response Codes: Use @ResponseStatus and @ExceptionHandler to return appropriate HTTP status codes like 404 for not found or 500 for server errors.
Global Exception Handling: Use @ControllerAdvice for centralized exception handling across multiple controllers.
Custom REST Annotations: Create custom annotations to standardize and simplify controller configurations while handling errors efficiently.
Improving Discoverability with an Index Endpoint
Overview: Learn how to enhance your Charity Registration API’s discoverability by creating an index endpoint that lists all available API endpoints with brief descriptions.
Key Benefits:
Improved Discoverability: Provides a centralized overview of available API operations.
Self-Documentation: Acts as live, self-updating documentation for developers.
Ease of Use: Simplifies understanding and integration of the API.
Support for Versioning: Easily adaptable for API versioning with version details included.
Testing REST Endpoints
Overview: Learn how to test REST endpoints in your Charity Registration application to ensure reliability and proper error handling.
Key Tools:
Postman: Ideal for manual testing and debugging with a user-friendly interface.
cURL: Command-line tool for quick, scriptable HTTP requests.
JUnit with Spring Boot Test: Automated testing for REST endpoints within the Spring context.
REST Assured: Java library for simplified, maintainable API testing.
Making Requests: Test your endpoints by sending HTTP requests and verifying the responses, ensuring functionality and proper status codes.
Configuring REST using Spring MVC
Overview:
Learn how to extend your existing Charity Registration Application to include RESTful web services using Spring MVC.
Key Steps:
Separate DispatcherServlet: Set up a dedicated DispatcherServlet for REST controllers to keep web UI and REST components distinct.
Segregate Controllers: Maintain separate contexts for web and REST controllers for cleaner architecture.
Develop REST Controllers: Implement REST controllers that handle JSON and XML requests.
Error Handling: Incorporate proper error handling for robust REST services.
Configuring REST using Spring MVC
Overview:
Learn how to extend your existing Charity Registration Application to include RESTful web services using Spring MVC.
Key Steps:
Separate DispatcherServlet: Set up a dedicated DispatcherServlet for REST controllers to keep web UI and REST components distinct.
Segregate Controllers: Maintain separate contexts for web and REST controllers for cleaner architecture.
Develop REST Controllers: Implement REST controllers that handle JSON and XML requests.
Error Handling: Incorporate proper error handling for robust REST services.
Improving Discoverability with an Index Endpoint
Overview: Learn how to enhance your Charity Registration API’s discoverability by creating an index endpoint that lists all available API endpoints with brief descriptions.
Key Benefits:
Improved Discoverability: Provides a centralized overview of available API operations.
Self-Documentation: Acts as live, self-updating documentation for developers.
Ease of Use: Simplifies understanding and integration of the API.
Support for Versioning: Easily adaptable for API versioning with version details included.
Testing REST Endpoints
Why Test REST Endpoints?
Ensure reliability, functionality, and error handling.
Validate that endpoints meet application requirements.
Key Testing Tools:
Postman
User-friendly for manual and exploratory testing.
Ideal for quick debugging and automating simple tests.
cURL
Command-line tool for lightweight, scriptable requests.
Suitable for server environments and CI/CD pipelines.
JUnit (Spring Boot Test)
Automated integration tests within Spring context.
Ensures end-to-end application reliability.
REST Assured
Simplifies writing Java tests for REST APIs.
Readable and maintainable test cases.
Swagger/OpenAPI
Combines API documentation with exploratory testing.
Making Requests to Test Endpoints
Tools like Postman and cURL simplify request formulation and response validation.
JUnit and REST Assured enable automated testing with assertions.
Conclusion:
Effective testing ensures that your RESTful API is reliable, consistent, and ready for production. Choose tools that align with your workflow for optimal results.
What is data persistence?
What is an Object Relational Mapper
Understanding the Hibernate ORM
How to prepare a relational database MariaDB
Maven Dependencies for our sample module
Getting started with Entities
Creating and using a Persistence Unit
Mapping Complex Data Types
Using Spring Repositories and Transactions
Configuring Persistence with the Spring Framework
Creating and using JPA Repositories
Converting data with DTO's and Entities
### Eliminating Boilerplate JDBC code with Spring Data JPA
### **1. Updated Maven Dependencies**
Replace your current dependencies with the following:
```xml
<!-- Spring Data JPA (compatible with Jakarta EE 8 and OpenJDK 11) -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.7.12</version> <!-- Jakarta EE 8 compatible, Spring 5.3.x aligned -->
</dependency>
<!-- JPA API - Jakarta EE 8 -->
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>2.2.3</version> <!-- Aligned with Jakarta EE 8 (JPA 2.2) -->
</dependency>
<!-- SLF4J API for logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<!-- SLF4J Simple implementation (or Logback/log4j if preferred) -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate Core as JPA provider (compatible with JDK 11 & Jakarta EE 8) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.15.Final</version>
</dependency>
<!-- Optional: MariaDB JDBC Driver -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.9</version>
</dependency>
```
> **Note:**
> - `spring-data-jpa:2.7.x` is the last line of Spring Data compatible with Spring Framework 5.3.x and Jakarta EE 8 (before Spring Boot 3.x moves to Jakarta EE 9+).
> - Jakarta EE 8 still uses `jakarta.persistence` with package names like `javax.persistence`, but artifact group IDs are now under `jakarta.*`.
---
### **2. Configuring and Creating Spring Data Repositories**
[View File](jee8jpaspringconfcrt.md)
### **3. Spring Data's Unified Data Access**
[View File](jee8udac.md)
Refactoring Charity Registration Application
Goal
Refactor the existing Charity Registration application to leverage Spring Data JPA. This will improve maintainability, reduce boilerplate code, and ensure more efficient, declarative data access.
Objectives
Migrate from manual JDBC or traditional JPA `EntityManager`-based queries to Spring Data JPA repositories.
Use interface-based repository definitions for common CRUD operations.
Implement custom queries using `@Query` annotations where necessary.
Maintain separation of concerns between the service and data access layers.
Preserve existing functionality for charity CRUD operations and file attachment management.
Before Refactoring
Previously, the application used:
Manually written SQL statements in DAO classes.
Direct use of `EntityManager` or `JdbcTemplate`.
Tedious boilerplate for basic operations like `findById`, `save`, or `delete`.
After Refactoring
Using Spring Data JPA:
Repositories extend `JpaRepository<Charity, Long>` or `CrudRepository`.
Common methods like `findAll()`, `save()`, `deleteById()` are inherited.
Custom finder methods like `findByCharityName()` or `findByTaxId()` can be declared using Spring Data conventions.
Complex joins (e.g., Charity with associated Programs or Attachments) can be handled with `@Query` and `JOIN FETCH`.
Benefits
Less boilerplate – no need to write CRUD SQL or manage transactions manually.
Better testability – repository interfaces are easy to mock.
Improved readability – business logic is no longer cluttered with persistence logic.
Flexible queries – supports both derived query methods and JPQL/native queries.
Next Steps
We’ll begin by:
1. Creating repository interfaces such as `CharityRepository`, `ProgramRepository`, and `RegistrationRepository`.
2. Refactoring service classes to delegate persistence operations to these repositories.
3. Ensuring that integration with controllers and unit tests remains intact.
1. Introduction to Spring Security
What is Spring Security and why use it?
How Spring Security fits into Jakarta EE 8 and Spring 5 applications
Comparing Spring Security with alternatives like Apache Shiro and Keycloak
2. Core Concepts and Project Setup
Authentication, authorization, and the security filter chain
Setting up your first Spring Security project
Java-based configuration using Spring Boot or Spring MVC
Lesson : Authenticating Users in a Legacy Spring Web Application
What You'll Learn:
Understand how our current custom authentication flow works
Learn how login, logout, and session management are handled
Discover the role of filters and custom user identity objects
Appreciate the importance of login form validation
Get ready to modernize with Spring Security
Overview:
Our legacy application uses custom authentication logic to protect URLs and manage sessions. A servlet filter checks whether users are authenticated and redirects them to the login page if not. Authenticated users are wrapped with a custom Principal object stored in the session.
The login form (JSP-based) uses Spring form tags and handles field-level validation. Our controller processes login and logout, validates inputs, regenerates session IDs, and stores the authenticated principal in the session.
Login Flow Summary:
Authenticates users via a custom service
Stores user identity in the session
Prevents session fixation attacks
Filters ensure only authenticated access to secure pages
Logout clears the session and redirects to login
Next Steps:
Identify and address security gaps like CSRF protection
Introduce Spring Security gradually
Migrate current logic to Spring Security’s standard mechanisms
Lesson Objectives
By the end of this section, you will be able to:
Identify security gaps in our existing authentication approach
Gradually integrate Spring Security with SecurityFilterChain and JDBC-based authentication
Migrate the custom login flow (AuthenticationController) to Spring Security’s form login
Use our existing USER_ADMIN table as the data source
Understand the code updates and test them incrementally
THIS IS FIXED!!!!
What We will Learn
Apply URL- and method-level security in legacy apps.
Use `@PreAuthorize`, `@Secured`, and JSP `<sec:authorize>` tags. JSPs)
Customize authorization using SpEL & voters.
Implement a JDBC-based `UserDetailsService`.
Apply ACLs for fine-grained object-level security.
Project Setup and Architecture
Jakarta JEE8 Web App: Prebuilt WAR (`charity-springjpa`)
Security:
XML + JavaConfig (`SecurityConfig`)
`USER_ADMIN` + `registrations` tables in MariaDB
JPA: RegistrationRepositoryJPA
JDBC Authorization: JdbcUserDetailsManager
Live Demo Goals
Run app on Tomcat
Log in with JDBC users
Use role-based restrictions on `/registration/delete`
Add `@PreAuthorize` and taglibs
Optional Self Exercise: Extend with custom `AccessDecisionVoter` + ACL
An introduction to Java Web Development with Jakarta JEE 8:
Creating a basic JEE 8 Maven project structure
Our Basic Jakarta JEE 8 Web Application Structure
Creating and populating our CharityDB in MariaDB
Creating and populating our Charity Associate Table in MariaDB
Updating the JEE 8 Web Application Module with a Hello World Servlet
Debugging the JEE 8 Web App
Using a Multiparameter Form in a JEE 8 Web App
Using Init Params in the JEE 8 Web App
Uploading files via Servlet in the JEE 8 Web App
Multi-threading in the Tomcat JEE 8 Web App
JSP is HTML in the JEE 8 Web App
Expanding on our JSP knowledge in Jakarta JEE 8
Embedding Java into JSP with JEE 8 Web App
Combining Java (C) and JSP(V) in our JEE 8 Web App MVC
Using HTML and CSS with Bootstrap in our JSPs
Understanding Jakarta Expression Language 3.0 - Part 1
Using the Java Standard Tag Library 1.2 in our JEE 8 Web Applications - Part 1
A short overview of Jakarta Server Faces
Maintaining State using Sessions in our JEE 8 Web Applications - Part 1
Maintaining State using Sessions in our JEE 8 Web Applications - Part 2
Understanding Jakarta Expression Language 3.0 - Part 2
Understanding Jakarta Expression Language 3.0 - Part 3
Using the Java Standard Tag Library 1.2 in our JEE 8 Web Applications - Part 2
Using custom Java Standard Tag Library 1.2 files in our JEE 8 Web Applications - Part 3
Using custom JSTL 1.2 files for enabling login to our JEE 8 Web Applications
Maintaining State using SessionListereners in our JEE 8 Web Applications - Part 3
Clustering and Session Replication in Tomcat 9 in our JEE 8 Web Applications
Improving our Jakarta JEE 8 Web Application using Filters
Making your Application Interactive with WebSockets
Logging with log4j and slf4j in our Jakarta JEE8 Web Application
Spring Framework Review with Jakarta JEE8
Spring Framework Enterprise Development with Jakarta JEE8
Java Persistence API and Hibernate ORM with Jakarta JEE8
Using Spring Security in a JEE 8 Web Application