📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
- Spring Core Annotations
- Spring Web Annotations (current article)
- Spring Boot Annotations
- Spring Scheduling Annotations
Before you get started, check out Spring Data JPA Tutorial and Spring MVC Tutorial
Spring MVC Tutorials and Articles :
- Spring MVC 5 - Hello World Example
- Spring MVC 5 - Sign Up Form Handling Example
- Spring MVC JSP Form Tags Tutorial
- Spring MVC 5 Form Validation with Annotations Tutorial
- Spring MVC 5 + Hibernate 5 + JSP + MySQL CRUD Tutorial
- Spring MVC 5 + Spring Data JPA + Hibernate 5 + JSP + MySQL Tutorial
- Spring MVC + Spring Boot2 + JSP + JPA + Hibernate 5 + MySQL Example
- Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example
- Spring MVC + Spring Boot2 + JSP + JPA + Hibernate 5 + MySQL Example
- Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example
- Spring Boot 2 - Spring MVC + Thymeleaf Input Form Validation
- Spring Boot 2 + Spring MVC + Spring Security + JPA + Thymeleaf + MySQL Tutorial
- Authenticating a User with LDAP using Spring Boot and Spring Security
- The Spring @Controller and @RestController Annotations with Examples
- Spring @RequestBody and @ResponseBody Annotations
- @GetMapping, @PostMapping, @PutMapping, @DeleteMapping and @PatchMapping
- Spring Web MVC Annotations
- Mini Todo Management Project using Spring Boot + Spring MVC + Spring Security
- User Registration Module using Spring Boot + Spring MVC + Spring Security + Hibernate 5
- 20+ Free Open Source Projects Using Spring Framework
@RequestBody Annotation
- Spring MVC 5 - Hello World Example
- Spring MVC 5 - Sign Up Form Handling Example
- Spring MVC JSP Form Tags Tutorial
- Spring MVC 5 Form Validation with Annotations Tutorial
- Spring MVC 5 + Hibernate 5 + JSP + MySQL CRUD Tutorial
- Spring MVC 5 + Spring Data JPA + Hibernate 5 + JSP + MySQL Tutorial
- Spring MVC + Spring Boot2 + JSP + JPA + Hibernate 5 + MySQL Example
- Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example
- Spring MVC + Spring Boot2 + JSP + JPA + Hibernate 5 + MySQL Example
- Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example
- Spring Boot 2 - Spring MVC + Thymeleaf Input Form Validation
- Spring Boot 2 + Spring MVC + Spring Security + JPA + Thymeleaf + MySQL Tutorial
- Authenticating a User with LDAP using Spring Boot and Spring Security
- The Spring @Controller and @RestController Annotations with Examples
- Spring @RequestBody and @ResponseBody Annotations
- @GetMapping, @PostMapping, @PutMapping, @DeleteMapping and @PatchMapping
- Spring Web MVC Annotations
- Mini Todo Management Project using Spring Boot + Spring MVC + Spring Security
- User Registration Module using Spring Boot + Spring MVC + Spring Security + Hibernate 5
- 20+ Free Open Source Projects Using Spring Framework
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
Read more at Spring @RequestBody and @ResponseBody Annotations
@RequestMapping
- 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
class EmployeeController {
@RequestMapping(value = "/employees/home", method = RequestMethod.GET)
String home() {
return "home";
}
}
@Controller
@RequestMapping(value = "/employees", method = RequestMethod.GET)
class EmployeeController {
@RequestMapping("/home")
String home() {
return "home";
}
}
@GetMapping
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@PostMapping
@PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
@PutMapping
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
@PatchMapping
@PatchMapping("/patch")
public @ResponseBody ResponseEntity<String> patch() {
return new ResponseEntity<String>("PATCH Response", HttpStatus.OK);
}
@ControllerAdvice
@ControllerAdvice(basePackages = {"com.javaguides.springmvc.controller"} )
public class GlobalControllerAdvice {
@InitBinder
public void dataBinding(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));
}
@ModelAttribute
public void globalAttributes(Model model) {
model.addAttribute("msg", "Welcome to My World!");
}
@ExceptionHandler(FileNotFoundException.class)
public ModelAndView myError(Exception exception) {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", exception);
mav.setViewName("error");
return mav;
}
}
Read complete example at Spring MVC Exception Handling
@ResponseBody Annotation
@ResponseBody
@RequestMapping("/hello")
String hello() {
return "Hello World!";
}
@ExceptionHandler
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> resourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@ResponseStatus
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> resourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@PathVariable
@RequestMapping("/{id}")
public User getUser(@PathVariable("id") long id) {
// ...
}
@RequestMapping("/{id}")
public User getUser(@PathVariable long id) {
// ...
}
@RequestMapping("/{id}")
public User getUser(@PathVariable(required = false) long id) {
// ...
}
@RequestParam
@RequestMapping
Vehicle getVehicleByParam(@RequestParam("id") long id) {
// ...
}
@RequestMapping("/buy")
Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
// ...
}
@Controller
@Controller
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
}
@RestController
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
}
Read more at The Spring @Controller and @RestController Annotations with Examples
@ModelAttribute
@PostMapping("/users")
void saveUser(@ModelAttribute("user") User user) {
// ...
}
@PostMapping("/users")
void saveUser(@ModelAttribute User user) {
// ...
}
@ModelAttribute("vehicle")
User getUser() {
// ...
}
@ModelAttribute
User user() {
// ...
}
@CrossOrigin
@CrossOrigin
@RequestMapping("/hello")
String hello() {
return "Hello World!";
}
@InitBinder
// add an initbinder ... to convert trim input strings
// remove leading and trailing whitespace
// resolve issue for our validation
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
}
Comments
Post a Comment
Leave Comment