👉 Understanding @PathVariable vs @RequestParam While building REST APIs in Spring Boot, we often need to send data from the URL to the controller. Two common ways to do this are: ➡ @PathVariable ➡ @RequestParam 🔹 1. @PathVariable @PathVariable is used to extract values directly from the URL path. Example URL: http://localhost:8080/users/10 Example Code: @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User ID: " + id; } ✔ Used when the value is part of the resource path ✔ Common in RESTful APIs 🔹 2. @RequestParam @RequestParam is used to extract query parameters from the URL. Example URL: http://localhost:8080/users?id=10 Example Code: @GetMapping("/users") public String getUser(@RequestParam int id) { return "User ID: " + id; } ✔ Used for filtering, searching, or optional parameters 🧠 Simple Way to Remember 👉 PathVariable → Part of URL path 👉 RequestParam → Extra data in query #SpringBoot #Java #RestAPI #BackendDevelopment #LearningInPublic #JavaDeveloper
Spring Boot REST API: @PathVariable vs @RequestParam
More Relevant Posts
-
When working with APIs, you often need to pass data in the request. Spring Boot provides two common ways: @PathVariable and @RequestParam Example: @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User ID: " + id; } Here, id is part of the URL. Now using RequestParam: @GetMapping("/users") public String getUser(@RequestParam int id) { return "User ID: " + id; } Difference: • @PathVariable → part of URL path • @RequestParam → query parameter Example URLs: /users/10 → PathVariable /users?id=10 → RequestParam Choosing the right one improves API design. Next post: What is @RequestBody and how JSON is handled #Java #SpringBoot #BackendDevelopment #APIDesign
To view or add a comment, sign in
-
-
#Post4 In the previous post, we understood how request mapping works using @GetMapping and others. Now the next question is 👇 How does Spring Boot handle data sent from the client? That’s where @RequestBody comes in 🔥 When a client sends JSON data → it needs to be converted into a Java object. Example request (JSON): { "name": "User", "age": 25 } Controller: @PostMapping("/user") public User addUser(@RequestBody User user) { return user; } 👉 Spring automatically converts JSON → Java object This is done using a library called Jackson (internally) 💡 Why is this useful? • No manual parsing needed • Clean and readable code Key takeaway: @RequestBody makes it easy to handle request data in APIs 🚀 In the next post, we will understand @PathVariable and @RequestParam 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
When building APIs in Spring Boot, you’ll see multiple mapping annotations. But what’s the difference? @RequestMapping → Generic mapping (can handle all HTTP methods) @GetMapping → Used for GET requests (fetch data) @PostMapping → Used for POST requests (create data) Example: @RestController @RequestMapping("/users") public class UserController { @GetMapping public List<String> getUsers() { return List.of("A", "B"); } @PostMapping public String createUser() { return "User created"; } } Modern Spring Boot prefers specific annotations like @GetMapping for clarity. Rule of thumb: GET → Read POST → Create PUT → Update DELETE → Remove Next post: What is @PathVariable and @RequestParam #Java #SpringBoot #APIDevelopment #BackendDevelopment
To view or add a comment, sign in
-
Day 20: 🧑💻 Read Replicas - Scale Reads Horizontally, Free the Primary (Java + Spring Boot) What Are Read Replicas? Read Replicas are copies of your primary database that continuously receive updates via replication (WAL streaming / binary log). All writes go to the primary; reads are distributed across replicas — offloading the primary and enabling horizontal read scale. Without Replicas: All traffic → Single Primary 90% reads + 10% writes fighting for same connections Primary saturates → everything slows down With Read Replicas: Writes → Primary only Reads → Replica 1, Replica 2, Replica 3 (load balanced) Primary free for writes → faster writes Add replicas = scale reads linearly Key Takeaways — Plain English : 1. Read Replicas = copies of primary — receive updates via replication 2. All writes → Primary — replicas are read-only 3. All reads → Replicas — offloads primary, enables horizontal scale 4. readOnly=true = Spring routes automatically to replica via AbstractRoutingDataSource 5. Replica lag= milliseconds behind primary — eventual consistency 6. Read-after-write = don't write then immediately read from replica 7. Failover = if primary fails, promote replica (RDS/Aurora does this automatically) 8. Monitor lag = SELECT EXTRACT(EPOCH FROM now()-pg_last_xact_replay_timestamp()); 9. Rule: every SELECT-only method should have @Transactional(readOnly=true) — no exceptions #SystemDesign #ReadReplicas #Database #PostgreSQL #SpringBoot #Java #Microservices
To view or add a comment, sign in
-
Hi everyone 👋 Continuing the Spring Boot Annotation Series 👇 📌 Spring Boot Annotation Series part 24 – @ResponseBody @ResponseBody is used to return data directly in the HTTP response body instead of returning a view (HTML page). It is part of the Spring Framework and is commonly used in REST APIs built with Spring Boot. 🔹 Why do we use @ResponseBody? In Spring MVC: Without @ResponseBody → returns a view (HTML/JSP) With @ResponseBody → returns data (JSON/XML) 👉 It is mainly used for building REST APIs. 🔹 Simple Example @Controller public class UserController { @GetMapping("/user") @ResponseBody public String getUser() { return "User details"; } } 👉 Output will be directly shown in response body, not a view. 🔹 Returning Object as JSON @GetMapping("/user") @ResponseBody public User getUser() { return new User(1, "Asmita"); } 👉 Spring automatically converts it into JSON. 🔹 How does it work? - Spring uses Jackson library internally - Converts Java object → JSON - Sends it in HTTP response 🔹 In Simple Words @ResponseBody tells Spring to send data directly in the response instead of returning a web page. 👉 🧠 Quick Understanding - Returns data, not view - Converts object → JSON - Used in REST APIs - Not needed with @RestController #SpringBoot #Java #ResponseBody #RESTAPI #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
💥Exception Handling in Spring Boot 🚀 When building REST APIs, things can go wrong — invalid input, missing data, or server errors. Instead of returning raw error messages, Spring Boot allows us to handle exceptions in a structured and clean way. This is called Exception Handling. 🔹 What is Exception Handling? Exception Handling is the process of managing errors in an application so that users receive meaningful responses instead of application crashes. Example errors: ->Resource not found ->Invalid request ->Database errors 🔹 Ways to Handle Exceptions in Spring Boot 1️⃣ Using @ExceptionHandler Used inside a controller to handle specific exceptions. Example: @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Something went wrong"); } ✔ Handles exceptions locally in a controller. 2️⃣ Using @ControllerAdvice (Global Exception Handling) Handles exceptions across the entire application. Example: @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<String> handleResourceNotFound() { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("Resource not found"); } } ✔ Centralized exception handling ✔ Cleaner architecture 3️⃣ Using @RestControllerAdvice Same as @ControllerAdvice, but automatically returns JSON responses. Example: @RestControllerAdvice public class GlobalExceptionHandler { } ✔ Best for REST APIs 🔄 Exception Handling Flow: Client Request ⬇ Controller ⬇ Exception Occurs ⬇ Exception Handler (@ExceptionHandler) ⬇ Custom Error Response Returned 🧠 Simple Understanding Exception Handling helps us send clean and meaningful error responses to clients instead of server crashes. #SpringBoot #Java #BackendDevelopment #ExceptionHandling #RestAPI #LearningInPublic #JavaDeveloper
To view or add a comment, sign in
-
-
#Post3 In the previous post, we understood the role of @RestController in building APIs. Now the next step is 👇 How do we map HTTP requests to methods? That’s where mapping annotations come in 🔥 In Spring Boot, we use: • @GetMapping → for GET requests • @PostMapping → for POST requests • @PutMapping → for UPDATE • @DeleteMapping → for DELETE • @PatchMapping → for partial updates Example: @GetMapping("/users") → fetch all users @PostMapping("/users") → create a new user 💡 What about @RequestMapping? @RequestMapping is a generic annotation that can handle all HTTP methods. Example: @RequestMapping(value="/users", method=RequestMethod.GET) 👉 But in modern Spring Boot, we prefer specific annotations like @GetMapping for cleaner and readable code Key takeaway: Use specific mapping annotations for better clarity and maintainability 👍 In the next post, we will understand how @RequestBody works in handling request data 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
🗂️ HashMap vs LinkedList: Which one and when? Two of the most commonly used Java data structures. But most devs reach for one without really thinking about the other. Here's the breakdown: ⚡ HashMap : → O(1) average for get/put/remove → Hash Table internals — array of buckets with chaining → Java 8+: bucket chains treeify at 8 collisions → O(log n) worst case → No ordering, one null key, load factor 0.75 → Use for: caching, frequency maps, fast key lookups 🔗 LinkedList: → Doubly linked nodes — implements both List and Deque → O(1) at head/tail — O(n) for random access → No resizing overhead, but poor cache locality → Use for: Queue, Stack, Deque, LRU Cache, Undo/Redo 🔑 Classic combo — LRU Cache: HashMap for O(1) lookup + LinkedList for recency order = O(1) full cache Quick rules: Need key-value fast lookup? → HashMap Need ordered? → LinkedHashMap or TreeMap Need queue/stack/deque? → LinkedList (or ArrayDeque for pure stack/queue) Never use LinkedList.get(index) — it's O(n) every time #Java #DataStructures #DSA #SystemDesign #SpringBoot #BackendDevelopment #SoftwareEngineering #JavaDeveloper #Programming
To view or add a comment, sign in
-
-
When working with Spring Boot + JPA, we often use derived methods like: • findByName() • findByEmail() But what happens when your requirement gets a bit complex? • That’s where JPA Custom Queries come in. 💡 What is a Custom Query? • Used when method naming is not enough • Helps you write your own queries using @Query • Gives more control over data fetching (JPQL or SQL) Example • Fetch users based on email domain (e.g., Gmail users) @Repository public interface UserRepository extends JpaRepository<User, Long> { @Query("SELECT u FROM User u WHERE u.email LIKE %:domain") List<User> findUsersByEmailDomain(@Param("domain") String domain); } 🔍 How it works • @Query → Define custom query • :domain → Dynamic parameter • % → Wildcard for pattern matching • Usage: userRepository.findUsersByEmailDomain("@gmail.com"); • Returns all users with Gmail accounts ⚡ Bonus: Native Query (SQL) @Query(value = "SELECT * FROM users WHERE age > :age", nativeQuery = true) List<User> findUsersAboveAge(@Param("age") int age); 🎯 When should you use Custom Queries? • Complex filtering conditions • Joins between multiple tables • Performance optimization • When method names become too long Final Takeaway • Derived Queries → Simple & quick • Custom Queries → Powerful & flexible #Java #SpringBoot #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #JavaDeveloper #Coding #Programming #Developers #TechCommunity #LearnToCode #SystemDesign #DSA #CodingJourney
To view or add a comment, sign in
-
New to Spring Boot? You'll see these annotations in every project. Here's what they actually do: @SpringBootApplication → Entry point. Combines @Configuration, @EnableAutoConfiguration, @ComponentScan @RestController → Marks a class as an HTTP request handler that returns data (not views) @Service → Business logic layer. Spring manages it as a bean @Repository → Data access layer. Also enables Spring's exception translation @Autowired → Inject a dependency automatically (prefer constructor injection instead) @GetMapping / @PostMapping / @PutMapping / @DeleteMapping → Maps HTTP methods to your handler methods @RequestBody → Deserializes JSON from request body into a Java object @PathVariable → Extracts values from the URL path Bookmark this. You'll refer back to it constantly. Which annotation confused you the most when starting out? 👇 #Java #SpringBoot #Annotations #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development