Quick Contact

    Hibernate

    Spring MVC Annotations with Examples

    @RequestBody Annotation

    @RequestBody, annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.

    For example, the employee JSON object is converted into Java employee object using @RequestBody annotation.

    @RestController
    @RequestMapping("/api/v1")
    publicclassEmployeeController {
    @Autowired
    privateEmployeeRepositoryemployeeRepository;
    
    @PostMapping("/employees")
    publicEmployeecreateEmployee(@Valid@RequestBodyEmployeeemployee) {
    returnemployeeRepository.save(employee);
        }
    

    @RequestMapping

    @RequestMapping annotation for mapping web requests onto methods in request-handling classes with flexible method signatures.

    Both Spring MVC and Spring WebFlux support this annotation through a RequestMappingHandlerMapping, and RequestMappingHandlerAdapter in their respective modules and package structure.

    @RequestMapping marks request handler methods inside @Controller classes; it can be configured using:

    • path, or its aliases, name, and value: which URL the method is mapped to
    • method: compatible HTTP methods
    • params: filters requests based on the presence, absence, or value of HTTP parameters
    • headers: filters requests based on the presence, absence, or value of HTTP headers
    • consumes: which media types the method can consume in the HTTP request body
    • produces: which media types the method can produce in the HTTP response body Here’s a quick example of what that looks like:
    @Controller
    classEmployeeController {
    
    @RequestMapping(value="/employees/home", method=RequestMethod.GET)
    Stringhome() {
    return"home";
        }
    }
    

    We can provide default settings for all handler methods in a @Controller class if we apply this annotation to the class level. The only exception is the URL which Spring won’t override with method level settings but appends the two path parts.

    For example, the following configuration has the same effect as the one above:

    @Controller
    @RequestMapping(value="/employees", method=RequestMethod.GET)
    classEmployeeController {
    
    @RequestMapping("/home")
    Stringhome() {
    return"home";
        }
    }
    

    @GetMapping

    @GetMapping annotation for mapping HTTP GET requests onto specific handler methods.

    Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

    Example:

    @GetMapping("/employees")
    publicList< Employee>getAllEmployees() {
    returnemployeeRepository.findAll();
    }
    
    @GetMapping("/employees/{id}")
    publicResponseEntity< Employee>getEmployeeById(@PathVariable(value="id") LongemployeeId)
    throwsResourceNotFoundException {
    Employeeemployee=employeeRepository.findById(employeeId)
       .orElseThrow(() ->newResourceNotFoundException("Employee not found for this id :: "+employeeId));
    returnResponseEntity.ok().body(employee);
    }
    

    @PostMapping

    @PostMapping annotation for mapping HTTP POST requests onto specific handler methods.

    Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).

    Example:

    @PostMapping("/employees")
    publicEmployeecreateEmployee(@Valid@RequestBodyEmployee employee) {
    returnemployeeRepository.save(employee);
    }
    

    @PutMapping

    @PutMapping annotation for mapping HTTP PUT requests onto specific handler methods.

    Specifically, @PutMapping is a composed annotation that acts as a shortcut for ,@RequestMapping(method = RequestMethod.PUT).

    Example:

    @PutMapping("/employees/{id}")
    publicResponseEntity< Employee>updateEmployee(@PathVariable(value="id") LongemployeeId,
    @Valid@RequestBodyEmployeeemployeeDetails) throws ResourceNotFoundException {
    Employeeemployee=employeeRepository.findById(employeeId)
     .orElseThrow(() ->newResourceNotFoundException("Employee not found for this id :: "+employeeId));
    
    employee.setEmailId(employeeDetails.getEmailId());
    employee.setLastName(employeeDetails.getLastName());
    employee.setFirstName(employeeDetails.getFirstName());
    finalEmployeeupdatedEmployee=employeeRepository.save(employee);
    returnResponseEntity.ok(updatedEmployee);
    }
    

    @DeleteMapping

    @DeleteMapping annotation for mapping HTTP DELETE requests onto specific handler methods.

    Specifically, @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).

    Example:

    @DeleteMapping("/employees/{id}")
    publicMap< String, Boolean>deleteEmployee(@PathVariable(value="id") LongemployeeId)
    throwsResourceNotFoundException {
    Employeeemployee=employeeRepository.findById(employeeId)
       .orElseThrow(() ->newResourceNotFoundException("Employee not found for this id :: "+employeeId));
    
    employeeRepository.delete(employee);
    Map< String, Boolean> response =newHashMap<>();
    response.put("deleted", Boolean.TRUE);
    return response;
    }
    

    @PatchMapping

    @PatchMapping annotation for mapping HTTP PATCH requests onto specific handler methods.

    Specifically, @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).

    Example:

    @PatchMapping("/patch")
    public@ResponseBodyResponseEntity< String> patch() {
    returnnewResponseEntity< String>("PATCH Response", HttpStatus.OK);
    }
    

    @ControllerAdvice

    @ControllerAdvice annotation is a specialization of @Component. The classes annotated with @ControllerAdvice are auto-detected by classpath scanning.

    The use of @ControllerAdvice is advising all or selected controllers for @ExceptionHandler, @InitBinder, and @ModelAttribute. What we have to do is create a class annotated with @ControllerAdvice and create a required method which will be annotated with @ExceptionHandler for global exception handling, @InitBinder for global init binding and @ModelAttribute for global model attributes addition. Whenever a request comes to a

    controller and its method with @RequestMapping and if there is no locally defined @ExceptionHandler, @InitBinder and @ModelAttribute, the globally defined class annotated with @ControllerAdvice is served.

    Here’s a quick example of what that looks like:

    @ControllerAdvice(basePackages= {"com.javaguides.springmvc.controller"} )
    publicclassGlobalControllerAdvice {
    @InitBinder
    publicvoiddataBinding(WebDataBinderbinder) {
    SimpleDateFormatdateFormat=newSimpleDateFormat("dd/MM/yyyy");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, "dob", newCustomDateEditor(dateFormat, true));
     }
    @ModelAttribute
    publicvoidglobalAttributes(Modelmodel) {
    model.addAttribute("msg", "Welcome to My World!");
            }
    @ExceptionHandler(FileNotFoundException.class)
    publicModelAndViewmyError(Exceptionexception) {
    ModelAndViewmav=newModelAndView();
    mav.addObject("exception", exception);
    mav.setViewName("error");
    returnmav;
     }
    }
    

    @ResponseBody Annotation

    When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the HTTP response automatically. Each method in the Controller class must be annotated with @ResponseBody.

    The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

    For example,

    @ResponseBody
    @RequestMapping("/hello")
    Stringhello() {
    return"Hello World!";
    }
    

    Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations.

    @ExceptionHandler

    @ExceptionHandler annotation for handling exceptions in specific handler classes and/or handler methods.

    Handler methods which are annotated with this annotation are allowed to have very flexible signatures.

    Spring calls this method when a request handler method throws any of the specified exceptions. The caught exception can be passed to the method as an argument:

    @ExceptionHandler(ResourceNotFoundException.class)
    publicResponseEntity<?>resourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
    ErrorDetailserrorDetails=newErrorDetails(newDate(), ex.getMessage(), request.getDescription(false));
    returnnewResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
    }
    

    @ResponseStatus

    We can specify the desired HTTP status of the response if we annotate a request handler method with this annotation. We can declare the status code with the code argument, or its alias, the value argument.

    Also, we can provide a reason using the reason argument.

    We also can use it along with @ExceptionHandler:

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ResourceNotFoundException.class)
    publicResponseEntity<?>resourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
    ErrorDetailserrorDetails=newErrorDetails(newDate(), ex.getMessage(), request.getDescription(false));
    returnnewResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
    }
    

    @PathVariable

    This annotation indicates that a method argument is bound to a URI template variable. We can specify the URI template with the @RequestMapping annotation and bind a method argument to one of the template parts with @PathVariable.

    We can achieve this with the name or its alias, the value argument:

    @RequestMapping("/{id}")
    publicUsergetUser(@PathVariable("id") long id) {
    // ...
    }
    

    If the name of the part in the template matches the name of the method argument, we don’t have to specify it in the annotation:

    @RequestMapping("/{id}")
    publicUsergetUser(@PathVariablelong id) {
    // ...
    }
    

    Moreover, we can mark a path variable optional by setting the argument required to false:

    @RequestMapping("/{id}")
    publicUsergetUser(@PathVariable(required=false) long id) {
    // ...
    }
    

    @RequestParam

    @RequestParam annotation which indicates that a method parameter should be bound to a web request parameter. We use @RequestParam for accessing HTTP request parameters:

    @RequestMapping
    VehiclegetVehicleByParam(@RequestParam("id") long id) {
    // ...
    }
    

    It has the same configuration options as the @PathVariable annotation.

    In addition to those settings, with @RequestParam we can specify an injected value when Spring finds no or empty value in the request. To achieve this, we have to set the default value argument.

    Providing a default value implicitly sets required to false:

    @RequestMapping("/buy")
    CarbuyCar(@RequestParam(defaultValue="5") intseatCount) {
    // ...
    }
    

    Apply now for Advanced Java Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.