Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Building a User-Friendly URL Shortener Using Spring Boot, Postgres, and FL0

Posted on Jul 30 • Originally published at blog.fl0.com In this tutorial, we will create a user-friendly URL shortener using SpringBoot and Postgres, deployed on FL0 for easy management and control. 🔗✨Nowadays, URLs have become an essential part of our workflow. However, long and complex URLs can be difficult to share or work with.In this tutorial, we will build a simple-to-use URL shortener that provides a convenient way to transform long URLs into shorter, more manageable links in just one click! 🧑‍💻We would be using Spring Boot to build our backend, Postgres as our database, both deployed simply using FL0. Then we would go ahead and build the user interface in the form of a simple Chrome Extension, which could call our APIs!Here’s some internet humor before we get started:Before we dive into the code, let's take a moment to understand the high-level overview of our project.Our URL shortener will be a Chrome extension designed to provide a seamless and delightful experience for users. Let's walk through the user journey to get a clear picture:Here’s a high-level diagram for better understanding:Before we begin, we need to make sure we have the following tools installed:Now we would go ahead and set up our new Spring Boot project using Spring Initializr 🌱In this step, we'll configure the necessary files and set up the database connection for our user-friendly URL shortener. Let's get started with the configuration setup!To run our app locally, we would also need postgresql running. So, lets set it up quickly.We create a new folder src/main/resources/local and create a new file local-postgre-docker-compose.ymlTo start our DB, in terminal navigate to the folder containing this file and run the command:This will start postgresql database as a docker container and we will be able to connect to it on localhost:5432 using the credentials as mentioned in the above docker fileNow we can run our application using below command:To centralize our configuration properties and make them easily accessible, let's create a ShortUrlConfig class. This class will be annotated with @ConfigurationProperties(prefix="short-url") to bind the properties from the application.yml file to the corresponding fields in our class. Here's an example:This will require us to add @ConfigurationPropertiesScan on top of the main application class. So, lets add it to our UrlshortenerApplication :Now that we have our files configured and the database connection established, it's time to move on to creating the necessary models and repositories.In this step, we'll configure the necessary files and set up the database connection for our user-friendly URL shortener. Let's get started with the configuration setup!To run our app locally, we would also need postgresql running. So, lets set it up quickly.We create a new folder src/main/resources/local and create a new file local-postgre-docker-compose.ymlTo start our DB, in terminal navigate to the folder containing this file and run the command:This will start postgresql database as a docker container and we will be able to connect to it on localhost:5432 using the credentials as mentioned in the above docker fileConfiguring Files and Database ConnectionFor local development we can use the default values.server.port: The port on which our application will run.spring.datasource.url: The URL for connecting to our PostgreSQL database.spring.datasource.username and spring.datasource.password: PostgreSQL database credentials.short-url.allowed-characters: The characters allowed in the generated keys. Feel free to modify or expand the character set if desired.short-url.key-length: The length of the generated keys for short url. We will be using length of 6 characters as key.Now we can run our application using below command:To centralize our configuration properties and make them easily accessible, let's create a ShortUrlConfig class. This class will be annotated with @ConfigurationProperties(prefix="short-url") to bind the properties from the application.yml file to the corresponding fields in our class. Here's an example:This will require us to add @ConfigurationPropertiesScan on top of the main application class. So, lets add it to our UrlshortenerApplication :Now that we have our files configured and the database connection established, it's time to move on to creating the necessary models and repositories.Next we'll define and create the necessary models and repositories for our URL shortener. The models will represent the table structure of our shortened URLs, and the repositories will handle the database operations. Let's dive in!The ShortUrlEntity entity represents a shortened URL and is annotated with @Entity to indicate that it's a JPA entity. The @Table annotation specifies the name of the table in the database.The entity has the following fields:The ShortUrlRepository extends the JpaRepository interface provided by Spring Data JPA. It enables us to perform CRUD operations on the ShortUrlEntity easily.We also define two custom methods:These methods will be used in our service layer to retrieve and manipulate data.Now we'll create the data transfer objects (DTOs), a utility class and service layer. The DTOs will facilitate data transfer, the utility class will provide helpful methods and the service will handle the business logic. Let's proceed!The ShortUrlRequest DTO represents a request to create a shortened URL. It has a single field, url.The ShortUrlResponse DTO represents the response after creating a shortened URL. It has a single field: key, which holds the unique key as response.We will create a new Java class named ShortUrlUtil in the com.fl0.urlshortener.util package and add the @Component annotation to the ShortUrlUtil class to make it a Spring bean:The ShortUrlUtil class is annotated with @Component to make it a Spring bean. It is also injected with the ShortUrlConfig using constructor injection.The ShortUrlUtil class provides a single method:This method will be used in the service layer.The UrlShortenerService class handles the business logic of URL shortening and retrieval. It relies on the ShortUrlRepository for database operations and the ShortUrlUtil for generating unique keys.The createShortUrl method checks if the URL already exists in the database.If it does, it returns the key of the URL from the database. Otherwise, it generates a new key, saves it along with the URL in the database, and returns the newly generated key.The getFullUrl method retrieves the original full URL based on the provided key.It finds the key in the database, increments the click count, saves the changes, and redirects to the original full URL.Our application is now equipped with the necessary components to handle the creation and retrieval of shortened URLs.To allow requests from the Chrome extension to our backend API, we need to configure Cross-Origin Resource Sharing (CORS). In this step, we'll create a CorsConfig class in our Spring Boot application to handle CORS configuration.The CorsConfig class implements the WebMvcConfigurer interface, allowing us to customize the CORS configuration for our application.Congratulations! We have successfully built the CorsConfig class to handle CORS configuration in our Spring Boot application. This will ensure that our backend API can accept requests from our Chrome extension without any CORS-related issues.Next let’s move on to build our chrome extension.In this step, we'll create a custom Chrome extension for our URL shortener. The extension will provide a convenient way for users to shorten URLs directly from their browser. Let's dive into the world of Chrome extension development!manifest.jsonpopup.htmlpopup.csspopup.jsbackground.jsNow lets load the extension in our Chrome browser by following these steps:We've successfully built the Chrome extension for our URL shortener.Now let’s go ahead and dockerize our application.Now we'll dockerize our application, making it easy to deploy and run in a containerized environment. Let's get started!We create a new file named Dockerfile in the root directory of our project.Here we specify the instructions for building the Docker image of our app for deployment.Now we will create a docker-compose in the project’s root directory.This docker-compose.yml file defines the service url-shortener-backend . The service is based on the configuration in the Dockerfile. It maps the container's port 8080 to the host's port 8080.Let's now navigate to the next section and explore hosting our backend and database with FL0!Now we would go ahead and host our application with the help of FL0And…Done ✅Our project is hosted on FL0 successfully.In this tutorial successfully built a link shortener chrome extension along with it’s backend and database and hosted it using FL0. 🎉You may find the repository link here https://github.com/dalefl0/fl0-url-shortener-backend.Moreover, here’s the link for the Chrome Extension if you want to use it yourself https://github.com/dalefl0/URL-Shortener-Chrome-ExtensionYou may visit https://fl0.com/ to start building and deploying your applications! 🚀Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Peter Wainaina - Apr 25 Internet Explorer - May 26 Jérôme Navez - May 25 Franck Pachot - Apr 22 Once suspended, fl0 will not be able to comment or publish posts until their suspension is removed. Once unsuspended, fl0 will be able to comment and publish posts again. Once unpublished, all posts by fl0 will become hidden and only accessible to themselves. If fl0 is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Dale Brett. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag fl0: fl0 consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging fl0 will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Building a User-Friendly URL Shortener Using Spring Boot, Postgres, and FL0

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×