Skip to content
IT-505 · Advanced Java Lab/Quick Revision Short Notes

Advanced Java Lab (IT-505) - Unit 5 Short Notes

1.0 Web Application Development Fundamentals (Servlet & JSP)

1.1 Servlet Lifecycle & API Deep Dive

  • Lifecycle Methods:

    • init(): Called once by the container to initialize the servlet.

    • service(): Called for each client request; dispatches to doGet(), doPost(), etc.

    • destroy(): Called once before removing the servlet from service.

  • Core Interfaces/Classes:

    • HttpServlet: Base class for HTTP servlets; overrides doGet(HttpServletRequest req, HttpServletResponse resp).

    • HttpServletRequest: Provides client request data (parameters, headers, session).

    • HttpServletResponse: Used to send response (status, headers, content via PrintWriter/ServletOutputStream).

  • ServletConfig vs ServletContext:

    | Feature | ServletConfig | ServletContext | | :--- | :--- | :--- | | Scope | Single servlet | Entire web application | | Purpose | Servlet-specific init parameters | Application-wide attributes & resources | | Access | getServletConfig() | getServletContext() |

[!TIP] Exam Focus: Be prepared to write code snippets for doGet()/doPost() and explain the difference between forward() (server-side) and sendRedirect() (client-side, new request).

1.2 Session Management Techniques

HTTP is stateless. Techniques to maintain state:

Technique Mechanism Pros Cons
HTTP Session request.getSession() creates HttpSession object stored on server. Secure, no data in URL. Consumes server memory.
URL Rewriting response.encodeURL(url) appends ;jsessionid=.... Works when cookies disabled. Ugly URLs, security risk if leaked.
Hidden Form Fields <input type="hidden" name="sessionId" value="...">. Simple. Only works for POST forms, visible in HTML.
Cookies Cookie cookie = new Cookie(name, value); response.addCookie(cookie); Persistent, configurable path/domain. Client can disable/delete, size limit (~4KB).

[!CAUTION] Common Pitfall: Forgetting to set cookie path/domain correctly can make cookies inaccessible across pages.

1.3 JavaServer Pages (JSP) Technology

  • Lifecycle: JSP → Servlet (translation) → Compilation → Execution.

  • Scripting Elements (Avoid in modern JSP, use JSTL/EL):

    • Scriptlet: <% java code %> (discouraged).

    • Expression: <%= expression %> (prints value).

    • Declaration: <%! declaration %> (class-level members).

  • Implicit Objects: request, response, session, application (ServletContext), out (JspWriter), config (ServletConfig), pageContext.

  • Directives:

    • <%@ page ... %>: Page-level (imports, errorPage, contentType).

    • <%@ include file="..." %>: Static include (at translation time).

  • JSTL Core Tags (c: prefix):

    • <c:out value="${...}"/>: Escape/print.

    • <c:if test="${...}">: Conditional.

    • <c:forEach var="x" items="${list}">: Loop.

    • <c:forTokens items="${str}" delims=",">: Tokenize string.

1.4 Expression Language (EL) & Custom Tags

  • EL Syntax: ${expression}. Accesses scoped attributes (pageScope, requestScope, sessionScope, applicationScope). Implicit objects: param, header, initParam.

  • Custom Tags:

    • Classic Tag Handlers: Implement Tag/IterationTag interfaces (more control, complex).

    • Simple Tag Handlers: Implement SimpleTag interface (easier, preferred). Lifecycle: doTag().

    • Tag Files: .tag files (like JSP fragments) for reusable view logic without Java code.


2.0 Model-View-Controller (MVC) Architecture Implementation

2.1 Designing MVC Pattern with Servlets/JSP

Component Role Technology
Model Business logic & data JavaBean/POJO, DAO classes
View Presentation JSP (with JSTL/EL)
Controller Request handling, flow control HttpServlet
  • Data Flow:

    1. Client → Servlet (Controller).

    2. Servlet invokes Model (Bean/DAO) for data.

    3. Servlet stores result in request/session scope.

    4. Servlet forwards to JSP (View) using RequestDispatcher.forward().

    5. JSP renders response using scoped data.

  • forward() vs sendRedirect():

    | forward() | sendRedirect() | | :--- | :--- | | Server-side transfer. | Client-side (new request). | | Same request/response objects. | New request/response objects. | | URL unchanged in browser. | URL changes in browser. | | Faster, keeps request attributes. | Slower, loses request attributes. |

2.2 Practical MVC Lab Exercises

  • CRUD Application Flow:

    1. StudentServlet (Controller) handles paths (/add, /edit, /delete, /list).

    2. StudentDAO (Model) performs JDBC/Hibernate operations.

    3. list.jsp (View) displays data using <c:forEach>.

  • Validation:

    • Client-side: JavaScript (quick feedback).

    • Server-side: In servlet/DAO (authoritative).

  • Pagination: DAO method getStudents(int page, int size) using LIMIT (MySQL) or ROW_NUMBER().


3.0 Database Connectivity & Persistence (JDBC & Hibernate)

3.1 Advanced JDBC

  • Connection Pooling: Configure DataSource in Tomcat's context.xml or use Apache DBCP/HikariCP in web app. Avoids overhead of creating new connections per request.

  • Batch Updates: PreparedStatement.addBatch(), executeBatch() for bulk inserts/updates. Improves performance.

  • Transaction Management:

    
    conn.setAutoCommit(false);
    
    // ... execute multiple statements ...
    
    conn.commit(); // or conn.rollback() on error
    
    
  • RowSet: Disconnected ResultSet. CachedRowSet can be serialized and used outside connection scope.

  • ResultSetMetaData: Get column count/type dynamically.

3.2 Hibernate ORM Framework (Core)

  • Architecture: SessionFactory (immutable, per DB) → Session (persistence context, per transaction) → Entity objects.

  • Configuration: hibernate.cfg.xml (DB connection, dialect, mapping resources) or Java config.

  • Mapping Annotations:

    
    @Entity @Table(name="students")
    
    public class Student {
    
        @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    
        private int id;
    
        private String name;
    
        // getters/setters
    
    }
    
    
  • Associations:

    | Relationship | Annotation (Owning Side) | mappedBy? | | :--- | :--- | :--- | | One-to-One | @OneToOne | Yes (on inverse side) | | One-to-Many | @OneToMany | Yes (on @ManyToOne side) | | Many-to-Many | @ManyToMany | Yes (on one side) |

  • Inheritance: @Inheritance(strategy=InheritanceType.SINGLE_TABLE/JOINED/TABLE_PER_CLASS).

  • HQL vs Criteria: HQL (Hibernate Query Language) is SQL-like; Criteria API is type-safe, programmatic.

  • Session Management: sessionFactory.getCurrentSession() (bound to transaction) vs openSession().

  • Caching:

    • First-Level (Session): Enabled by default. Objects in same session are cached.

    • Second-Level (SessionFactory): Shared across sessions. Configure with EhCache/Infinispan.

  • Optimistic Locking: @Version field (int/timestamp) ensures concurrent updates don't overwrite.

3.3 Hibernate Lab Exercises

  • CRUD: session.save(), session.get(), session.update(), session.delete().

  • Fetching Strategies:

    • FetchType.EAGER: Load immediately (can cause N+1).

    • FetchType.LAZY: Load on demand (default for @OneToMany, @ManyToMany).

    • Override in HQL: FROM Student s JOIN FETCH s.courses.

  • Integration with MVC:

    1. Servlet calls StudentService.

    2. StudentService uses StudentDAO (Hibernate).

    3. DAO methods use Session/Transaction.

    4. Results sent to JSP.


4.0 Spring Framework (Core & MVC)

4.1 Spring Core Container & DI/IoC

  • BeanFactory vs ApplicationContext:

    | BeanFactory | ApplicationContext | | :--- | :--- | | Lazy initialization. | Eager initialization (by default). | | Basic container. | Advanced (i18n, events, AOP). |

  • Dependency Injection:

    • Constructor Injection: Dependencies as constructor parameters (recommended for mandatory deps, immutability).

    • Setter Injection: Dependencies via setter methods (optional deps).

  • Bean Configuration:

    • XML: <bean id="..." class="...">.

    • Annotations: @Component, @Service, @Repository, @Controller + <context:component-scan>.

    • Java Config: @Configuration class with @Bean methods.

  • Bean Scopes:

    | Scope | Description | | :--- | :--- | | singleton | One instance per Spring container (default). | | prototype | New instance each getBean(). | | request | One per HTTP request (web app). | | session | One per HTTP session (web app). |

  • @Autowired & @Qualifier: Autowire by type; @Qualifier("beanName") disambiguates.

4.2 Spring MVC Framework

  • Front Controller: DispatcherServlet (defined in web.xml or via WebApplicationInitializer). Maps requests to controllers.

  • Annotations:

    
    @Controller
    
    public class StudentController {
    
        @GetMapping("/students")
    
        public String list(Model model) {
    
            model.addAttribute("students", service.getAll());
    
            return "studentList"; // View name (resolved by ViewResolver)
    
        }
    
        @PostMapping("/students")
    
        public String add(@ModelAttribute Student student) {
    
            service.save(student);
    
            return "redirect:/students";
    
        }
    
    }
    
    
  • View Resolvers: InternalResourceViewResolver (prefix/suffix for JSPs), TilesViewResolver.

  • Form Handling: <form:form modelAttribute="student">, <form:input path="name"/>. BindingResult for validation errors.

  • Interceptors vs Filters: Interceptors (Spring MVC, post-handler) vs Filters (Servlet API, pre-handler).

4.3 Spring Integration Labs

  • Layered Architecture: @Controller → @Service (business) → @Repository (DAO).

  • Spring + Hibernate:

    • Configure LocalSessionFactoryBean in XML/Java config.

    • Use @Repository with HibernateTemplate or plain Session.

    • @Transactional on service methods for declarative transaction management.

  • Validation: @Valid on @ModelAttribute, BindingResult in method param.

  • Exception Handling: @ControllerAdvice class with @ExceptionHandler methods for global handling.


5.0 RESTful Web Services with Spring

5.1 REST Principles & Spring Support

  • REST Constraints: Uniform Interface, Statelessness, Cacheable, Layered System, Code-on-Demand (optional).

  • @RestController: Combination of @Controller + @ResponseBody (all methods return JSON/XML, not view).

  • HTTP Method Mappings:

    | Method | Annotation | Purpose | | :--- | :--- | :--- | | GET | @GetMapping | Read resource | | POST | @PostMapping | Create resource | | PUT | @PutMapping | Update full resource | | DELETE | @DeleteMapping | Delete resource | | PATCH | @PatchMapping | Partial update |

5.2 Working with Request/Response Bodies

  • @RequestBody: Deserializes HTTP request body (JSON/XML) to Java object using HttpMessageConverter (Jackson for JSON).

  • @ResponseBody: Serializes return object to response body.

  • ResponseEntity<T>: Full control over HTTP status, headers, body.

    
    @GetMapping("/{id}")
    
    public ResponseEntity<Student> get(@PathVariable int id) {
    
        Student s = service.get(id);
    
        return s != null ? ResponseEntity.ok(s) : ResponseEntity.notFound().build();
    
    }
    
    

5.3 REST Client & Testing

  • RestTemplate (Spring 5): Synchronous client. restTemplate.getForObject(url, Student.class).

  • WebClient (Spring 5+): Reactive, non-blocking client.

  • Testing with MockMvc:

    
    @WebMvcTest(StudentController.class)
    
    class StudentControllerTest {
    
        @Autowired MockMvc mockMvc;
    
        @Test void testGetAll() throws Exception {
    
            mockMvc.perform(get("/students"))
    
                   .andExpect(status().isOk())
    
                   .andExpect(jsonPath("$[0].name").value("John"));
    
        }
    
    }
    
    

5.4 REST Lab Exercises

  • CRUD API: Standard endpoints (GET /api/students, POST /api/students, GET /api/students/{id}, PUT /api/students/{id}, DELETE /api/students/{id}).

  • HATEOAS: Use EntityModel<T> and CollectionModel<T> from spring-hateoas to add _links in JSON response.

  • Error Handling: @ControllerAdvice with @ExceptionHandler returning ResponseEntity with error JSON { "error": "Message", "timestamp": ... }.

  • Securing REST: SecurityFilterChain config: http.csrf().disable().authorizeRequests().antMatchers("/api/**").hasRole("USER").... Stateless: sessionCreationPolicy(SessionCreationPolicy.STATELESS).


6.0 Application Security with Spring Security

6.1 Core Concepts & Configuration

  • Authentication vs Authorization: Who are you? vs What can you do?

  • Java Config (Modern):

    
    @Configuration @EnableWebSecurity
    
    public class SecurityConfig {
    
        @Bean
    
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    
            http
    
                .authorizeHttpRequests(auth -> auth
    
                    .antMatchers("/admin/**").hasRole("ADMIN")
    
                    .anyRequest().authenticated()
    
                )
    
                .formLogin(withDefaults())
    
                .httpBasic(withDefaults());
    
            return http.build();
    
        }
    
        @Bean
    
        public UserDetailsService users() {
    
            UserDetails user = User.withDefaultPasswordEncoder()
    
                                   .username("user").password("pass").roles("USER").build();
    
            return new InMemoryUserDetailsManager(user);
    
        }
    
    }
    
    
  • PasswordEncoder: Always use BCryptPasswordEncoder (never plain text).

6.2 URL-Based & Method-Based Security

  • URL Patterns: antMatchers("/admin/**").hasRole("ADMIN"), mvcMatchers() for Spring MVC path matching.

  • HTTP Basic: http.httpBasic() (for stateless APIs, not UI).

  • Form Login: http.formLogin() (default login page, customizable).

  • CSRF: Enabled by default for form login; disable for stateless REST APIs (http.csrf().disable()).

  • Method Security: Enable with @EnableGlobalMethodSecurity(prePostEnabled = true).

    • @PreAuthorize("hasRole('ADMIN')") on method.

    • @Secured("ROLE_USER").

    • @RolesAllowed("USER").

6.3 Securing REST APIs

  • Stateless: http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).

  • JWT Flow:

    1. POST /login with credentials → server validates, generates signed JWT (using jjwt library).

    2. Client sends Authorization: Bearer <token> in subsequent requests.

    3. OncePerRequestFilter validates token, sets Authentication in SecurityContext.

  • OAuth2 Resource Server: http.oauth2ResourceServer().jwt() for token validation.

6.4 Security Lab Exercises

  • Form-Based Login: Configure SecurityFilterChain, create custom login page (/login?error), role-based URL access.

  • JWT Implementation:

    • JwtUtil class to generate/validate tokens.

    • JwtRequestFilter extends OncePerRequestFilter to extract/validate token.

    • JwtAuthenticationEntryPoint for unauthorized responses.

  • Custom Access Denied: AccessDeniedHandler to return JSON error for REST APIs.


7.0 Build Automation & Dependency Management

7.1 Apache Maven

  • pom.xml Key Elements:

    
    <project>
    
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.example</groupId>
    
        <artifactId>myapp</artifactId>
    
        <version>1.0.0</version>
    
        <packaging>war</packaging>
    
        <dependencies>...</dependencies>
    
        <build><plugins>...</plugins></build>
    
    </project>
    
    
  • Dependency Scope: compile (default), provided (Tomcat servlet-api), runtime, test.

  • Build Lifecycle: validate → compile → test → package → install → deploy.

  • Key Plugins:

    • maven-compiler-plugin: Set Java version.

    • maven-war-plugin: Customize WAR structure.

    • maven-surefire-plugin: Run unit tests.

  • Archetypes: mvn archetype:generate -DgroupId=... -DartifactId=... -DarchetypeArtifactId=maven-archetype-webapp.

7.2 Gradle (Overview & Comparison)

  • build.gradle (Groovy DSL):

    
    plugins { id 'war' }
    
    group = 'com.example'
    
    version = '1.0.0'
    
    repositories { mavenCentral() }
    
    dependencies {
    
        implementation 'org.springframework:spring-webmvc:5.3.0'
    
        providedCompile 'javax.servlet:javax.servlet-api:4.0.1'
    
        testImplementation 'junit:junit:4.13.2'
    
    }
    
    
  • Comparison: Gradle uses Groovy/Kotlin DSL (more expressive), convention-over-configuration, faster builds (incremental). Maven uses XML (more verbose, rigid).

7.3 Lab Integration

  • Convert to Maven: Create pom.xml, move libs to <dependencies>, delete WEB-INF/lib (Maven will manage).

  • Dependency Tree: mvn dependency:tree to visualize transitive dependencies.

  • Build WAR: mvn clean package → target/myapp.war.

  • Deploy: Copy WAR to Tomcat's webapps/ or use Tomcat Maven plugin.


8.0 Logging, Testing & Deployment

8.1 Logging Frameworks

  • SLF4J + Logback: SLF4J is facade; Logback is implementation.

  • logback.xml Configuration:

    
    <configuration>
    
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    
            <encoder><pattern>%d{HH:mm:ss} %-5level %logger{36} - %msg%n</pattern></encoder>
    
        </appender>
    
        <root level="INFO"><appender-ref ref="STDOUT"/></root>
    
        <logger name="com.example" level="DEBUG"/>
    
    </configuration>
    
    
  • Best Practice: Use SLF4J API in code: private static final Logger logger = LoggerFactory.getLogger(MyClass.class);.

8.2 Unit & Integration Testing

  • JUnit 5: @Test, @BeforeEach, @AfterEach, assertions (assertEquals, assertTrue).

  • Spring Testing:

    • @SpringBootTest: Full context (integration test).

    • @ContextConfiguration: Load specific config.

    • @WebMvcTest: Slice test for MVC controllers (loads only MVC beans).

  • Mockito: @Mock, @InjectMocks, when(...).thenReturn(...), verify(mock).method().

  • Testing Layers:

    • Unit: Test service/DAO with Mockito (mock dependencies).

    • Integration: @SpringBootTest with real DB (use @Transactional for rollback).

    • Web: MockMvc for controller endpoints.

8.3 Application Deployment

  • WAR vs JAR:

    | WAR | JAR (Spring Boot) | | :--- | :--- | | Deploy to external Tomcat. | Embedded server (Tomcat/Jetty) inside JAR. | | web.xml may be needed (pre-Servlet 3.0). | No web.xml; Java config. | | WEB-INF/ structure. | Executable: java -jar app.jar. |

  • Tomcat Deployment:

    1. Copy WAR to $CATALINA_HOME/webapps/.

    2. Access via http://localhost:8080/yourapp.

    3. Use Tomcat Manager App (/manager/html) for deploy/undeploy.

  • JNDI DataSource: Define in $CATALINA_BASE/conf/context.xml:

    
    <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
    
              driverClassName="com.mysql.cj.jdbc.Driver"
    
              url="jdbc:mysql://localhost:3306/mydb" maxTotal="20" />
    
    

    Access in app via @Resource(lookup="java:comp/env/jdbc/MyDB").

8.4 Debugging & Profiling

  • Remote Debugging: Start Tomcat in debug mode (catalina.sh jpda start). Configure IDE (IntelliJ/Eclipse) to connect on port 8000.

  • Tomcat Manager: Monitor sessions, memory usage, thread state.

  • Profiling: Use VisualVM, JProfiler to detect memory leaks (unclosed resources, session accumulation) and thread contention.


Final Note: For lab exams, focus on writing complete, compilable code for servlets, Spring controllers, Hibernate DAOs, and REST endpoints. Understand the flow of data from client → controller → service → DAO → database and back. Practice configuring web.xml/dispatcher-servlet.xml (if using XML) or Java config. Always handle exceptions and close resources (try-with-resources for JDBC, session.close() for Hibernate).

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in