- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Extend Security in an Auction Application with Spring Framework 7
This lab is designed as a Challenge Lab, you'll start with several requirements and build out a basic Spring Framework application and gradually move to more complex concepts. By the end of this Lab you will have a working auction application that you can use as a reference for future projects.
Lab Info
Table of Contents
-
Challenge
Introduction
In this lab, you'll build a comprehensive Spring Boot application for an auction system.
Starting with the
AuctionApplicationclass as your foundation, you'll define theItementity class that represents an auction item in a Java Persistence API (JPA) repository. You'll also create aCrudRepositoryinterface to handle CRUD operations for our Item entity.Next, you'll construct two Spring MVC Controllers:
ItemControllerfor fetching items and populating the modelAdminControllerfor managing administrative tasks for items
Finally, you'll create Thymeleaf templates to:
- Dynamically render your list of auction items in
index.html - Present an admin view with functionalities in
admin.html - Provide a form for creating or editing items in
form.html
This Lab will give you a thorough understanding of building a functional Spring Boot application, combining Spring MVC, Spring Data, and Thymeleaf templates.
Running and Testing the Application:
- This project uses gradle to run the application. Use the command
./gradlew bootRunfrom the Terminal. - You may encounter compiler errors while working through the lab. If that happens, review your code and run the application again.
- When you make code changes, stop the application with
Ctrl+C, then run the command again to restart it - Once the application is running it can be viewed in the Web Browser tab.
-
Challenge
Application Class
The
AuctionApplicationclass lies at the heart of your Spring Boot application.Annoted with
@SpringBootApplication, this class seamlessly configures Spring for you while enabling component scanning. TheSpringApplicationclass from the Spring Boot framework is your key to bootstrapping a Spring application from a Java main method.To start your application, simply call the
run()method from theSpringApplicationclass. This nifty method returns aConfigurableApplicationContextthat you can tuck away for later use.Relevant File: /src/main/java/com/pluralsight/auction/AuctionApplication.java
Instructions
- Import the SpringApplication Class: Import the
SpringApplicationclass from the Spring Boot framework. This class is used to bootstrap and launch a Spring application from a Java main method. - Start the Application: Call the static method
run()from theSpringApplicationclass. This method returns aConfigurableApplicationContextthat you can use later if needed. But for now, just start the application by passing two arguments to therun()method. - Run and verify the application:
- In the Terminal, run
./gradlew bootRun. - Verify that the application starts and
/loads. - If the application is already running, stop it with
Ctrl+Cand run the command again.
- In the Terminal, run
- Import the SpringApplication Class: Import the
-
Challenge
Item Entity Class
The
Itementity class is a crucial part of our auction setup, serving as an Entity class for a JPA (Java Persistence API) repository.This class represents an auction item, complete with properties like
name,description,seller,price, andreserve.To access these properties, you'll equip your class with getters and setters. Plus, you'll design a constructor that accepts parameters for each property, making it a breeze to create new
Iteminstances.Relevant File: /src/main/java/com/pluralsight/auction/Item.java
Instructions
- Define Properties: Define the properties for the
Itementity. Remember to specify the correct data types for each property. These properties should include:namedescriptionsellerpricereserve
- Create Getters and Setters: Add getter and setter methods for each property. These methods will allow other parts of your code to read (get) or modify (set) the values of your properties.
- Define a Parameterized Constructor:
Finally, define a constructor that accepts parameters for each property (except the
id, which is automatically generated). This constructor will make it easy to create newIteminstances with specific values.
- Define Properties: Define the properties for the
-
Challenge
Spring Data CrudRepository Interface
In this step, you'll be crafting a Spring Data repository interface that can handle the CRUD operations for your
Itementity.The
CrudRepositoryinterface from Spring Data is your ticket to these operations, and yourItemRepositoryinterface will extend this, specifyingItemandLongas the type parameters.Relevant File: /src/main/java/com/pluralsight/auction/ItemRepository.java
Instructions
- Import the CrudRepository Interface: Import the
CrudRepositoryinterface from Spring Data. This interface provides several methods for common CRUD operations. You can do this by typingimport org.springframework.data.repository.CrudRepository;at the top of your file. - Define the ItemRepository Interface: Define an interface named
ItemRepository. This interface should extendCrudRepository, which requires two type parameters: the entity class and the type of the entity ID. In this case, you'll useItemandLong.
- Import the CrudRepository Interface: Import the
-
Challenge
Item Controller
Next, you'll build a Spring MVC Controller that utilizes the
ItemRepositoryto fetch items. It then populates the model with these items for rendering in the view.To achieve this, you'll rely on the
Autowired,Model,GetMapping, and theItemRepositoryclasses and interfaces.Relevant File: /src/main/java/com/pluralsight/auction/ItemController.java
Instructions
- Import Required Classes: Import all the required classes and interfaces. These include:
AutowiredModelGetMappingItemRepository(interface that you created in the previous module)
- Inject the ItemRepository: Use dependency injection to get an instance of
ItemRepository. You can use the@Autowiredannotation to do this. Also, create a constructor to set theItemRepositoryinstance to a class level variable. - Define the listItems Method: Define a method named
listItemsthat:- handles
GETrequests for root URL ("/") - uses the
ItemRepositoryto fetch all items - adds the result to the model
- returns
"index"as the view name
- handles
- Run and verify your changes: Stop the application with
Ctrl+C(if it is running). Restart it with./gradlew bootRun. Open the Web Browser and navigate to/. The page may still appear empty. This is expected.
- Import Required Classes: Import all the required classes and interfaces. These include:
-
Challenge
Thymeleaf template: index.html
In this step, you'll create a Thymeleaf template named
index.htmlthat will serve as the canvas for rendering our list of auction items.The body of this page will house a
<main>element, within which you'll nest a<section>. This section will then generate an<article>for each item in theitemsattribute of the model.Relevant File: /src/main/resources/templates/index.html
Instructions
- Create the Main Content Area: In the
<body>of the page, create a<main>element. Inside this element, create a<section>. - Display the Auction Items: Inside the section, create an
<article>element for each item in theitemsattribute of the model (which was set inItemController). For each article:- Display the name in a
<h3>. - Display the description in a
<p>. - Display the item's price and seller in a
<footer>. Use theth:utextattribute to generate the content.
- Display the name in a
- Run and verify your changes: Stop the application with
Ctrl+C(if it is running). Restart it with./gradlew bootRun. Open the Web Browser and navigate to/. The page should render the layout. It may still be empty if no items exist yet.
- Create the Main Content Area: In the
-
Challenge
Admin Controller
Now, you'll put together a Spring MVC Controller named
AdminController.This controller will oversee administrative tasks for items, including listing all items, creating a new item, saving an item, editing an item, and deleting an item.
Relevant File: /src/main/java/com/pluralsight/auction/AdminController.java
Instructions
- Import Required Classes: Import all the required classes and interfaces. These include:
ModelModelAttributePathVariableGetMappingPostMappingItemRepository
- Inject the ItemRepository: Use constructor injection to provide an instance of
ItemRepositoryto the controller. - Define Controller Methods: Define the following methods:
listItems: HandlesGETrequests at the "/admin" URL, fetches all items, and adds them to the model.newItem: HandlesGETrequests at the "/admin/new" URL, creates a newIteminstance, adds it to the model and renders theform.htmltemplate.saveItem: HandlesPOSTrequests at the "/admin/save" URL, saves an item to the repository, and redirects to the "/admin" URL.editItem: HandlesGETrequests at the "/admin/edit/{id}" URL, fetches an item by its ID, adds it to the model and renders theform.htmltemplate.deleteItem: HandlesGETrequests at the "/admin/delete/{id}" URL, deletes an item by its ID, and redirects to the "/admin" URL.
- Run and verify your changes: Stop the application with
Ctrl+C(if it is running). Restart it with./gradlew bootRun. Open the Web Browser and navigate to/. At this stage, the page may only show the heading until you completeadmin.html.
- Import Required Classes: Import all the required classes and interfaces. These include:
-
Challenge
Thymeleaf template: admin.html
In this step, you'll construct a Thymeleaf template that presents auction items in a table format for an admin view.
This view will provide additional functionalities like creating a new item and editing or deleting existing items.
Relevant File: /src/main/resources/templates/admin.html
Instructions
- Create a Table to Display the Auction Items: Add a table with headers for:
- ID
- Name
- Price
- Reserve
- Seller
- Actions (an empty header)
- Add a Link to Create a New Item: Above the table, add a link that navigates to "/admin/new" to create a new auction item.
- Display the Auction Items in the Table: In the table body, create a row for each item in the
itemsattribute of the model. For each row:- Display the item's
id,name,price,reserve, andsellerin separate cells. - In the last cell, add links to edit and delete the item. The edit link should navigate to
/admin/edit/{id}, and the delete link should navigate to/admin/delete/{id}. The{id}in the URLs should be replaced with the item's ID.
- Display the item's
- Run and verify your changes: Stop the application with
Ctrl+C(if it is running). Restart it with./gradlew bootRun. Open the Web Browser and navigate to/admin. You should see:- A new link
- A table structure
- Create a Table to Display the Auction Items: Add a table with headers for:
-
Challenge
Thymeleaf template: form.html
In your final step, you'll create a Thymeleaf template for an auction item form.
This form will give users the ability to create a new item or edit an existing one.
Relevant File: /src/main/resources/templates/form.html
Instructions
- Create the Form
- In the body of the page, create a
<main>element. Inside this element, create a<section>. - In the section, create a
<form>with the action set to "/admin/save" and the method set to "post". The form should use theitemattribute of the model as the object.
- In the body of the page, create a
- Add Input Fields to the Form
- In the form, add input fields for the item's ID, name, price, reserve, description, and seller. Use the
th:fieldattribute to bind each input field to a property of the item. - The ID field should be a hidden input field.
- Each input field (except for the ID field) should be wrapped in a
<label>.
- In the form, add input fields for the item's ID, name, price, reserve, description, and seller. Use the
- Add Buttons to the Form
- At the bottom of the form, add a submit button with the text Save.
- Next to the submit button, add a link with the text Cancel. The link should navigate back to the admin page.
- Run and verify your changes: Stop the application with
Ctrl+C(if it is running). Restart it with./gradlew bootRun. Open the Web Browser and navigate to/admin/new. Confirm that the form loads and that you can submit it to create an item.
Note: When you submit the form you may receive an error message that says
This content is blocked. Contact the site owner to fix the issue.. This happens because the form is submitted inside an iframe in the lab environment. Refresh the page to confirm that your changes were saved. - Create the Form
-
Challenge
Completion
Congratulations on successfully completing this Spring Lab! You've taken important steps in your journey to learn Spring Boot.
Throughout the lab, you've built a complete auction system, starting from the ground up with the
AuctionApplicationclass, moving to defining theItementity class, and setting up aCrudRepositoryinterface to handle CRUD operations.You've also gotten hands-on experience with building Spring MVC Controllers, specifically the
ItemControllerandAdminController, each with its own responsibilities in managing auction items.Moreover, you've learned how to create dynamic Thymeleaf templates for various views, such as listing auction items (
index.html), presenting an admin view with functionalities (admin.html), and providing a form for creating or editing items (form.html).These skills are not only critical for building Spring applications but also lay a strong foundation for your journey in Java web development.
Well done on your achievement and keep up the good work!
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.