People Who Code | Blog

Learning Is Never Ending Process

▼

Java with Angular interview topics and practical code examples tailored for someone with 5 years of experience

Skip to content

You said:

๐Ÿ”ง 1. Java (Spring Boot) Core Topics

๐ŸŸฉ Topics

  • Spring Boot fundamentals (annotations, starters, auto-configuration)

  • REST API development

  • Exception handling (ControllerAdvice)

  • Spring Security & JWT

  • JPA/Hibernate – relationships, criteria queries

  • Transactions and Isolation Levels

  • Microservices architecture

  • Unit & Integration Testing (JUnit, Mockito)

  • OpenAPI/Swagger

๐Ÿงช Practical Question

Q: How would you design a RESTful service to manage products using Spring Boot and JPA?

@RestController @RequestMapping("/api/products") public class ProductController { @Autowired private ProductService productService; @PostMapping public ResponseEntity<Product> createProduct(@RequestBody Product product) { return new ResponseEntity<>(productService.save(product), HttpStatus.CREATED); } @GetMapping public List<Product> getAll() { return productService.findAll(); } // etc. }

๐ŸŽจ 2. Angular Topics

๐ŸŸฉ Topics

  • Components, Services, Modules

  • Reactive Forms vs Template-driven Forms

  • RxJS Observables & Subjects

  • HTTPClient with interceptors

  • Angular Routing (Lazy loading, Guards)

  • Angular Material/PrimeNG usage

  • State management (NgRx basics or simple service-based state)

  • Lifecycle hooks and change detection

๐Ÿงช Practical Question

Q: Create a form using Angular Reactive Forms to submit a product to the backend.

productForm = this.fb.group({ name: ['', Validators.required], price: [0, Validators.min(1)], category: ['', Validators.required] }); onSubmit() { if (this.productForm.valid) { this.http.post('/api/products', this.productForm.value) .subscribe(res => console.log('Saved!', res)); } }

๐Ÿ”— 3. Integration – Java + Angular

๐ŸŸฉ Topics

  • CORS configuration in Spring Boot

  • Serving Angular app from Spring Boot

  • REST communication using Angular HTTPClient

  • JWT authentication and token passing

  • Global error handling

๐Ÿงช Practical Question

Q: How do you handle JWT authentication between Angular and Spring Boot?

  • Generate token in Spring Boot on login.

  • Store it in Angular (localStorage or sessionStorage)

  • Use HTTP Interceptor in Angular to attach token.

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem('token'); if (token) { req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); } return next.handle(req); }

๐Ÿงช 4. Advanced Concepts

๐ŸŸฉ Topics

  • API Versioning

  • Exception handling using @ControllerAdvice

  • Custom annotations in Spring

  • Angular Performance: Lazy loading, OnPush

  • Unit Testing Angular Services/Components (Jasmine, Karma)

๐Ÿงช Practical Question

Q: How would you structure a multi-module Spring Boot project to support microservices?

Structure:

/product-service /src/main/java/com.example.product /controller, /service, /repository /user-service ... /gateway-service (Zuul/Spring Cloud Gateway)

๐Ÿ› ️ 5. Tools and DevOps Knowledge

๐ŸŸฉ Topics

  • Maven/Gradle build process

  • Dockerizing Spring Boot and Angular

  • Swagger/OpenAPI documentation

  • Jenkins pipelines (if CI/CD experience)

  • SonarQube (code quality)


๐Ÿ” 6. Sample Project Interview Scenario

“Build an e-commerce admin dashboard that allows CRUD for products, categories, and users. Secure it with JWT. Use Angular Material for the UI. Backend must expose REST APIs and store data in a PostgreSQL database.”

You should be prepared to:

  • Design the database schema (JPA entities)

  • Build backend APIs

  • Secure APIs with Spring Security

  • Build Angular components (product list, product form)

  • Connect frontend to backend


If you'd like a complete mini project or need mock questions with answers, I can prepare those as well. Let me know the focus (Java-heavy, Angular-heavy, or full-stack).

You said:
ChatGPT said:

Great! Since you're aiming for Java with Angular (5 years experience) and mentioned interest in a complete mini project or mock interview questions, here's what I can provide:


✅ Let’s go with a Full-Stack Mini Project + Mock Interview Q&A Set.


๐Ÿ“ฆ Mini Project: Product Management System (Full Stack)

๐Ÿ”ง Tech Stack:

  • Backend: Java 17, Spring Boot 3.x, JPA (Hibernate), Spring Security + JWT

  • Frontend: Angular 16+, Angular Material, RxJS

  • Database: H2 (for simplicity), or PostgreSQL

  • Build Tool: Maven

  • Testing: JUnit 5, Mockito, Jasmine/Karma


๐Ÿงฉ Project Features

๐Ÿ–ฅ️ Angular Frontend:

  • Login form with JWT authentication

  • Product List page with filters

  • Product Add/Edit form using Reactive Forms

  • Angular services to communicate with REST API

  • Route guards for secure pages

  • Material UI with responsive layout

⚙️ Spring Boot Backend:

  • JWT-secured REST APIs for product CRUD

  • User login endpoint for token generation

  • JPA entities: User, Product

  • Role-based access (ADMIN, USER)

  • Global exception handling with @ControllerAdvice

  • DTO usage with ModelMapper


๐Ÿ“‚ Project Structure Overview

Spring Boot (Backend)

src/main/java/com/example/productapi ├── config │ └── SecurityConfig.java ├── controller │ └── ProductController.java │ └── AuthController.java ├── dto │ └── ProductDTO.java ├── entity │ └── Product.java │ └── User.java ├── repository │ └── ProductRepository.java ├── service │ └── ProductService.java ├── util │ └── JwtUtil.java

Angular (Frontend)

src/app/ ├── auth/ │ └── login.component.ts ├── product/ │ └── product-list.component.ts │ └── product-form.component.ts ├── services/ │ └── auth.service.ts │ └── product.service.ts ├── guards/ │ └── auth.guard.ts

๐Ÿš€ Sample Code Snippets

๐Ÿ”’ Spring Boot – JWT Authentication Setup

@RestController @RequestMapping("/api/auth") public class AuthController { @Autowired AuthenticationManager authManager; @Autowired JwtUtil jwtUtil; @PostMapping("/login") public ResponseEntity<?> login(@RequestBody AuthRequest request) { Authentication auth = authManager.authenticate( new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())); String token = jwtUtil.generateToken(auth.getName()); return ResponseEntity.ok(new AuthResponse(token)); } }

๐Ÿ“‹ Angular – Product Service with Auth Header

getAllProducts(): Observable<Product[]> { return this.http.get<Product[]>(`${this.baseUrl}/products`, { headers: new HttpHeaders({ Authorization: `Bearer ${this.authService.getToken()}` }) }); }

๐Ÿง  Mock Interview Questions & Answers

๐Ÿ“Œ Backend (Java + Spring Boot)

Q1: What are the key differences between @RestController and @Controller?

@RestController combines @Controller and @ResponseBody, making it suitable for REST APIs. It automatically serializes responses into JSON.


Q2: How do you handle exceptions globally in Spring Boot?

@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(EntityNotFoundException.class) public ResponseEntity<String> handleNotFound(EntityNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); } }

Q3: How do you secure REST APIs using JWT in Spring Boot?

  • Use Spring Security filters to intercept requests

  • Generate a JWT on login

  • Store the token in the frontend (usually in localStorage)

  • Send token via Authorization: Bearer header


๐Ÿ“Œ Frontend (Angular)

Q1: How do you handle HTTP errors globally?

@Injectable() export class ErrorInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe( catchError(err => { alert('Error: ' + err.statusText); return throwError(() => err); }) ); } }

Q2: Explain difference between BehaviorSubject and Subject.

BehaviorSubject stores the latest value and emits it to new subscribers immediately. Subject does not store any value.


Q3: What is lazy loading and why is it useful?

Lazy loading loads Angular modules only when they are needed. This improves app performance by reducing the initial bundle size.


๐Ÿ”ง DevOps / Project Structure

Q1: How do you deploy Angular with Spring Boot?

  • Build Angular with ng build --prod

  • Copy /dist to src/main/resources/static

  • Spring Boot serves Angular via index.html


If you're interested, I can prepare:

  • A GitHub-ready mini project template

  • A PDF mock interview document with 30+ questions and answers

  • A step-by-step deployment guide (Docker or CI/CD)

Would you like the code base, the interview question set, or both?

You said:
ChatGPT said:

Sure! Let’s walk through each feature of the Product Management System project and explain it with examples—both backend (Java Spring Boot) and frontend (Angular). This will simulate what you'd build and explain in a real interview.


๐ŸŽฏ Project Features – Explained with Examples


✅ 1. Login with JWT Authentication

๐Ÿ“ Feature:

Allow users to log in with a username and password. If valid, return a JWT token which will be used to access other protected APIs.


๐Ÿ”ง Backend (Spring Boot):

@PostMapping("/login") public ResponseEntity<?> login(@RequestBody LoginRequest request) { Authentication auth = authManager.authenticate( new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())); String jwt = jwtUtil.generateToken(auth.getName()); return ResponseEntity.ok(new AuthResponse(jwt)); }

๐Ÿ” JWT Utility:

public String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) // 1 hour .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); }

๐Ÿง‘‍๐Ÿ’ป Frontend (Angular):

login() { this.http.post<{ token: string }>('api/auth/login', this.loginForm.value).subscribe(res => { localStorage.setItem('token', res.token); this.router.navigate(['/products']); }); }

✅ 2. Product List Page with Filters

๐Ÿ“ Feature:

Show all products in a table with filtering options by name or category.


๐Ÿ”ง Backend:

@GetMapping("/products") public List<Product> getAll(@RequestParam Optional<String> name) { if (name.isPresent()) { return productRepo.findByNameContaining(name.get()); } return productRepo.findAll(); }

๐Ÿง‘‍๐Ÿ’ป Frontend:

searchByName(name: string) { return this.http.get<Product[]>(`/api/products?name=${name}`); }

๐Ÿ“บ UI:

<mat-form-field> <input matInput placeholder="Search" (input)="search($event.target.value)"> </mat-form-field> <table mat-table [dataSource]="products">...</table>

✅ 3. Add/Edit Product Form (Reactive Forms)

๐Ÿ“ Feature:

Allow user to add a new product or edit an existing one.


๐Ÿง‘‍๐Ÿ’ป Angular Reactive Form:

form = this.fb.group({ id: [null], name: ['', Validators.required], price: [0, [Validators.required, Validators.min(1)]], category: ['', Validators.required] }); submit() { if (this.form.valid) { this.productService.save(this.form.value).subscribe(() => this.router.navigate(['/products'])); } }

๐Ÿ”ง Backend Save Endpoint:

@PostMapping("/products") public Product save(@RequestBody Product product) { return productRepo.save(product); }

✅ 4. Angular Services & HTTP Interceptors

๐Ÿ“ Feature:

Use services for HTTP communication and interceptors to automatically attach JWT tokens to requests.


Angular Interceptor:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem('token'); if (token) { req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); } return next.handle(req); }

✅ 5. Route Guards for Secure Pages

๐Ÿ“ Feature:

Protect routes like /products from unauthorized access.


Angular Route Guard:

canActivate(): boolean { const token = localStorage.getItem('token'); if (!token) { this.router.navigate(['/login']); return false; } return true; }

Routing Module:

{ path: 'products', component: ProductListComponent, canActivate: [AuthGuard] }

✅ 6. Role-based Access Control (Spring Security)

๐Ÿ“ Feature:

Restrict certain endpoints (like add/edit product) only to users with ROLE_ADMIN.


Backend:

@PreAuthorize("hasRole('ADMIN')") @PostMapping("/products") public Product create(@RequestBody Product product) { return productRepo.save(product); }

✅ 7. Angular Material UI

๐Ÿ“ Feature:

Use Material Design to create a modern UI: tables, buttons, dialogs.


Example:

<mat-card> <mat-card-title>Product List</mat-card-title> <button mat-raised-button color="primary" (click)="addProduct()">Add Product</button> </mat-card> <mat-table [dataSource]="products"> <ng-container matColumnDef="name"> <mat-header-cell *matHeaderCellDef>Name</mat-header-cell> <mat-cell *matCellDef="let p">{{p.name}}</mat-cell> </ng-container> </mat-table>

✅ 8. Global Exception Handling

๐Ÿ“ Feature:

Catch all errors globally in the backend and return standard responses.


Java Spring:

@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<String> handleAll(RuntimeException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error: " + ex.getMessage()); } }

✅ 9. Testing Support

๐Ÿ“ JUnit Example:

@Test public void testCreateProduct() { Product product = new Product("Laptop", 1000.0, "Electronics"); when(repo.save(any(Product.class))).thenReturn(product); Product created = productService.create(product); assertEquals("Laptop", created.getName()); }

๐Ÿ“ Angular Unit Test:

it('should call save product', () => { spyOn(service, 'save').and.returnValue(of({})); component.form.setValue({ name: 'Test', price: 100, category: 'Test' }); component.submit(); expect(service.save).toHaveBeenCalled(); });

✅ Summary

FeatureAngular ExampleSpring Boot Example
Login with JWTauth.service.ts/api/auth/login
Product CRUDproduct.service.ts, Reactive Form/api/products
Route GuardsAuthGuardSpring Security Config
Global Error HandlingErrorInterceptor@ControllerAdvice
Role-Based AccessUI hides buttons; Guard routes@PreAuthorize("hasRole('ADMIN')")
Material UImat-card, mat-table, dialogs—
Exception HandlingToast/snackbarsGlobalExceptionHandler
TestingJasmine/KarmaJUnit, Mockito

Would you like me to:

  1. Generate a GitHub project structure for this?

  2. Prepare a downloadable ZIP code template?

  3. Create a PDF/Word summary document with this info?

Let me know what format suits you best!

You said:
if interviewer can explanation what is Interceptors above all question explanation as deep
ChatGPT said:

Here’s an in‑depth breakdown of Angular HTTP Interceptors, perfect for impressing an interviewer:


๐Ÿง  What Are Interceptors?

Angular’s HTTP interceptors act as middleware for HttpClient, letting you intercept, inspect, or modify every outgoing request and incoming response across the app reddit.com+15angular.dev+15kevinschuchard.com+15reddit.com+4geeksforgeeks.org+4reddit.com+4. They're ideal for embedding cross-cutting behavior like logging, authentication, error handling, caching, or performance monitoring.


๐Ÿ”— Request–Response Pipeline

Multiple interceptors can form a chain. Requests flow through them in registration order (e.g., A → B → C), and responses flow back in reverse (C → B → A) geeksforgeeks.orgkevinschuchard.com.


๐Ÿ”„ How to Modify Requests

HttpRequest objects are immutable. To modify (say, add headers), you .clone() the request with your changes before passing it down the chain via next.handle() thetiwari-tiwari01.medium.com+7angular.dev+7kevinschuchard.com+7:

const authReq = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) }); return next.handle(authReq);

⚙️ Interceptor Use Cases

  1. Authentication Tokens
    Automatically attach JWT or other tokens to every API request reddit.com+8geeksforgeeks.org+8momentslog.com+8.

  2. Global Error Handling
    Intercept error responses, e.g., redirect on 401 Unauthorized or show a standardized error toast reddit.com+6geeksforgeeks.org+6medium.com+6.

  3. Logging & Profiling
    Log request URLs, timings, response status to console or tracking services .

  4. Caching
    For GET requests, return cached responses rather than hitting the server repeatedly reddit.com+12geeksforgeeks.org+12runebook.dev+12.

  5. Retry / Circuit Breakers
    Retry failed network requests or implement backoff strategies, though avoid naรฏve global retries browserstack.com+6reddit.com+6reddit.com+6.

  6. URL Rewriting / Versioning
    Prepend base URLs or API versions programmatically reddit.com+4geeksforgeeks.org+4reddit.com+4.


๐Ÿ› ️ Advanced Techniques

  • Conditional Logic using HttpContextToken: skip token injection or caching for selected endpoints reddit.com+8angular.dev+8reddit.com+8.

  • Token Refresh Handling: catch 401, pause queued requests, refresh the token once, then retry the original request using streams like BehaviorSubject and switchMap geeksforgeeks.org+2reddit.com+2requestly.com+2.

  • Mocking in development: intercept certain URLs and return fake HttpResponse() without contacting the server thetiwari-tiwari01.medium.com.


๐Ÿงฉ Sample Interceptor Skeleton

@Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private auth: AuthService) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = this.auth.getToken(); const cloned = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req; return next.handle(cloned).pipe( tap(event => { if (event.type === HttpEventType.Response) { console.log('Response from', req.url, 'status', event.status); } }), catchError(err => { if (err.status === 401) this.auth.logout(); return throwError(err); }) ); } }

✅ Why Use Interceptors?

BenefitDescription
DRYAvoid repeating header setup, error handling, logs across each service
CentralizedManage concerns like auth, error flows or caching in one place
ComposableAdd/remove logic by ordering piped interceptors
Immutable SafetyClone pattern ensures safe, predictable behavior even with retries

๐Ÿšฆ Interview-Ready Notes

  • Interceptors use a chain-of-responsibility pattern, processing in order and returning in reverse stackoverflow.com+9kevinschuchard.com+9reddit.com+9geeksforgeeks.org+1reddit.com+1.

  • You must clone requests/responses when altering them.

  • They're ideal for handling cross-cutting concerns—logic consistent across the app (auth, logging, caching) kevinschuchard.comreddit.com.

  • Guard against pitfalls, e.g. retry loops without backoff, handling concurrent token refresh, or accidentally intercepting admin vs public endpoints.


๐Ÿ“Œ TL;DR

An Angular HTTP interceptor is a powerful middleware construct enabling you to centralize and modularize HTTP concerns—like authentication, error handling, logging, or caching—by intercepting each request and response. They support immutability, chaining order, dependency injection, and advanced patterns such as token refresh coordination. Mastery of interceptors is a strong hallmark of a senior Angular engineer!

Let me know if you'd like practical code deep dives or interview-style questions around this!

at July 02, 2025
Share

No comments:

Post a Comment

‹
›
Home
View web version

About Me

My photo
Hi, I’m Vijay Chauhan, a web developer from India in love with all things internet. Online since 2015.
View my complete profile
Powered by Blogger.