Call : +11234567895
I

SPRING MVC TUTORIAL

Learn the fundamentals of Spring MVC, including annotations, architecture, form handling, JSTL integration, and building RESTful APIs.

SPRING MVC TUTORIAL

Spring MVC is a widely-used and powerful framework for building Java web apps. It is based on the Model-View-Controller (MVC) architectural pattern, offering developers a structured way to build web applications.

In this tutorial, we will go over the basics and more advanced features of Spring MVC, such as its annotations, architecture, flow, form handling, integration with JSTL, and REST API.

Basics of Spring MVC

Spring MVC is a framework that helps developers use the Model-View-Controller (MVC) architectural pattern to build web applications. To get a feel for how Spring MVC works, let's look at its main parts:

  1. Model: The model is what the application's data and business logic look like. It holds the information that the application needs to work. In a Spring MVC application, the model can be made using plain Java objects (POJOs) or frameworks like Hibernate or JPA to talk to a database.
  2. View: The view's job is to show the user the information. It stands for the application's user interface, which can be an HTML page, a JSP (JavaServer Pages), a Thymeleaf template, or any other way to show information. The data comes from the controller and is shown by the view.
  3. Controller: The controller sits between the model and the view. It takes requests from users, processes them, and decides how to respond. In Spring MVC, controllers are made up of Java classes that have the @Controller annotation added to them. The @RequestMapping annotation is used to map certain methods to specific URLs.

Spring MVC Annotations

Annotations are predominantly used in Spring MVC to make it easier to set up and map controllers and handle requests. These annotations use a declarative method, so developers can use simple annotations to describe how their web application works.

Let's explore some Spring MVC annotations that are often used:

  1. @Controller: With Spring MVC's @Controller annotation, a Java class is marked as a controller. This annotation tells the framework that the class has methods to handle requests and make responses. When this annotation is added to a class, it becomes ready to handle requests from clients.
  2. @RequestMapping: The @RequestMapping annotation is used to connect a URL pattern to a specific controller method. Both the class level and the method level can use this annotation. It sets the base URL for all methods in that controller at the class level. At the method level, it gives more information about the URL mapping for each method. For instance:

In the above example, the @RequestMapping annotation at the class level sets the base URL for all methods in the ProductController to "/products". The listProducts() method is mapped to "/products/list".

  1. @PathVariable: The @PathVariable annotation is used to extract values from the URL path and pass them as method parameters. This is useful when someone has dynamic portions in the URL that they want to capture and use in their controller method. For example:

In the above example, the @PathVariable annotation captures the "id" value from the URL path "/products/{id}" and binds it to the productId method parameter.

  1. @RequestParam: The @RequestParam annotation is used to get request parameters from the URL query string or form data. It ties the parameter value to the method parameter that has been annotated. For instance:

In the above example, the @RequestParam annotation retrieves the value of the "query" parameter from the URL query string and binds it to the searchQuery method parameter.

  1. @ModelAttribute: With the help of the @ModelAttribute annotation, request parameters can be linked to a model object. It can be used with method parameters or the types that methods return. When it is used on method parameters, it ties the values of the request parameters to the model object properties that match. When it is used on method return types, the object is added to the model's attributes. For instance:

In the above example, the @ModelAttribute annotation binds the request parameters to the properties of the Product object. The Product object is then available in the method for further processing.

Spring MVC Architecture:

Spring MVC uses a layered architecture that encourages separating concerns and building things in pieces. Here are the most important parts of Spring MVC architecture:

  1. DispatcherServlet: It acts as the front controller and is in charge of receiving requests and managing the whole request-response lifecycle. Based on the URL mapping, the DispatcherServlet sends the request to the right controller.
  2. HandlerMapping: The job of HandlerMapping is to send requests to the right controller. It looks at the URL pattern to figure out which controller should handle a certain request. Spring MVC has different implementations of HandlerMapping, like the RequestMappingHandlerMapping, which maps requests using annotations like @RequestMapping.
  3. Controller: Java classes marked with @Controller are controllers. They handle requests and make responses. They have methods with @RequestMapping or other annotations for mapping. Based on the URL mapping, when a request comes in, the DispatcherServlet sends it to the right controller method.
  4. Model: The model is what the application's data and business logic look like. It contains the data that needs to be shown or changed. Controllers store data in the model and send it to the view so it can be shown.
  5. ViewResolver: ViewResolver is in charge of connecting the logical view name that the controller gives back to the real view implementation. It connects the logical view name to a specific view technology, such as JSP, Thymeleaf, or FreeMarker.
  6. View: The response that will be sent back to the client is made by the view. It makes HTML or other content based on the data in the model. Spring MVC works with a number of different view technologies, such as JSP, Thymeleaf, and others.

Spring MVC Flow

It's important to know how a Spring MVC application works:

  • The user tells the DispatcherServlet what they want.
  • The HandlerMapping is used by the DispatcherServlet to find the right controller.
  • The controller takes care of the request, talks to the model, and gets ready to send the response.
  • The ViewResolver works out the logical view name that the controller gave back.
  • The response is shown by the view, and then it is sent back to the user.

Spring Form Handling

Spring MVC provides robust support for handling HTML forms. It simplifies form submission, data binding, and validation. Let's explore the basics of Spring form handling:

  1. Create a form in JSP: First, create a form in JSP (JavaServer Pages) or any other view technology supported by Spring MVC. The form includes input fields, checkboxes, radio buttons, and other form elements. For example:
  1. Create a model class: Next, make a model class that represents the form data. The model class should have properties for each form field. Use the right annotations for validating and binding data. For instance:
  1. Handle form submission in a controller: In the controller, create a method to handle the form submission. Annotate the method with @PostMapping or @RequestMapping and specify the URL to handle the form submission. Bind the form data to the model object using the @ModelAttribute annotation. For example:
  1. Perform data validation: Spring MVC automatically performs data validation based on the annotations applied to the model class properties. The BindingResult object is used to capture any validation errors. If there are validation errors, handle them accordingly, such as displaying error messages to the user or redirecting to an error page.
  2. Display validation errors in the view: In the view, display the validation errors, if any, using the BindingResult object. For example,  <form:errors> tag in JSP can be used:

By following these steps, organizations can handle form submission, bind form data to the model, perform data validation, and display error messages in a Spring MVC application.

Spring MVC with JSTL:

JavaServer Pages Standard Tag Library (JSTL) provides a set of tags that simplify JSP development. Integrating Spring MVC with JSTL enhances the view layer. Here's how  JSTL can be used in Spring MVC:

  1. Include JSTL dependency: Add the JSTL dependency to the project's dependencies. For example, if Maven is being used:
  1. Configure JSTL in web.xml: In the web.xml file, configure the JSTL tags by adding the JSTL configuration:
  1. Import JSTL tag library in JSP: In JSP file, import the JSTL tag library by adding the following taglib directive at the top:
  1. Use JSTL tags in JSP: Use various JSTL tags to perform logic, iteration, conditional rendering, and more in the JSP. For example, <c:forEach> tag can be used to iterate over a collection:

In the above example, the <c:forEach> tag iterates over the "products" collection and assigns each element to the "product" variable. The product name is then displayed using ${product.name}.

By integrating JSTL with Spring MVC, one can leverage the power of JSTL tags to simplify and enhance their JSP views. JSTL provides a wide range of tags for iteration, conditional rendering, formatting, and more.

Spring MVC with REST API

Spring MVC provides excellent support for building RESTful APIs. REST (Representational State Transfer) is an architectural style for designing networked applications.

Spring MVC simplifies the development of RESTful APIs by providing features like content negotiation, request mapping, and response handling. Let's explore how to build REST APIs with Spring MVC:

  1. Create a REST Controller: In Spring MVC, REST APIs are typically implemented using @RestController annotated classes. These classes combine the @Controller and @ResponseBody annotations, indicating that the returned values should be serialized directly into the response body. For example:

In the above example, the ProductController class is annotated with @RestController to indicate that it is a REST controller. The @GetMapping and @PostMapping annotations define the HTTP methods (GET and POST) and the corresponding URL mappings for retrieving and creating products.

  1. Handle Request Mapping: In RESTful APIs, the URL mappings are typically based on the resource being manipulated. Spring MVC provides annotations like @RequestMapping, @GetMapping, @PostMapping, etc., to define the URL mappings for different HTTP methods. These annotations can be applied at the class or method level. For example, the @GetMapping("/{id}") annotation maps the getProductById() method to the URL "/api/products/{id}".
  2. Handle Request and Response Bodies: REST APIs deal with request and response bodies, which contain data in formats like JSON or XML. Spring MVC can automatically serialize and deserialize Java objects to and from these formats using the @RequestBody and @ResponseBody annotations. The @RequestBody annotation binds the request body to a method parameter, and the @ResponseBody annotation serializes the method's return value to the response body.
  3. Use ResponseEntity for Response Customization: Spring MVC provides the ResponseEntity class to customize the HTTP response. It allows to set the response status, headers, and body. For example, in the createProduct() method, ResponseEntity is used to return a response with the HTTP status code 201.
  4. Implement RESTful CRUD Operations: REST APIs often involve implementing CRUD (Create, Read, Update, Delete) operations for resources. Spring MVC simplifies this by providing annotations like @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping to handle the corresponding HTTP methods. By mapping these methods to appropriate URLs, the required CRUD functionality can be implemented.

Conclusion

Spring MVC is a valuable framework for making web applications. In this tutorial, we've gone over the basics of Spring MVC, including its annotations, architecture, and handling of forms. We have also learned how to improve view rendering by combining Spring MVC with JSTL. and how Spring MVC can be used to make RESTful APIs.

To keep learning more, consult Cogent University. We have the best-in-class instructor-led programs for upskilling technical talent. These programs cover Spring MVC and other relevant technologies. Enrol today to learn more about Spring MVC development and get hands-on experience.

Visit our website to learn about the learning tools you can leverage to grow and succeed.

What’s a Rich Text element?

The rich text element allows you to create and format headings, paragraphs, blockquotes, images, and video all in one place instead of having to add and format them individually. Just double-click and easily create content.

Static and dynamic content editing

A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

How to customize formatting for each rich text

Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.

Ever wondered how computer programming works, but haven't done anything more complicated on the web than upload a photo to Facebook?

Then you're in the right place.

To someone who's never coded before, the concept of creating a website from scratch -- layout, design, and all -- can seem really intimidating. You might be picturing Harvard students from the movie, The Social Network, sitting at their computers with gigantic headphones on and hammering out code, and think to yourself, 'I could never do that.

'Actually, you can. ad phones on and hammering out code, and think to yourself, 'I could never do that.'

Start today and get certified in fundamental course.
We offer guaranteed placements.