five most used annotations in Spring Mvc

five most used annotations in Spring Mvc

1. @Controller

The `@Controller` annotation marks a class as a Spring MVC controller, which means that it can handle web requests. It is a specialization of the `@Component` annotation, allowing for autodetection through classpath scanning.

annotations in Spring Mvc

Example
Example:
```java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Spring MVC!");
        return "home";
    }
}
```

 2. @RequestMapping

The `@RequestMapping` annotation is used to map web requests to specific handler functions in controller classes. It can be applied to classes or methods to specify the URL patterns they should handle.

Example
```java

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

@Controller

@RequestMapping("/home")

public class HomeController {

    @RequestMapping("/")

    public String home(Model model) {

        model.addAttribute("message", "Hello, Spring MVC!");

        return "home";
 }

}

```

 3. @GetMapping and @PostMapping

These annotations are specialized versions of `@RequestMapping` that simplify mapping HTTP GET and POST requests to handler methods, respectively. They make the code more readable and less verbose.

Example
Example:
```java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class FormController {

    @GetMapping("/form")
    public String showForm() {
        return "form";
    }

    @PostMapping("/form")
    public String submitForm(Model model) {
        model.addAttribute("message", "Form submitted successfully!");
        return "result";
    }
}
```

4. @RequestParam

The @RequestParam annotation is used to extract query parameters, form data, and other parameters from the request. It can specify default values and whether the parameter is required.

    Example
    Example:
    ```java
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    public class GreetingController {
    
        @GetMapping("/greet")
        public String greet(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
            model.addAttribute("message", "Hello, " + name + "!");
            return "greet";
        }
    }
    ```
    

    5. @ModelAttribute

    The `@ModelAttribute` annotation binds a method parameter or method return value to a named model attribute, which can then be accessed in a view. It is useful for preparing data for the view and handling form submissions.

    Example
    ```java
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.PostMapping;
    
    @Controller
    public class UserController {
    
        @GetMapping("/userForm")
        public String showForm(Model model) {
            model.addAttribute("user", new User());
            return "userForm";
        }
    
        @PostMapping("/userForm")
        public String submitForm(@ModelAttribute User user, Model model) {
            model.addAttribute("user", user);
            return "userResult";
        }
    }
    
    class User {
        private String name;
        private int age;
    
        // getters and setters
    }
    ```
    
     Project Structure
    
    ```
    src
     └── main
         └── java
             └── com
                 └── example
                     └── controller
                         └── HomeController.java
                         └── FormController.java
                         └── GreetingController.java
                         └── UserController.java
                     └── model
                         └── User.java
         └── resources
             └── application.properties
         └── webapp
             └── WEB-INF
                 └── views
                     └── home.jsp
                     └── form.jsp
                     └── result.jsp
                     └── greet.jsp
                     └── userForm.jsp
                     └── userResult.jsp
         └── web.xml
    ```
    
     Maven Dependencies (pom.xml)
    
    ```xml
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.10</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    ```
    
     web.xml Configuration
    
    ```xml
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 
             version="4.0">
        
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    ```
    
     Views (JSP files)
    
     home.jsp
    ```jsp
    <!DOCTYPE html>
    <html>
    <head>
        <title>Home</title>
    </head>
    <body>
        <h1>${message}</h1>
    </body>
    </html>
    ```
    
     form.jsp
    ```jsp
    <!DOCTYPE html>
    <html>
    <head>
        <title>Form</title>
    </head>
    <body>
        <form action="/form" method="post">
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
    ```
    
     result.jsp
    ```jsp
    <!DOCTYPE html>
    <html>
    <head>
        <title>Result</title>
    </head>
    <body>
        <h1>${message}</h1>
    </body>
    </html>
    ```
    
     greet.jsp
    ```jsp
    <!DOCTYPE html>
    <html>
    <head>
        <title>Greeting</title>
    </head>
    <body>
        <h1>${message}</h1>
    </body>
    </html>
    ```
    
     userForm.jsp
    ```jsp
    <!DOCTYPE html>
    <html>
    <head>
        <title>User Form</title>
    </head>
    <body>
        <form action="/userForm" method="post">
            Name: <input type="text" name="name"><br>
            Age: <input type="number" name="age"><br>
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
    ```
    
     userResult.jsp
    ```jsp
    <!DOCTYPE html>
    <html>
    <head>
        <title>User Result</title>
    </head>
    <body>
        <h1>User Information</h1>
        <p>Name: ${user.name}</p>
        <p>Age: ${user.age}</p>
    </body>
    </html>
    ```
    
    

    Homepage

    Readmore