Introduction to Spring MVC

Laukikrupne
4 min readMar 21, 2021

--

Introduction:

Spring is a lightweight, powerful, and flexible framework for building Java EE applications. It is easy to use and comes with its IDE called the SpringSource Tool Suite (STS). STS contains everything you need for building most Java EE applications. You can also start spring MVC project with spring boot Initializer. It is nice because you don’t have to add and remove several libraries to get one technology working with others.

Spring includes a set of modules, each with their own specific purpose (i.e., the JDBC module). This way, you can enable and disable different modules according to the needs of your application, thus keeping the framework as lightweight as possible.

While getting familiar with the Spring modules, the most important module is the Core module. This module provides the fundamental functionality of the spring framework. In this module, BeanFactory is the heart of any Spring-based application. The entire framework was built on the top of this module. This module makes the Spring container, which is similar to a JEE container, to manage transactions and object lifecycles.

The following defines the notable architectural features of Spring:

  • Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of the Spring framework is around 1MB. And the processing overhead is also very negligible.
  • Inversion of control (IoC): Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
  • Aspect-oriented programming (AOP): Spring supports aspect-oriented programming and enables cohesive development by separating application business logic from system services.
  • Container: Spring contains and manages the life cycle and configuration of application objects.
  • Framework: Spring provides most of the intra-functionality, leaving rest of the coding to the developer.

What is Spring MVC?

Spring MVC

MVC in Spring MVC stands for Model View Control. It is a design pattern Spring MVC follows and forces it on web developers to built web applications. Now we’ll see one by one what this Model, View, and Controller is.

  • Model : Model is simply data or objects that are passed to the Controller and view. In order them to communicate with each other. These Models can be bean classes, a simple java POJO’s, or data coming from a database doesn’t matter. Model is just a representation of data that can be understood by both the view and controller.
  • View : The view is a result that the user sees after the completion of his request. The view is also an interface user interacts with to use the web application. Generally, this view is web pages that give the user an interactive way to communicate with the application.
  • Controller : The controller is an section where we write our core business logic. The controller gets the data from the View, processes it, and generates the model. Then passes that model back to the View to give a response back to the user.

Spring MVC defines interaction between components to promote separation of concerns and loose coupling.

  • Each file has one responsibility.
  • Enables division of labour between programmers and designers.
  • Facilitates unit testing.
  • Easier to understand, change and debug.

Advantages of Spring MVC:

Separation of application logic and web design through the MVC pattern.

  • Integration with template languages.
  • Some MVC frameworks provide built-in components.
  • Other advantages include:

Form validation, Error handling, Request parameter type conversion, Internationalization, IDE integration.

Annotations in Spring MVC:

@Controller : If you annotate a class with the @controller annotation, it indicates that the annotated class is a Controller, the controller is an extension of @component annotation from spring core. This annotation helps in the component scanning of spring. Component scanning means that if you annotate, the class with component annotation spring will register that component in its registry so that you can ask spring to give that to you whenever you need it.

@Controller
public class BlogController {
@GetMapping("/")
public String listPosts(Model model,
@RequestParam Optional<Integer> start,
@RequestParam Optional<Long> authorId) {
return "/";
}
@PostMapping("/savepost")
public String savePost(@ModelAttribute("post") Post thePost ) {
blogService.savePost(thePost);
return "redirect:/"+thePost.getId().toString();
}
}

@Service: Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @Controller class file. The logic for creating a service component class file is shown here.

Service Interface.

public interface BlogService {
}

Service Implementation.

@Service
public class BlogServiceImpl implements BlogService {
}

@Entity : Models are defined in entity class.

@Entity
@Table(name = "post")
public class Post {

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "title")
private String title;

@Column(name = "excerpt",columnDefinition="TEXT")
private String excerpt;

@Column(name = "context",columnDefinition="TEXT")
private String context;

@Column(name = "published_at")
private LocalDateTime publishedAt;

@Column(name = "is_published")
private boolean publishStatus;

@CreationTimestamp
@Column(name = "created_at")
private LocalDateTime createdAt;

@UpdateTimestamp
@Column(name = "updated_at")
private LocalDateTime updatedAt;

@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
@JoinColumn(name="post_id")
private List<Comment> comments;

@Column(name="author")
private String author;

@ManyToMany(fetch=FetchType.LAZY,
cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
@JoinTable(
name="post_tags",
joinColumns=@JoinColumn(name="post_id"),
inverseJoinColumns=@JoinColumn(name="tag_id")
)
private List<Tag> tags;
}

@Repository :

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
//...
}

Repositories are used to implement DAO methods. DAO is design pattern in which a data access object (DAO) is an object that provides an abstract interface to some type of database or other persistence mechanisms. By mapping application calls to the persistence layer, DAOs provide some specific data operations without exposing details of the database.

Conclusion:

Your project structure in Spring Must look like.

Spring Boot MVC Project Structure.

--

--