Understanding of Mavne Structure
@Controller
- Definition: Marks a class as a Spring MVC Controller. It returns a View (like JSP, Thymeleaf) instead of JSON/XML by default.
- Used in MVC pattern for handling web requests.
- If you need REST APIs, you typically use @RestController instead.
@Controller
public class HomeController {
@RequestMapping("/home")
public String home() {
return "home"; // returns view name (home.jsp or home.html from templates)
}
}
@RestController
- Definition: Shortcut annotation = @Controller + @ResponseBody.
- Automatically serializes returned objects to JSON/XML (using Jackson by default).
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!"; // directly returns JSON response
}
}
@ResponseBody
- Definition: Tells Spring to serialize method return value into the HTTP response body.
- If not used, Spring assumes return value is a view name.
- Advantages: Converts Java objects → JSON/XML automatically using HttpMessageConverters.
@Controller
public class UserController {
@RequestMapping("/json")
@ResponseBody
public User getUser() {
return new User("Kishor", "Bhosale"); // returned as JSON
}
}
@RequestMapping and Derived Annotations
- @RequestMapping: Maps HTTP requests to handler methods/classes.
- Can define: path, method, headers, consumes, produces.
- Derived annotations:
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public String getUser(@PathVariable int id) {
return "User id: " + id;
}
@PostMapping
public String createUser(@RequestBody User user) {
return "Created user: " + user.getFirstName();
}
}
@RequestParam
- Extracts query parameters from URL.
- Supports type conversion: primitive, wrapper, String, Enum, custom objects.
- Example URL: http://localhost:8080/api/fetchUser?firstName=Kishor&lastName=Bhosale
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/fetchUser")
public String getUserDetails(
@RequestParam(required = false) String firstName,
@RequestParam(required = false) String lastName) {
return "User: " + firstName + " " + lastName;
}
}
Custom Object Conversion using @InitBinder + PropertyEditor:
public class Address {
private String city;
private String state;
// getters & setters
}
@RestController
@RequestMapping("/api")
public class AddressController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Address.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
String[] parts = text.split(",");
Address addr = new Address();
addr.setCity(parts[0]);
addr.setState(parts[1]);
setValue(addr);
}
});
}
@GetMapping("/address")
public Address getAddress(@RequestParam Address address) {
return address; // e.g. ?address=Pune,MH
}
}
@PathVariable
- Binds URI template variable to method parameter.
- Example URL: /api/users/101
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users/{id}")
public String getUser(@PathVariable("id") int userId) {
return "Fetched user id: " + userId;
}
}
@RequestBody
- Binds HTTP request body → Java object.
- Uses Jackson (default) or Gson for JSON ↔ Object conversion.
- Field mapping is done by matching JSON keys with POJO field names.
public class User {
private String firstName;
private String lastName;
// getters & setters
}
@RestController
@RequestMapping("/api")
public class UserController {
@PostMapping("/create")
public User createUser(@RequestBody User user) {
return user; // JSON → User object
}
}
@ResponseEntity
- Represents the complete HTTP response: status, headers, body.
- Provides fine-grained control compared to just returning objects.
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/status")
public ResponseEntity<String> getStatus() {
return ResponseEntity
.status(HttpStatus.OK)
.header("Custom-Header", "SpringBoot")
.body("Everything is fine!");
}
}