
Quick Contact
Java Tutorial
- What is Java?
- History of Java
- Hello Java Program
- Features of Java
- Basic Syntax
- Java Setup
- Data Types in Java
- Java Variables
- Operators in Java
- JVM
- Java If-else Statement
- Switch Case Statement
- Java Loops
- Do-While Loop
- Java While Loop
- Continue Statement
- Break Statement in Java
- Constructors in Java
- Oops Concept in Java
- Features of OOPs
- Inheritance
- Exeception handeling
- Aggregation (HAS-A relationship) in Java
- Method Overriding in Java
- Method Overloading
- Java Static Keyword
- Java This Keyword
- Java Final Keyword
- Polymorphism
- Static Binding and Dynamic Binding
- Abstract class in Java
- Access Modifiers in Java
- Difference between abstract class and interface
- Interface in Java
- Garbage Collection in Java
- Java Package
- Encapsulation
- Serialization and Deserialization in Java
- Java Inner Classes
- Java Applets
- Multithreading in Java
- Thread Priorities in Java
- Thread Creation
- Inter Thread Communication
- Wrapper Classes in Java
- Java Input Output
- Java AWT Introduction
- Java Layout Manager
- Java Layout Policy
- Java AWT Events
- Collection Framework
- Collection Framework List Interface
- Swing in Java
- Swing Utility Classes
- Swing Layout Managers
- Java JDBC
- Hibernate Framework Overview – Architecture and Basics
Springboot
- Spring Environment Setup
- Spring Boot CRUD REST API Project using IntelliJ IDEA | Postman | MySQL
- Dockerizing Spring Boot Application | Spring Boot Docker Tutorial
- spring-boot-restapidocumentation with swagger
- Spring Boot HttpClient Overview
- Apache HttpClient POST HTTP Request Example
- Apache HttpClient PUT HTTP Request Example
- Apache HttpClient DELETE HTTP Request Example
- Apache HttpClient HTML Form POST Request Example
- Spring Boot JSP Exampl
- Deploying Spring Boot WAR file with JSP to Tomcat
- Spring Boot Annotations
- Spring Core Annotations
- Spring MVC Annotations with Examples
- Spring Scheduling Annotations
- Spring - Java-based Container Configuration
- Spring Java Based Configuration Example
Hibernate
- Hibernate 5 hello world
- Hibernate- One to One Unidirectional Mapping Annotation Example
- Hibernate - Batch Processing
- Hibernate - Interceptors
- Hibernate 5 - Create, Read, Update and Delete (CRUD) Operations Example
- Hibernate Transaction Management
- Hibernate One to Many Unidirectional Mapping Example
- Hibernate One to Many Bidirectional Mapping Example
- Hibernate Many to Many Annotation Mapping Example
- Hibernate Primary KeyJoin Column
- Hibernate First Level Cache with Example
- Hibernate XML Configuration Example with Maven + Eclipse + MySQL Database
- Hibernate Java Configuration Example
- JPA 2 with Hibernate 5 Bootstrapping Example
- JPA and Hibernate Cascade Types
- Hibernate/JPA - Primary Key Generation
- Hibernate 5 - Enum Type Mapping Example
- Hibernate Component Mapping
- Hibernate Object States – Transient,Persistent and Detached
- Hibernate 5 - Save an Entity Example
- Hibernate 5 - Persist an Entity Example
- Hibernate 5 - saveOrUpdate() Method Example
- Hibernate 5 - get(), load() and byId() Method Examples
- Hibernate 5 - merge() Example
- Hibernate 5 - Delete or Remove an Entity Example
- Hibernate 5 - load() Method Example
- Hibernate Session Interface Methods
- Hibernate Session.clear() Method Example
- Introduction Of Java strutes to Architecture
- Struts 2 - Architecture
- Struts 2 - Configuration Files
- Struts 2 - Actions
- Struts 2 - Interceptors
- Struts 2 - Results & Result Types
- Struts 2 - Value Stack/OGNL
- Struts 2 - File Uploading
- Struts 2 - Database Access
- Struts 2 - Validations Framework
JAVA FX
- JavaFX Tutorial
- Introduction to JavaFX Pane
- JavaFX Popup
- JavaFX group
- JavaFX Controller
- JavaFX Gradient Color
- JavaFXAnchorPane
- JavaFXTabPane
- JavaFX Scene
- JavaFX Stage
- JavaFXWebView
- JavaFX Timeline
- JavaFX Timer
- JavaFX Image
- JavaFX Background
- JavaFX dialog
- JavaFX Font
- JavaFXTextArea
- JavaFXObservableList
- JavaFX GUI
- JavaFX FXML
- JavaFXEventHandler
- JavaFXGradle
- JavafxScrollpane
- JavaFXAPI
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