JAKARTA EE FOR JUNIOR DEVELOPERS - Lesson 6 Using JSP and Servlet to save data in the database (Part 2)

 


INTRODUCTION

In this free lesson, Jakarta EE for Junior Developers, after we complete our application by making it more user-friendly with the addition of a JSP page, we will explain what exactly the MVC pattern is and how our application follows the basic principles of the MVC pattern.

WHAT IS JAKARTA SERVER PAGES?

According to Jakarta Server Pages specification (https://jakarta.ee/specifications/pages/3.1/jakarta-server-pages-spec-3.1#what-is-a-jsp-page-2) JSP (JavaServer Pages) is a technology used to create dynamic, web-based applications in Java. It allows developers to embed Java code directly into HTML pages. The primary purpose of JSP is to simplify the creation of dynamic content, like displaying data retrieved from a database or processing user input on a web page.

Also on the Jakarta Server Pages specification (Section "Components and Containers") is mentioned that JSP pages are collectively referred to as web components and they are delivered to a container that provides the services indicated in the JSP Component Contract. The JSP file is compiled into a Java Servlet. This is done by the servlet container. The JSP is essentially a mix of HTML and Java code, and the container converts the entire JSP file into a Java class (a servlet). This compiled servlet contains the Java code that was inside the JSP (like processing logic, loops, conditions, etc.) and is responsible for generating dynamic HTML content.

In short, JSP pages are processed on the server-side (in a Java servlet container like Wildfly), and the output (HTML) is sent to the client's browser for display. 

CREATING A JSP PAGE

Before we create a JSP page in our web application, we need to delete the existing html file that exists inside the Web Pages folder of our project. Right click on the index.html file and click on the delete option.


Now, right click on the Web Pages folder and select JSP.


Give the name index to the file and leave the options as JSP File (Standard Syntax). Click Finish to create the JSP page.


As you have noticed already, the file contains pure html tags. However, whenever it is needed, now we have the ability to write Java code inside HTML using special JSP tags (like <% %>), allowing dynamic content generation. For example, displaying user data or server-side logic within a webpage. We are not going to explain advanced features of the JSP pages on this tutorial. We will leave that for later lessons. For now, all we need is to create a simple page that can send a POST request to our Servlet.

Let's see the complete code and then we will explain it.

index.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <link rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
        crossorigin="anonymous">
    </head>
    <body>
        <h1 style="text-align: center">Employee Registration Form</h1>
        <div class="container mt-5">
            <section>
            <form action="Controller" method="post">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="firstname" class="form-label">First Name</label>
                        <input type="text" class="form-control" id="firstname"
                               placeholder="Enter your first name" name="firstName" >
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="lastname" class="form-label">Last Name</label>
                        <input type="text" class="form-control" id="lastname"
                               placeholder="Enter your last name" name="lastName" >
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="email" class="form-label">Enter your email</label>
                        <input type="email" class="form-control" id="email"
                               placeholder="Enter your email" name="email" >
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="phone" class="form-label">Enter your Phone number</label>
                        <input type="text" class="form-control" id="phone"
                               placeholder="Enter your phone number" name="phoneNumber" >
                    </div>
                </div>

                <div class="row">
                     <div class="col-md-6 mb-3">
                        <label for="date" class="form-label">Enter the hiredate</label>
                        <input type="date" class="form-control" id="date"
                               placeholder="Enter the hire date" name = "hireDate"  >
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="salary" class="form-label">Montly Salary</label>
                        <input type="number" class="form-control" id="salary"
                               placeholder="Enter yout salary" name = "monthlySalary" >
                    </div>
                </div>

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
            </section>
        </div>

    </body>
</html>

This JSP code represents a simple Employee Registration Form built using Bootstrap for styling and JSP to handle form data submission. Let's break it down:

Page Directive

<%@page contentType="text/html" pageEncoding="UTF-8"%>

This line is a JSP directive that sets the page's content type and character encoding:

  • contentType="text/html": It tells the server that the output is HTML.
  • pageEncoding="UTF-8": Specifies that the page uses UTF-8 character encoding, ensuring proper handling of international characters.

HTML Structure

This is a standard HTML document structure with some JSP-specific additions.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <link rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
        crossorigin="anonymous">
    </head>
  • The <meta> tag specifies the character encoding of the page.
  • The Bootstrap CSS link imports Bootstrap's default styles.

Body Content

Inside the <body>, we have a registration form:

   <body>
        <h1 style="text-align: center">Employee Registration Form</h1>
        <div class="container mt-5">
            <section>
            <form action="Controller" method="post">
  • <h1>: A header displaying the title of the form, centered on the page.
  • <div class="container mt-5">: This Bootstrap class ensures that the form is centered and given some spacing (top margin mt-5).
  • <form action="controller" method="post">: This is the actual form that will submit the data. The action="Controller" specifies that the form will be submitted to a URL mapped to the Controller (this the name of our Servlet that processes the data). The method="post" indicates that the data will be sent in the HTTP request body, which is typical for forms involving sensitive data like emails and phone numbers.

Form Fields

The form consists of several fields for employee information. Each one is grouped inside a Bootstrap grid system (<div class="row">), which helps layout the fields responsively.

Fields First Name & Last Name

 <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="firstname" class="form-label">First Name</label>
                        <input type="text" class="form-control" id="firstname"
                               placeholder="Enter your first name" name="firstName" >
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="lastname" class="form-label">Last Name</label>
                        <input type="text" class="form-control" id="lastname"
                               placeholder="Enter your last name" name="lastName" >
                    </div>
                </div>
  • These are two fields for First Name and Last Name, each in a separate column (thanks to the col-md-6 class for responsive grid layout). The form uses Bootstrap classes like form-control for styling and form-label for the label styling.
  • The name="firstName" and name="lastName" attributes are crucial because they define the parameters that will be used when the form is submitted to the server (in the POST request).

Fields Email & Phone Number

 <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="email" class="form-label">Enter your email</label>
                        <input type="email" class="form-control" id="email"
                               placeholder="Enter your email" name="email" >
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="phone" class="form-label">Enter your Phone number</label>
                        <input type="text" class="form-control" id="phone"
                               placeholder="Enter your phone number" name="phoneNumber" >
                    </div>
                </div>
  • These fields allow the user to enter their email and phone number.
  • The type="email" for the email field ensures that the input is validated as an email address.

Fields Hire Date & Monthly Salary

<div class="row">
                     <div class="col-md-6 mb-3">
                        <label for="date" class="form-label">Enter the hiredate</label>
                        <input type="date" class="form-control" id="date"
                               placeholder="Enter the hire date" name = "hireDate"  >
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="salary" class="form-label">Montly Salary</label>
                        <input type="number" class="form-control" id="salary"
                               placeholder="Enter yout salary" name = "monthlySalary" >
                    </div>
                </div>
  • These two fields are for the hire date (using an HTML5 date input type) and monthly salary (using a number input type).

Submit Button

<button type="submit" class="btn btn-primary">Submit</button>
  • This is a submit button with the Bootstrap btn and btn-primary classes, which styles the button with a blue color.

Closing Tags

 </form>
            </section>
        </div>

    </body>
</html>
  • The form is closed, and then the HTML body and document are closed properly.

Summary of the Workflow:

  1. The user fills out the form, providing first name, last name, email, phone number, hire date, and salary.
  2. When the user clicks Submit, the form sends a POST request to the Controller URL with the entered data.
  3. The Controller (our Servlet) processes the form data, typically saving it to a database or performing other server-side actions.

RUN THE APP

If you run the app and fill the fields with data, after clicking the submit button you should be able to see the data saved inside the Employees table.






WELCOME TO THE MVC PATTERN

The MVC (Model-View-Controller) pattern is a widely used software architectural design pattern that helps organize code into three interconnected components. It is commonly used in web development to separate concerns, making applications more modular, maintainable, and scalable.

Model
  • The Model represents the data and the business logic of the application.
  • It is responsible for retrieving, storing, and updating data from databases or other data sources.
  • The Model does not know about the View or the Controller—it simply handles the application's core functionality.
  • Example: In a web application, the Model could be a class that interacts with a database to retrieve or update records.

Responsibilities of the Model:

  • Fetch data (e.g., from a database).
  • Update data (e.g., saving or modifying records).
  • Perform business logic (e.g., calculating values or processing data).

View

  • The View is responsible for displaying the data to the user. It is the user interface (UI) of the application.
  • The View receives data from the Model and renders it, but it does not contain business logic. It is purely focused on presentation.
  • The View is usually a UI element (HTML in web applications, for example) that displays the information to the user and can also be updated dynamically.

Responsibilities of the View:

  • Render data from the Model.
  • Display the user interface elements (e.g., forms, buttons, tables).
  • Respond to user actions (through the Controller).

Controller

  • The Controller acts as the intermediary between the Model and the View.
  • It listens for user input (like button clicks, form submissions, etc.), processes that input (possibly modifying the Model), and then updates the View accordingly.
  • The Controller is responsible for handling user actions, updating the Model, and selecting the appropriate View to display.

Responsibilities of the Controller:

  • Receive and handle user input.
  • Update the Model based on user actions.
  • Determine which View to display after processing user input.

full-width



full-width

Post a Comment

0 Comments