DEV Community

Prasanth
Prasanth

Posted on

Spring Framework (Spring MVC) & Spring Boot (Spring MVC with auto-configuration)

Spring Framework (Spring MVC) & Spring Boot (Spring MVC with auto-configuration)

Spring Boot MVC Full Flow (Two-Way)

Image description

  • We will see Real-time Example spring MVc how to flow .

  • Before going just remember , now will see only dynamic page ,we will see up coming blog static page. Now you brain ask what is static and dynamic page.

  • Static page: page does not change , same for every user like index.html.,Does not need controller or DB just enough home.html,contact.html...etc(show directly from /static(Static HTML/CSS/JS goes in src/main/resources/static)or/public folder in spring boot ).

Dynamic page:

  • user like click "Get Pizza catelog"-> it triggers GET/pizzas like flow Controller => Service => DB => returns a dynamic list of pizzas. This list may change(different prices,offers,availability)so its dynamic. (Dynamic HTML (Thymeleaf, JSP, etc.) uses Controller + Model+view) ** 1.Client sends Request**

user click "Get Pizza Catalog" this hits url GET/pizzas,it goes to DispatcherServlet

2.DispatcherServlet (Built-in Spring Front Controller)

It find the correct controller based url pattern(GET/pizzas) in Pizza_Controller because controller class is request handler and responder when hitting something from browser or postman direct came after DispatcherServlet to controller class, this class request and response incoming/outgoing.

3. @RestController or @Controller => PizzaController

@RestController public class PizzaController { @Autowired private PizzaService pizzaService; @GetMapping("/pizzas") public List<Pizza> getPizzaCatalog() { return pizzaService.getAllPizzas(); } } 
Enter fullscreen mode Exit fullscreen mode
  • Controller handles request and then pass request Service class ,Controller in handle only request/response and also called Request mapper( it receives Http request from client(browser/postman) maps and the correct java method using annotation . how it map((http request type)@GetMapping,@PostMapping,@PutMapping,@DeleteMapping)
  • It does not contain logic.

Note: Real-time hide request like POST,PUT,DELETE from normal user can not give all request like can not see or access it ,every user hit the request security issue occurred,only accessible that request for admin.we will see depth knowledge spring security( @PreAuthorize("hasRole('ADMIN')")
@PostMapping("/pizzas").


In terms of in real meaning:

  • GET for Read, POST for Create, PUT/PATCH for Update, DELETE for Delete.

Note: now we see only how to flow of mvc architecture not deep dive(POStmapping,DeleteMapping..etc) let understand only flow it give confident make to the project.

we simply see what is Responsibilities in @Controller class:

  • Request Mapping => Map URL like /pizzas using @GetMapping(Accepts client/browser/postman requests.),@PostMapping, etc.

  • Sends input to @Service.

  • Input Validation => Use @valid to validate input models

  • Handle Security => Restrict access using Spring Security roles(User/Admin)

  • Return response to the Data for client => JSON for REST, or HTML for Thymeleaf(serialization/Deserialization)

  • Error Handling =>Return error status codes to client.

4. @Service => PizzaService

@Service public class PizzaService { @Autowired private PizzaRepository pizzaRepository; public List<Pizza> getAllPizzas() { return pizzaRepository.findAll(); // JPA built-in method } } 
Enter fullscreen mode Exit fullscreen mode
  • This is the business logic layer (Buy 1 get 1 free,total bill calculation,offers,Logging/filterring(type,price..etc), auditing) all main logic is there in the class , how to function, validation(validate pizza name not empty,check price > 0,discounts,..etc),exception handling(Unexpected event the occurs at runtime which disturb the flow the program is called exception handling, like if pizza not available custom exception throw PizzaNotFoundException ), condition(if pizza is veg allow delivery ,if not ,show alert) and other things .

we simply see what is Responsibilities in @Service class:

  • Business Logic => EG:-Buy 1 Get 1 Free” logic, total bill calculation,Logging, auditing etc.

  • Validation => Check if price > 0, name not empty, etc.

  • Exception Handling =>If pizza not found → throw custom PizzaNotFoundException

  • Condition Logic => If pizza is veg → allow delivery, if not show alert

  • Looping/Filtering => Filter available pizzas by type, price, etc.

5.@Repository => PizzaRepository

@Repository public interface PizzaRepository extends JpaRepository<Pizza, Integer> { } 
Enter fullscreen mode Exit fullscreen mode
  • Now we created custom interface that interface extend another inbuilt interface JpaRepository. Pizza is the entity/pojo class, Integer is the wrapper for @id field, This interface connects to Database Using JpaRepository interface .JpaRepository give fetch,delete,save,update and other functionality without sql.

  • It doesn’t need implementation — Spring Data does ,that mean you do not need to write the logic like how to fetch data,save,delete data (you do not write like this save(),findAll() ,findById(),deleteById()) in the Repository interface - because spring data Jpa automatically provides it for you.No need to call this function but you can call to service class tho function.

Example:-

you write this

public interface PizzaRepository extends JpaRepository<Pizza, Integer> { } 
Enter fullscreen mode Exit fullscreen mode
  • Above is just an interface , you do not need write below function in this this interface like findAll(), JpaRepository interface provide or manged .
 public List<Pizza> findAll() { // connect to DB and get pizzas } 
Enter fullscreen mode Exit fullscreen mode
  • Before i said Do not need to write method or function(spring know belong to the JPA those function) in the interface, JpaRepository provide them based on the request, but you can call those method, you can call in the service class. you must to call .save(), .findAll(), .deleteById() from the service class to access repository based on request or logic what your write in the service class.

//Spring Boot Application Startup Flow with JPA and Repository Initialization

  • application starts after main class inside of run the method (SpringApplication.run(...)), spring read
  • application.properties or application.yml for DB settings (URL, username, password).
  • Connects to the database using JPA and Hibernate.
  • Creates proxy object for PizzaRepository and registers it as a Spring bean.

Example: you can call incomleted JPA Repository method to called in service in the

public List<Pizza> getAllPizzas() { return pizzaRepository.findAll(); } //findAll(),deleteById()..etc is a method from which interface? //It comes from JpaRepository interface, which your PizzaRepository extends. // in service class. public List<Pizza> getAllPizzas() { return pizzaRepository.findAll(); } 
Enter fullscreen mode Exit fullscreen mode

Spring Data JPA internally how it is work :

  • 1.Uses Dynamic proxy it create fake object at runtime for the Repository interface (why? This proxy object handles method calls like save() or findAll() without writing any logic) and 2.uses Reflection like find your method name findAll(), save(), 3.connect them to real SQL behind the scenes, so you do not write method ,you can use it directly, spring writes it for you during runtime.

  • Note: Proxy object created at run time by spring only once when the application starts(Note: this proxy object know how to call the correct Sql, Map the object,return results)..it stays in memory (spring container) and it is reused every time request like save() ,delete() comes. it does not disappear each request, singleton bean in the container.

1.Why use JpaRepository

  • Because i am telling spring , i want perform CRUD operations (like save, update, delete, select) on the Pizza table, and the primary key type is Integer.

  • Pizza => is your Entity class (mapped to a DB table).

  • Integer(wrapper class) => is the type of the @id field (like pizzaId).

  1. Why call .save(), .deleteById() in the Service Layer, not Controller?

Because of MVC Architecture:

  • Controller => Handle HTTP requests (GET, POST, etc.)
  • Service => Business logic (validation, conditions)
  • Repository => Only database access like get the data in database.

Example:

serviceClass

public void savePizza(Pizza pizza) { if(pizza.getPrice() > 0) { // business logic pizzaRepository.save(pizza); // JPA + Hibernate handles SQL } else { throw new RuntimeException("Invalid price"); } } 
Enter fullscreen mode Exit fullscreen mode

we simply see what is Responsibilities in @Repository interface:

  • Save Data => save(pizza)
  • Fetch Data => findAll(), findById(id)
  • Custom Queries =>findByName(String name), or @Query annotation.

6. @Entity (Model(data)) => Pizza.java

@Entity public class Pizza { @Id private int id; private String name; private double price; //contructor //getter and setter methods } 
Enter fullscreen mode Exit fullscreen mode
  • This class create a table in Database( fields=Table_Columns).
  • If you have any doubt like, we created table ,how to insert,update,modify,delete..etc how , before i said JPA Repositry gives (or) provide inbuilt method or function(save(), deleteById()..etc ) without Sql query(No need to write SQL manually) based on what you get that request from service class.Hibernate is provide the logic into in-completed method underground operation before i said.

  • JPARepoistory+Hibernet ,if you need to know please read previous blog.

  • we simply see what is Responsibilities in @Entity (POJO) class:
    Create Table => @Entity auto-generates DB table
    Columns => Fields become columns like id, name, price
    Validation =>Add @notblank, @min, etc., for field rules
    Primary Key =>Use @id and @GeneratedValue

Response Goes Back:-

Data comes from DB => Repository => Service => Controller => DispatcherServlet => Client

RestAPI outpt:-

 `[ { "id": 101, "name": "Cheese Pizza", "price": 250 }, { "id": 102, "name": "Veg Pizza", "price": 300 } ] `` 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)