Spring Web/MVC
Spring Web/MVC
Beginner
Q1: What is Spring MVC?
Spring MVC is a web framework in Spring for building HTTP web apps and REST APIs using the Model-View-Controller pattern.
Q2: What does MVC stand for?
Model, View, Controller.
Q3: What is the role of the Controller?
Handle incoming HTTP requests and return responses (view or data).
Q4: What is the role of the Model in MVC?
Holds data passed between controller and view/business layers.
Q5: What is the role of the View in MVC?
Renders UI output (HTML/templates) in server-side rendered applications.
Q6: What is DispatcherServlet?
Front controller that routes requests to handlers and coordinates MVC workflow.
Q7: Why is DispatcherServlet important?
It centralizes request handling and framework integration points.
Q8: What is a HandlerMapping?
Maps incoming request to a controller method.
Q9: What is a HandlerAdapter?
Invokes the matched handler method with resolved arguments.
Q10: What is ViewResolver?
Resolves logical view names to actual template/view implementations.
Q11: What is @Controller?
Marks a class as Spring MVC controller (typically view-oriented).
Q12: What is @RestController?
Convenience annotation combining @Controller + @ResponseBody for REST APIs.
Q13: What is @RequestMapping?
Maps HTTP paths/methods/content conditions to controller classes/methods.
Q14: What are shortcut mapping annotations?
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping.
Q15: What is @PathVariable?
Binds URI path segment value to method parameter.
Q16: What is @RequestParam?
Binds query string/form parameter to method parameter.
Q17: What is @RequestBody?
Binds HTTP request payload to Java object.
Q18: What is @ResponseBody?
Writes method return value directly to HTTP response body.
Q19: What is ResponseEntity?
Represents full HTTP response with status, headers, body.
Q20: What is content negotiation?
Choosing response format (e.g., JSON/XML) based on headers and config.
Q21: Which header is key for response format negotiation?
Accept header.
Q22: Which header indicates request payload format?
Content-Type header.
Q23: What is HttpMessageConverter?
Converts request/response body between bytes and Java objects.
Q24: Default JSON converter in Spring Boot MVC?
Jackson-based converter (typically).
Q25: What HTTP status is commonly used for successful GET?
200 OK.
Q26: Common status for resource creation?
201 Created.
Q27: Common status for successful delete with no body?
204 No Content.
Q28: Common status for bad client input?
400 Bad Request.
Q29: Common status for unauthorized access?
401 Unauthorized.
Q30: Common status for forbidden action?
403 Forbidden.
Q31: Common status for missing resource?
404 Not Found.
Q32: Common status for server errors?
500 Internal Server Error.
Q33: What is @ResponseStatus?
Sets HTTP status on controller method or exception type.
Q34: What is @RequestHeader?
Binds HTTP header value to method parameter.
Q35: What is @CookieValue?
Binds cookie value to method parameter.
Q36: What is @ModelAttribute?
Binds request parameters to model object (often for forms).
Q37: What is BindingResult?
Holds binding/validation errors for model attributes/request bodies.
Q38: What is Bean Validation integration?
Using constraints annotations and @Valid / @Validated with MVC binding.
Q39: Difference between @Valid and @Validated?
@Validated supports validation groups in Spring.
Q40: What is @InitBinder?
Customizes data binding/validators for controller scope.
Q41: What is type conversion in MVC?
Converting String request input into target Java types.
Q42: What is Formatter in Spring MVC?
Locale-aware parser/printer for presentation-layer type conversion.
Q43: What is Converter in Spring?
General type conversion abstraction.
Q44: What is CORS?
Cross-Origin Resource Sharing rules for browser cross-origin requests.
Q45: How configure CORS in MVC?
Globally via configurer or per-controller/per-method annotations.
Q46: What is @CrossOrigin?
Annotation enabling/configuring CORS for endpoints.
Q47: What is PRG pattern?
Post/Redirect/Get pattern to prevent duplicate form submissions.
Q48: What is flash attribute?
Temporary attribute surviving redirect for one subsequent request.
Q49: What is redirect prefix in view return?
Returning redirect:/path triggers client redirect.
Q50: What is forward prefix?
forward:/path forwards request internally on server.
Q51: What is default method argument resolution?
Spring auto-resolves known parameter types/annotations via resolvers.
Q52: Can controllers return plain objects?
Yes, especially in REST; converter serializes them.
Q53: Can controllers return views and REST in same app?
Yes, but keep design boundaries clear.
Q54: What is static resource handling in MVC?
Serving CSS/JS/images from configured resource locations.
Q55: What is locale resolution?
Determining user locale for messages/formatting.
Q56: What is MessageSource in web apps?
Resolves i18n messages from bundles.
Q57: What is a common beginner MVC mistake?
Putting business logic directly in controllers.
Q58: Where should business logic live?
Service layer, not controller methods.
Q59: What is beginner REST endpoint best practice?
Clear resource naming, proper status codes, validated inputs.
Q60: Beginner best practice summary?
Keep controllers thin, responses explicit, and validation consistent.
Intermediate
Q61: What is HandlerInterceptor?
MVC component for pre/post processing around handler invocation.
Q62: Interceptor vs Servlet Filter?
Filter is servlet-container level; interceptor is Spring MVC handler level.
Q63: Typical interceptor use cases?
Auth context setup, request logging, correlation IDs, timing.
Q64: What interceptor methods are common?
preHandle, postHandle, afterCompletion.
Q65: Why use afterCompletion?
Cleanup resources/context even when exceptions occur.
Q66: What is ControllerAdvice?
Global component for exception handling, binder/model enhancements.
Q67: What is RestControllerAdvice?
@ControllerAdvice + @ResponseBody for REST-centric global handling.
Q68: What is @ExceptionHandler?
Method-level/global handler for specific exception types.
Q69: Why centralize exception handling?
Consistency of error payloads and reduced duplication.
Q70: What is ResponseStatusException?
Programmatic exception carrying HTTP status and reason.
Q71: What is Problem Details (RFC 7807) concept?
Standardized JSON structure for API errors.
Q72: Why adopt a standard error format?
Predictable client integration and easier troubleshooting.
Q73: What is pagination in MVC REST?
Splitting large collections into pages with limit/offset or cursor parameters.
Q74: Why paginate endpoints?
Performance, bandwidth control, and client usability.
Q75: What is sorting support pattern?
Accepting sort fields/directions as query params with validation.
Q76: What is HATEOAS concept?
Including navigational links in representations to guide clients.
Q77: Should every API use HATEOAS?
Not always; depends on domain/client needs.
Q78: What is ETag?
Response validator for caching/conditional requests.
Q79: What is If-None-Match flow?
Client sends ETag; server returns 304 if unchanged.
Q80: What is Last-Modified caching?
Timestamp-based conditional request support.
Q81: What is 304 Not Modified?
Response indicating cached client resource is still valid.
Q82: What is idempotency in HTTP methods?
Repeated identical request yields same intended effect (e.g., PUT/DELETE semantics).
Q83: Is POST idempotent by default?
No.
Q84: How can POST be made safer with retries?
Use idempotency keys and dedup logic.
Q85: What is form binding vulnerability risk?
Mass assignment/binding to unintended fields.
Q86: How reduce mass assignment risk?
Use DTOs and explicit allowed fields.
Q87: Why use DTOs in controllers?
Decouple API contracts from domain entities and control exposure.
Q88: Entity vs DTO in web layer?
Entities are persistence models; DTOs are transport contracts.
Q89: What is validation group use case?
Different constraints for create vs update operations.
Q90: What is custom validator?
User-defined validation logic beyond built-in constraints.
Q91: What is MethodArgumentNotValidException?
Raised when @Valid request body binding fails.
Q92: How return field-level validation errors?
Extract errors from BindingResult/exception and map to structured response.
Q93: What is type mismatch exception in MVC?
Occurs when request value cannot convert to expected type.
Q94: How handle conversion failures gracefully?
Global exception handling with clear client error messages.
Q95: What is multipart request handling?
Handling file uploads/form-data in controllers.
Q96: What is MultipartFile?
Spring abstraction representing uploaded file.
Q97: File upload security basics?
Size limits, content-type checks, virus scanning, storage isolation.
Q98: What is async request processing in MVC?
Free servlet thread while background processing continues.
Q99: Common async return types in MVC?
Callable, DeferredResult, WebAsyncTask.
Q100: Why use async MVC?
Improve scalability for long-running I/O operations in servlet stack.
Q101: What is timeout handling in async MVC?
Define timeout + fallback/error response behavior.
Q102: What is SSE (Server-Sent Events) in MVC context?
Streaming server updates over HTTP to clients.
Q103: What is HttpEntity/RequestEntity usage?
Access request headers/body as typed entity wrappers.
Q104: What is ResponseBodyAdvice?
Hook to customize/transform response bodies globally.
Q105: What is RequestBodyAdvice?
Hook to inspect/modify request body before controller method consumes it.
Q106: What is custom HandlerMethodArgumentResolver?
Extension to resolve custom parameter types in controller methods.
Q107: Example argument resolver use?
Inject current authenticated domain user object.
Q108: What is WebDataBinder role?
Binds web request params to Java objects with conversion/validation.
Q109: What is path matching strategy concern?
Ant-style vs PathPattern parser differences affect route behavior/performance.
Q110: Why avoid ambiguous mappings?
Ambiguity causes startup failures or unpredictable routing.
Q111: What is API versioning strategy?
URI/header/media-type versioning approaches for evolving APIs.
Q112: Why version APIs?
Preserve backward compatibility for existing clients.
Q113: What is deprecation policy in web APIs?
Communicate sunset timelines and migration guidance.
Q114: What is locale change interceptor?
Interceptor switching locale based on request parameter/header.
Q115: What is theme resolver (classic MVC)?
Resolves UI theme resources for server-rendered apps.
Q116: What is view technology integration?
Thymeleaf/JSP/Freemarker template rendering in MVC.
Q117: What is redirect vs forward tradeoff?
Redirect changes URL/new request; forward stays internal same request.
Q118: What is session attribute usage in MVC?
Store conversational state across requests (use sparingly).
Q119: Why avoid excessive session state?
Scalability, memory, and stateless API concerns.
Q120: What is intermediate anti-pattern in MVC?
Fat controllers handling validation, business rules, and persistence together.
Q121: What is intermediate best practice?
Thin controllers + service orchestration + unified error contract.
Q122: Why document API contracts?
Improves client integration and reduces support cost.
Q123: What is OpenAPI integration purpose?
Machine-readable API spec for docs/client generation/testing.
Q124: What is contract-first vs code-first?
Design API spec first vs derive spec from implemented code.
Q125: Intermediate maturity signal?
Consistent status codes, validation errors, and observable request flow.
Advanced
Q126: What is content negotiation pitfall at scale?
Unexpected converter selection causing incompatible payload formats.
Q127: How control converter behavior?
Order/customize HttpMessageConverters and media type support explicitly.
Q128: What is large payload streaming strategy?
Use streaming responses/resources to avoid loading full payload in memory.
Q129: What is zero-copy file response concept?
Efficient file transfer using server/container optimizations where possible.
Q130: What is backpressure challenge in servlet MVC?
Blocking model lacks native reactive backpressure; must control concurrency/timeouts.
Q131: How protect MVC apps from slow clients?
Write timeouts, response buffering strategy, connection limits.
Q132: What is thread pool saturation in MVC?
All request threads busy, causing queueing/timeouts.
Q133: How mitigate thread pool saturation?
Optimize handlers, offload slow I/O, tune pools/timeouts, apply bulkheads.
Q134: What is bulkhead pattern in web tier?
Isolate critical endpoints/resources from noisy neighbors.
Q135: What is rate limiting at MVC boundary?
Limit request frequency per client/key to protect service availability.
Q136: Where implement rate limits?
Gateway, filter/interceptor, or dedicated infrastructure layer.
Q137: What is idempotency-key storage concern?
Need fast consistent dedup store with TTL and conflict handling.
Q138: What is optimistic concurrency in REST?
Use version/ETag with conditional updates (If-Match).
Q139: What is 412 Precondition Failed use case?
Conditional request failed due to version/ETag mismatch.
Q140: What is API gateway vs MVC responsibility split?
Gateway handles cross-cutting edge concerns; MVC handles domain endpoint logic.
Q141: What is BFF pattern relation to Spring MVC?
Backend-for-Frontend tailored endpoints for specific client experiences.
Q142: What is anti-corruption layer at controller boundary?
Translate external payload semantics to internal domain model safely.
Q143: Why avoid exposing domain entities directly in responses?
Prevents tight coupling, data leaks, and evolution constraints.
Q144: What is security hardening for MVC endpoints?
Input validation, authz checks, CSRF/CORS policy, headers, output encoding.
Q145: What is method security vs URL security?
Method security protects service methods; URL security protects request routes.
Q146: Why use both method and URL security?
Defense in depth and clearer enforcement boundaries.
Q147: What is SSRF concern in web handlers?
User-controlled URLs triggering unsafe server-side outbound requests.
Q148: How mitigate SSRF in MVC apps?
Allowlists, DNS/IP validation, network egress controls.
Q149: What is request smuggling concern (edge-related)?
Malformed HTTP parsing discrepancies across proxies/servers.
Q150: Who should primarily handle smuggling defenses?
Edge proxies/load balancers + strict server config.
Q151: What is observability baseline for MVC services?
Structured logs, request metrics, traces, and correlation IDs.
Q152: Which metrics matter most for MVC endpoints?
RPS, latency percentiles, error rates, saturation, payload sizes.
Q153: Why monitor p99 latency?
Tail latency captures worst user impact and hidden bottlenecks.
Q154: What is cardinality pitfall in endpoint metrics?
Unbounded labels (e.g., raw user IDs) exploding metrics storage.
Q155: How avoid high-cardinality labels?
Use bounded dimensions like route template and status class.
Q156: What is graceful degradation in MVC?
Fallback responses/partial data when downstream dependencies fail.
Q157: What is circuit breaker role for controllers?
Prevent repeated slow/failing downstream calls from exhausting resources.
Q158: What is timeout budget strategy?
Define per-hop timeouts so end-to-end SLA is protected.
Q159: Why should controller timeouts be explicit?
Avoid hanging threads and unpredictable client experience.
Q160: What is schema evolution strategy for APIs?
Additive changes first; deprecate/remove fields with clear versioning policy.
Q161: What is compatibility test for APIs?
Automated tests ensuring old clients still work after changes.
Q162: What is consumer-driven contract testing?
Consumers define expectations verified against provider builds.
Q163: What is canary release for MVC changes?
Roll out endpoint changes to small traffic subset before full release.
Q164: What is shadow traffic testing?
Replay production-like traffic to new version without impacting users.
Q165: What is advanced exception mapping principle?
Map technical failures to stable client-facing error categories.
Q166: What is incident triage workflow for MVC outages?
Correlate logs, traces, metrics, deploy diffs, and dependency health.
Q167: Biggest advanced MVC anti-pattern?
Treating controllers as orchestration engines with hidden domain logic.
Q168: What is maintainable controller size heuristic?
Small cohesive endpoints with delegated business operations.
Q169: What is long-term API governance requirement?
Versioning, deprecation policy, review standards, and observability gates.
Q170: What is documentation maturity for MVC APIs?
Always-current OpenAPI, examples, error catalog, and auth guidance.
Q171: What is zero-downtime API deployment requirement?
Backward-compatible contracts during rolling/blue-green updates.
Q172: How to prevent breaking clients accidentally?
Schema diff checks, contract tests, staged rollout, telemetry-based verification.
Q173: What is final performance rule for MVC?
Optimize end-to-end path: serialization, DB calls, downstream I/O, and thread usage.
Q174: What is final architecture rule for MVC?
Keep web layer focused on transport concerns; isolate domain logic in services.
Q175: Final maturity principle?
Design APIs for clarity, compatibility, observability, and operational resilience.