0% found this document useful (0 votes)
4 views11 pages

Java EE & Spring Framework

The document provides an overview of Java EE and Spring Framework, detailing key concepts such as Java EE fundamentals, JSON data binding, server configuration, CORS, Spring Core concepts, and Spring MVC. It covers various topics including the purpose of filters, types of containers, dependency injection, and the role of DispatcherServlet. Additionally, it discusses build tools like Maven and Gradle, Spring Data JPA, authentication methods, and best practices for using JWT securely.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Java EE & Spring Framework

The document provides an overview of Java EE and Spring Framework, detailing key concepts such as Java EE fundamentals, JSON data binding, server configuration, CORS, Spring Core concepts, and Spring MVC. It covers various topics including the purpose of filters, types of containers, dependency injection, and the role of DispatcherServlet. Additionally, it discusses build tools like Maven and Gradle, Spring Data JPA, authentication methods, and best practices for using JWT securely.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Java EE & Spring Framework

Phase 1: Java EE Fundamentals 4. Purpose and usage of Filters in Java EE (2


marks)
1. Why is Java EE recommended for
enterprise-level application development? Filters are used to pre-process requests and
(3 marks) post-process responses. Common uses
include:
Java EE is recommended because: - Authentication/authorization checks
- It provides a standardized, modular platform - Logging and auditing
for developing large-scale, distributed - Data compression
applications - Input validation
- Offers built-in support for transaction - CORS handling
management, security, and concurrency
- Includes APIs for common enterprise needs Phase 2: JSON and Data Binding
(JPA for persistence, JMS for messaging, etc.)
- Supports scalability and high availability 5. What does JSON stand for? (1 mark)
through clustering and load balancing JavaScript Object Notation
- Has a large ecosystem and community
support 6. Two benefits of using JSON for data
exchange (2 marks)
2. Types of containers in Java EE and their
roles (3 marks) 1. Lightweight and human-readable format
2. Language-independent (can be parsed by
- Web Container: Manages servlets, JSPs, and most programming languages)
web components (e.g., Tomcat)
- EJB Container: Manages Enterprise JavaBeans 7.1 Define a MIME type (2.5 marks)
(EJBs) for business logic
- Application Client Container: Manages MIME (Multipurpose Internet Mail Extensions)
standalone client applications type is a standard that indicates the nature
- Applet Container: Manages applets (now and format of a document/file. For JSON, the
largely deprecated) MIME type is `application/json`.
MIME types are important in APIs to ensure
3. Define a Servlet in Java EE (2 marks) proper content negotiation between client
and server. The Content-Type header (e.g.,
A Servlet is a Java class that extends server application/json) tells the receiver how to
capabilities to handle HTTP requests and interpret the data.
generate dynamic responses. Servlets run
inside a web container and follow a lifecycle 7.2 Suitable JSON implementation for Java
managed by the container. API (2.5 marks)
Jackson library is most suitable because:
- High performance
- Comprehensive feature set
- Good Spring integration
- Active maintenance
example:
Phase 3: Server Configuration and JDBC Simple request: GET request to fetch data with
standard headers
8.1 Configuration file that manages servlet Preflight: OPTIONS request sent before
settings in Tomcat (2 marks) DELETE/PUT to check permissions

`web.xml` (Deployment Descriptor) in the 14. Safe HTTP methods (3.5 marks)
WEB-INF directory
Safe methods don't modify resources: GET,
9. Java utility to manage DB connections (2 HEAD, OPTIONS
marks)
15. Idempotent methods (3.5 marks)
Apache Commons DBCP (Database Connection
Pool) or HikariCP Idempotent methods produce same result if
called once or multiple times: GET, PUT,
10. Comparison with JDBC (2 marks) DELETE, HEAD, OPTIONS

- JDBC: Requires manual connection Phase 5: CORS and Cross-Domain


management, more boilerplate code Communication
- Connection Pool: Manages connections
efficiently, improves performance, reduces 16. Define CORS and Shan's issue (4 marks)
overhead
CORS (Cross-Origin Resource Sharing) is a
Phase 4: HTTP and RESTful Concepts mechanism that allows restricted resources to
be requested from another domain. Shan
11. Technology to store form data and likely encountered a browser blocking
populate frontend tables (1 mark) requests from his frontend to a backend on a
LocalStorage or SessionStorage in JavaScript different domain due to same-origin policy.

12. HTTP methods mapped to CRUD (4 17. How CORS acts as security mechanism
marks) (3 marks)
- GET → Read
- POST → Create CORS protects users by:
- PUT → Update (full resource) - Restricting cross-origin requests by default
- PATCH → Update (partial resource) - Requiring server consent via headers
- DELETE → Delete - Preventing malicious sites from making
unauthorized requests to other domains
13. Simple request vs Preflight request (3
marks) 18. Step-by-step solution for CORS errors (8
marks)
- Simple request: Direct request using GET,
POST or HEAD with allowed headers 1. Configure server to include CORS headers
- Preflight request: OPTIONS request sent (`Access-Control-Allow-Origin`)
before actual request for CORS, checks if 2. For Spring, use `@CrossOrigin` annotation
server allows the actual requestA real-world on controllers
3. Or create a global CORS configuration with
`WebMvcConfigurer`
4. For complex requests, ensure proper 23. Define Dependency Injection (2 marks)
handling of OPTIONS (preflight)
5. Set allowed methods, headers, and DI is a design pattern where objects receive
credentials if needed their dependencies from an external source
6. Test with different browsers rather than creating them directly, promoting
7. Consider security implications of permissive loose coupling.
CORS settings
8. For production, specify exact origins rather 24. Methods for DI in Spring (3 marks)
than "*"
1. Constructor injection (recommended)
Phase 6: Spring Core Concepts 2. Setter injection
3. Field injection (using `@Autowired`)
19. Why choose Spring Framework? (2
marks) 25. Explain Inversion of Control (2 marks)

- Lightweight dependency injection IoC is a principle where the control of object


- Comprehensive programming/configuration creation and lifecycle is transferred to the
model framework (container) rather than being
- Excellent integration with other technologies managed by the objects themselves.
- Strong community and documentation
26. Types of ApplicationContexts (5 marks)
20. Define a Bean in Spring (3 marks)
1. `ClassPathXmlApplicationContext`: Loads
A bean is an object that is instantiated, from XML in classpath
assembled, and managed by the Spring IoC 2. `FileSystemXmlApplicationContext`: Loads
container. Beans are defined in configuration from XML in file system
metadata and created based on that 3. `AnnotationConfigApplicationContext`: Uses
definition. Java configuration classes
4. `WebApplicationContext`: For web
21. Ways to declare Spring Bean (3 marks) applications
5. `AnnotationConfigWebApplicationContext`:
1. XML configuration (`<bean>` tag) Web version of annotation config
2. Java configuration (`@Bean` in
`@Configuration` class) 27. Full mode vs Light mode (2 marks)
3. Component scanning (`@Component` and
derivatives) - Full mode: All beans are eagerly initialized at
startup
22. Describe annotations (3 marks) - Lite mode: Beans are initialized when needed
(lazy initialization)
- @Component: Marks a class as Spring
component for auto-detection 28. Concept of AOP (2 marks)
- @Configuration: Indicates a class contains
Spring bean definitions Aspect-Oriented Programming allows
- `@ComponentScan`: Configures component cross-cutting concerns (logging, security,
scanning directives transactions) to be modularized separately
from business logic and applied declaratively.
29. Bean Ambiguity and resolution (3 Example:
@GetMapping("/api/v1/customer*")
marks)

- `/api/v1/customer` (exact):
Bean ambiguity occurs when multiple beans of
Matches only the exact path
the same type exist. Solutions:
`/api/v1/customer`.
1. `@Primary` to mark preferred bean
2. `@Qualifier` to specify bean name
Example:
3. Use specific bean names in injection points
@GetMapping("/api/v1/customer")

Phase 7: Spring MVC and Web Development - `/api/v1/customer/{value}` (segment variable):


Captures dynamic path segments (e.g.,
30. Advantages of Spring in controller layer `/api/v1/customer/123` maps `{value}` to `123`).
(3 marks)
Example:
- Simplified request mapping with annotations @GetMapping("/api/v1/customer/{id}")
- Built-in support for content negotiation public String getCustomer(@PathVariable("id") String id)
- Easy integration with view technologies { ... }

- Powerful validation mechanisms


- Exception handling framework
34. Explain the purpose of: (3 marks)
- `@RestController`:
31. Role of DispatcherServlet (3 marks)
Combines `@Controller` + `@ResponseBody`.
Used in Spring MVC to create RESTful
DispatcherServlet is the front controller that:
controllers that return JSON/XML instead of
1. Receives all HTTP requests
views.
2. Delegates to controllers based on URL
mappings
- `@RequestMapping`:
3. Manages view resolution
Maps HTTP requests to handler methods.
4. Handles exceptions
Can specify path, method (GET/POST),
5. Returns the final response
produces/consumes content types.

32. URL analysis (6 marks)


- `@Service`:
Marks a class as a business service layer
- `http://www.example.com`: Root of
component (Spring stereotype). Enables
example.com with www subdomain
auto-detection during scanning.
- `http://example.com`: Root without
subdomain (may be same or different)
35. Interpret the method and annotations:
- `http://exams.example.com`: Different
(4 marks)
subdomain (may be treated as cross-origin)
@PatchMapping(value = "/{id}", consumes =
"application/json", produces =
33. Identify appropriate mappings for
"application/json")
these: (3 marks)
private void
updateStudent(@PathVariable("id") String id,
- `/api/v1/customer*` (wildcard):
@RequestBody StudentDTO student) {
Matches any path starting with
dataProcess.updateStudent(id, student);
`/api/v1/customer`
}
(e.g., `/api/v1/customer123`).
- `@PatchMapping`: Handles HTTP PATCH Phase 8: Build Tools
requests to `/somepath/{id}`.
37. Briefly describe `pom.xml` and
- `consumes="application/json"`: Expects `build.gradle`: (3 marks)
JSON input in the request body.
- `pom.xml`:
- `produces="application/json"`: Returns JSON - Used by Maven.
response. - XML-based configuration for dependencies,
plugins, and build lifecycle.
- `@PathVariable`: Extracts `{id}` from the URL. - Structured with `<dependencies>`, `<build>`,
and `<properties>`.
- `@RequestBody`: Binds the JSON payload to
`StudentDTO`. - `build.gradle`:
- Used by Gradle.
- Behavior: Updates a student with the given - Groovy/Kotlin DSL (more concise than XML).
ID using data from the request body. - Uses `dependencies {}`, `plugins {}`, and
task-based configuration.

38. Compare Maven/Gradle with Ant: (5


marks)

Feature Maven/Gradle Ant

Configuration Declarative Procedural (build.xml)


(pom.xml/build.gradle)

Dependency Mgmt Built-in (Maven Central) Manual (no built-in support)

Performance Gradle is faster Slower (re-executes all tasks)


(incremental builds)

Flexibility Convention over Highly flexible (but verbose)


configuration

Learning Curve Easier for standard Steeper (requires scripting)


projects

Phase 9: Spring Data JPA


2. Does Java offer a complete solution? (4
39. Sachini is building a Spring API with a marks)
relational database.
1. Suggest a built-in Java solution: (1 mark) - Yes, but with limitations:
- JPA provides ORM standard, but needs an
JPA (Java Persistence API) with Hibernate as the implementation (e.g., Hibernate).
implementation.
- Requires additional configuration
(datasource, transactions).
- For complex queries, native SQL or
QueryDSL may be needed.

3. Placeholders in `JpaRepository<?, ?>`: (2


marks)

public interface MyRepository extends


JpaRepository<EntityClass, IdType>

Example:
public interface CustomerRepository extends
JpaRepository<Customer, Long>

40. Define the following: (8 marks)

Term Definition

BasicDataSource Apache Commons DBCP connection pool


implementation (manages DB
connections).

DriverManagerDataSource Simple Spring JDBC datasource (no


pooling, for testing/simple apps).

@Repository Spring stereotype for DAO classes.


Enables exception translation to Spring’s
DataAccessException.

@Transactional Defines transactional boundaries


(methods execute within a database
transaction).

Phase 10: Spring Boot and Testing 2. Notable annotation: (4 marks)

41. Waruna is building a Java API using `@SpringBootApplication`: Combines:


Spring. - `@Configuration` (defines beans),
- `@EnableAutoConfiguration` (auto-configures
1. Recommend the optimal Spring project: Spring),
(1 mark) - `@ComponentScan` (auto-discovers
components).
Spring Boot (simplifies setup with
auto-configuration, embedded servers).
3. Suitable testing method: (1 mark) 46. Claims in a JWT token: (3 marks)

JUnit 5 + `@SpringBootTest` for integration - Registered claims:


tests. Standard fields (`iss`, `exp`, `sub`).

4. Test without affecting real data: (2 - Public claims:


marks) Custom claims (e.g., `roles`).

- Use `@Transactional` (rolls back after test). - Private claims:


- **Testcontainers** (Dockerized DBs). Agreed between parties.
- **H2 in-memory database** for tests.
47. HTTP header for JWT: (2 marks)
Phase 11: Authentication and Authorization
Authorization: Bearer <token>

42.1. Technical term for login requirement:


(2.5 marks)

Authentication (verifying user identity).

42.2. Kamal’s restricted access vs manager:


(2.5 marks)

Role-Based Access Control (RBAC):


Permissions granted based on roles (e.g.,
`USER` vs `ADMIN`).

Phase 12: JWT and Security

43. What is a JWT token? (2 marks)

A JSON Web Token is a compact, URL-safe


token format for securely transmitting claims
(e.g., user identity) between parties.

44. Main parts of a JWT: (3 marks)

1. Header (algorithm + token type).


2. Payload (claims like `sub`, `exp`).
3. Signature (verifies token integrity).

45. One alternative to JWT: (2 marks)

Opaque tokens (random strings validated via


backend lookup).
48. Definitions: (8 marks)

Term Definition

@PreAuthorize Checks permissions before method


execution (e.g.,
@PreAuthorize("hasRole('ADMIN')")).

@PostAuthorize Checks permissions after method


execution (e.g., for return value validation).

SecurityContextHolder Stores the current security context


(authentication + user details).

UserDetailsService Loads user data during authentication


(loadUserByUsername()).

50. Recommend a secure password storage


49. List best practices for using JWT method (2 marks)
securely (3 marks)
Use bcrypt with:
1.Set short expiration times (use refresh
tokens for long sessions) 1.A work factor of 10-12 (balance between
security and performance)
2.Always use HTTPS to prevent token 2.Automatic salt generation
interception 3.Spring Security's BCryptPasswordEncoder

3.Store tokens securely - avoid localStorage Why bcrypt?


(use HttpOnly cookies for web apps) Specifically designed for password hashing
Slow by design (thwarts brute force)
4.Validate tokens properly - check signature, Handles salting automatically
issuer, audience, and expiration Adaptive to increasing compute power (work
factor)

5.Use strong signing keys (HS256 with long Example:


secrets or RS256)
@Bean
6.Implement token blacklisting for logout public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
functionality
}

7.Avoid sensitive data in payload as JWTs are


not encrypted by default
1. Explain the difference between 5. Explain the role of `DispatcherServlet` in
`@Controller` and `@RestController` in Spring MVC with a diagram. (4 marks)
Spring. (2 marks)
Role: Front controller that routes requests to
- `@Controller`: Used for traditional MVC apps appropriate handlers (controllers).
where methods return view names (resolved Flow:
to HTML/JSP). 1. Client → `DispatcherServlet` → Handler
- `@RestController`: Combines `@Controller` + Mapping
`@ResponseBody`; methods return data 2. `DispatcherServlet` → Controller → Service
(JSON/XML) directly, used for REST APIs. → DAO
3. Controller → `DispatcherServlet` →
ViewResolver → Client
2. What is the purpose of
`@SpringBootTest`? Provide an example. (3 6. What is Bean Scoping in Spring? List
marks) common scopes. (3 marks)

- Purpose: Used for integration testing in Defines the lifecycle and visibility of a bean.
Spring Boot. Loads the full application context. Scopes:
- Example: - `singleton` (default: one instance per
@SpringBootTest container)
class CustomerControllerTest { - `prototype` (new instance each time)
@Autowired
- `request` (per HTTP request)
private MockMvc mockMvc;
- `session` (per user session)
@Test
void testGetCustomer() throws Exception { 7. How would you handle exceptions
mockMvc.perform(get("/api/customer/1")) globally in Spring Boot? (3 marks)
.andExpect(status().isOk());
}
} Use `@ControllerAdvice`+`@ExceptionHandler`:

@ControllerAdvice
3. How does Spring Security handle
public class GlobalExceptionHandler {
authentication? (3 marks)
@ExceptionHandler(ResourceNotFoundException.class)
1. User submits credentials (e.g., login public ResponseEntity<String>
form/JWT). handleNotFound(ResourceNotFoundException ex) {
return
2. `AuthenticationManager` validates
ResponseEntity.status(404).body(ex.getMessage());
credentials using `UserDetailsService`. }
3. On success, a `SecurityContext` is created }
with the user’s `Authentication` object.

4. What is the difference between `PUT` and


`PATCH` in REST? (2 marks)

- PUT: Replaces the entire resource with the


new representation.
- PATCH: Partially updates specific fields of the
resource.
8. What is the difference between 11. Draw the architecture of a typical
`@Component`, `@Service`, and Spring Boot REST API with layers. (4 marks)
`@Repository`? (3 marks)
Client → Controller (REST Endpoints) → Service
All are stereotypes for auto-detection, but (Business Logic) → Repository (DB Access) →
semantically: Database
↑ ↑
- `@Component`: Generic Spring-managed DTOs (Data Transfer Objects) Entities
bean. (JPA)
- `@Service`: Business logic layer.
- `@Repository`: Persistence layer (adds 12. What is @ControllerAdvice in Spring? (2
exception translation). marks)

9. Explain the purpose of A global exception handler for multiple


`application.properties` in Spring Boot with controllers. Combines @ExceptionHandler
2 examples. (3 marks) methods to centralize error handling.

The application.properties file in Spring Example:


Boot is used to configure application java
@ControllerAdvice
settings such as database connections, server
public class GlobalExceptionHandler {
behavior, logging, and more. It allows
developers to externalize configuration @ExceptionHandler(ResourceNotFoundException.class)
without hardcoding values in Java code. public ResponseEntity<?> handleResourceNotFound() {
Centralized configuration file. return ResponseEntity.notFound().build();
}
Examples:
}

# Database config
13. Explain the purpose of the
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa @Transactional annotation in Spring (3
marks)
# Server port
server.port=8081
@Transactional:
●​Declares that a method or class should be
10. What is the difference between
executed within a database transaction
`@Mock` and `@MockBean`? (2 marks)
●​Provides ACID properties (Atomicity,
Consistency, Isolation, Durability)
- `@Mock`: Creates a mock using Mockito
●​Can be configured with:
(plain unit tests).
Propagation behavior (e.g., REQUIRED,
- `@MockBean`: Adds/replaces a Spring
REQUIRES_NEW)
context bean with a mock (used in
Isolation level
`@SpringBootTest`).
Timeout
Read-only mode
Rollback rules
14. What is the purpose of the
DispatcherServlet in Spring MVC? (3 marks)

The DispatcherServlet is:


●​ The front controller in Spring MVC
architecture
●​ Responsible for request processing
workflow:
Receives all incoming HTTP requests
Delegates to controllers via handler mapping
Manages view resolution
Handles exceptions
Returns the final response
●​ Configurable through Java config or XML
●​ Can have multiple instances in one
application

15. What is the difference between


@RequestParam and @PathVariable? (3
marks)

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id,
@RequestParam(required = false) String details) {
// ...
}

16.what is the @Repository annotation

In Spring Boot, we use the @Repository


annotation to mark a class or interface as part of
the persistence layer. This makes it easy for
Spring to detect and manage it as a bean.

●​ Tells Spring this class is for data access.


●​ Enables automatic database exception
handling.
●​ Works with JpaRepository or custom DAO
classes.

@Repository
public interface StudentRepository extends
JpaRepository<Student, Long> {
List<Student> findByName(String name);
}

You might also like