IT-505: Advanced Java Lab - UNIT 3 Short Notes
1.0 Java Servlet Technology (Core Web Component)
1.1 Servlet Lifecycle & API Deep Dive
-
Lifecycle Methods:
-
init(ServletConfig config): Called once by container to initialize servlet. Access config viagetServletConfig(). -
service(HttpServletRequest req, HttpServletResponse resp): Called for each request. Container creates new thread per request. Must be thread-safe (avoid instance variables). -
destroy(): Called once before servlet is removed from service.
-
-
GenericServletvsHttpServlet:-
GenericServlet: Protocol-independent. Must overrideservice(). -
HttpServlet: HTTP-specific. OverridedoGet(),doPost(), etc. Most common choice.
-
-
ServletConfigvsServletContext:-
ServletConfig: Servlet-specific. Holds init parameters fromweb.xmlor@WebServlet. One per servlet. -
ServletContext: Application-wide. Shared across all servlets/JSPs in the web app. Holds context params, attributes, and resource paths.
-
Exam Tip:
ServletContextis like a global application object.ServletConfigis like a private config for a single servlet.
1.2 Request Handling & Response Generation
-
HttpServletRequestKey Methods:-
getParameter(String name),getParameterValues(String name)for form data. -
getHeader(String name),getCookies(). -
getSession(): Creates/retrievesHttpSession. -
getRequestDispatcher(String path): ReturnsRequestDispatcherfor server-side forward.
-
-
HttpServletResponseKey Methods:-
sendRedirect(String location): Client-side redirect (new request, URL changes). -
setContentType(String type): e.g.,"text/html". -
addCookie(Cookie cookie).
-
-
Forward vs Redirect:
| Feature |
RequestDispatcher.forward()|response.sendRedirect()| | :--- | :--- | :--- | | Request | Same request object | New request | | URL | Unchanged in browser | Changes in browser | | Scope | Request attributes shared | Request attributes lost | | Performance | Faster (server-side) | Slower (client round-trip) |
Common Pitfall: Use forward for internal navigation (MVC). Use redirect for PRG pattern (Post/Redirect/Get) or external URLs.
1.3 Session Management Techniques
-
HttpSession: Default mechanism. Uses cookie (JSESSIONID) by default.-
session.setAttribute(String name, Object value) -
session.getAttribute(String name) -
session.invalidate()to kill session.
-
-
URL Rewriting: Appends
;jsessionid=...to URL. Used when cookies disabled.String encodedURL = response.encodeURL("page.jsp"); out.println("<a href='" + encodedURL + "'>Link</a>"); -
Hidden Form Fields:
<input type="hidden" name="sessionId" value="...">. Less secure, manual management.
Tip: Session tracking order: Cookies -> URL Rewriting -> Hidden Fields.
1.4 Servlet Filters (Filter Interface)
-
Lifecycle:
init(FilterConfig config)->doFilter(ServletRequest req, ServletResponse res, FilterChain chain)->destroy(). -
doFilter: Must callchain.doFilter(request, response)to pass control to next filter/servlet. -
Common Uses: Authentication, logging, compression, character encoding set.
public void doFilter(...) { // Pre-processing (e.g., set encoding) chain.doFilter(request, response); // Continue chain // Post-processing (e.g., log response time) }
1.5 Servlet 3.0+ Annotations & Programmatic Configuration
-
Annotations (replaces
web.xml):-
@WebServlet("/urlPattern") -
@WebFilter("/*") -
@WebListener
-
-
Programmatic Registration:
public class MyAppInitializer implements WebApplicationInitializer { public void onStartup(ServletContext sc) { ServletRegistration.Dynamic reg = sc.addServlet("myServlet", new MyServlet()); reg.addMapping("/dynamic"); } }
1.6 Exception Handling in Servlets
-
Declarative (
web.xml):<error-page> <error-code>404</error-code> <location>/error404.jsp</location> </error-page> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/error.jsp</location> </error-page> -
Programmatic: Use
try-catchin servlet and forward to error page.
2.0 JavaServer Pages (JSP) & Expression Language
2.1 JSP Lifecycle & Translation Model
-
JSP -> Servlet Translation: Container converts
.jspto_jspService()method in a servlet class (e.g.,index_jsp.java). -
JSP Lifecycle: Translation -> Compilation -> Loading -> Instantiation ->
_jspService()->jspDestroy(). -
Directives:
-
<%@ page ... %>: Page-level (imports, session, contentType). -
<%@ include file="header.jsp" %>: Static include (at translation time). -
<%@ taglib uri="..." prefix="c" %>: Import tag library.
-
2.2 JSP Scripting Elements & Best Practices
| Element | Syntax | Use | Recommendation |
|---|---|---|---|
| Declaration | <%! int x = 0; %> |
Class-level members | Avoid (use beans) |
| Scriptlet | <% int y = 1; %> |
Java code in _jspService() |
STRICTLY AVOID |
| Expression | <%= new java.util.Date() %> |
Output to response | Avoid (use EL/JSTL) |
Critical Rule: Never use scriptlets (
<% %>). Use JSTL and EL for all logic and output. JSP is for view only.
2.3 JSP Implicit Objects
| Object | Type | Scope |
|---|---|---|
request, response, out |
HttpServletRequest, HttpServletResponse, JspWriter |
Page |
session, application |
HttpSession, ServletContext |
Session / Application |
config, pageContext |
ServletConfig, PageContext |
Page |
exception |
Throwable |
Page (only in error pages) |
2.4 Java Standard Tag Library (JSTL)
-
Core (
c:):-
<c:out value="${user.name}" />(escape XML by default). -
<c:set var="total" value="${100}" scope="session" />. -
<c:if test="${not empty user}">...</c:if>. -
<c:forEach var="item" items="${list}">...</c:forEach>. -
<c:choose><c:when test="...">...</c:when><c:otherwise>...</c:otherwise></c:choose>.
-
-
Formatting (
fmt:):<fmt:formatDate value="${now}" pattern="yyyy-MM-dd" />. -
SQL (
sql:): For learning/prototyping only. NEVER use in production. Use JDBC/DAO layer.
2.5 Expression Language (EL)
-
Syntax:
${expression}. Accesses scoped attributes (pageScope,requestScope,sessionScope,applicationScope), parameters (param,paramValues), headers (header,headerValues), cookies (cookie), init parameters (initParam). -
Accessing Collections:
${user.address.city} // Bean property ${map['key']} // Map ${list[0]} // List/Array -
Operators:
.,[],?(safe navigation), arithmetic (+,-,*,/,%), relational (==,!=,<,>), logical (&&,||,!), empty (empty list).
2.6 Custom Tag Libraries (Simple Tag Handlers)
-
Implement
SimpleTaginterface:doTag()method. -
Tag Files (
.tag): Simpler alternative to Java classes.// mytag.tag <%@ tag description="My custom tag" %> Hello, ${name}!Usage:
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>then<my:mytag name="John"/>.
3.0 Java Database Connectivity (JDBC) - Advanced Usage
3.1 JDBC 4.x+ Features & Auto-Loading
- Service Provider Mechanism: Driver auto-registered via
META-INF/services/java.sql.Driverin driver JAR. No need forClass.forName("com.mysql.cj.jdbc.Driver")(since JDBC 4.0, Java 6).
3.2 Connection Pooling (DataSource)
-
Rationale: Creating connections is expensive. Pooling reuses connections, improves performance and scalability.
-
JNDI Lookup (in container like Tomcat):
Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/MyDB"); Connection conn = ds.getConnection(); -
Tomcat
context.xmlConfiguration:<Context> <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:3306/mydb" username="user" password="pass" maxTotal="20" maxIdle="10" /> </Context> -
Standalone (e.g., HikariCP):
HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:mysql://..."); config.setUsername("user"); config.setPassword("pass"); DataSource ds = new HikariDataSource(config);
3.3 Transaction Management
-
Disable Auto-Commit:
conn.setAutoCommit(false);. -
Commit/Rollback:
try { // ... execute statements ... conn.commit(); } catch (SQLException e) { conn.rollback(); // Crucial on error throw e; } finally { conn.setAutoCommit(true); // Reset for next user conn.close(); } -
Savepoints: Nested rollback points.
Savepoint sp = conn.setSavepoint("point1"); // ... some work ... conn.rollback(sp); // Rollback to this point only
3.4 Batch Processing & Large Objects (LOBs)
-
Batch Updates:
PreparedStatement ps = conn.prepareStatement("INSERT INTO users VALUES (?, ?)"); for (User u : users) { ps.setString(1, u.getName()); ps.setInt(2, u.getAge()); ps.addBatch(); } int[] counts = ps.executeBatch(); // Returns update counts -
BLOB/CLOB:
// BLOB (Binary) Blob blob = conn.createBlob(); blob.setBytes(1, fileBytes); ps.setBlob(1, blob); // CLOB (Character) Clob clob = conn.createClob(); clob.setString(1, largeText); ps.setClob(1, clob);
3.5 RowSet & ResultSet Types/Concurrency
-
ResultSetTypes:-
TYPE_FORWARD_ONLY: Default, cursor moves forward only. -
TYPE_SCROLL_INSENSITIVE: Cursor scrolls, ignores DB changes after creation. -
TYPE_SCROLL_SENSITIVE: Cursor scrolls, sees DB changes (rarely supported).
-
-
ResultSetConcurrency:-
CONCUR_READ_ONLY: Default. -
CONCUR_UPDATABLE: AllowsupdateRow(),deleteRow(),insertRow().
-
-
Creating Scrollable/Updatable RS:
Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE ); -
RowSet: DisconnectedResultSet(can operate without DB connection).-
JdbcRowSet: Connected, scrollable, updatable. -
CachedRowSet: Disconnected, can be serialized.
-
4.0 Model-View-Controller (MVC) Architecture in Java Web Apps
4.1 MVC Pattern Deep Dive
| Layer | Responsibility | Java Tech |
|---|---|---|
| Model | Business logic, data access, state | POJOs, DAO, Service classes |
| View | Presentation, UI | JSP (with JSTL/EL), HTML, Thymeleaf |
| Controller | Request handling, flow control, populates model | Servlet (Front Controller) |
-
Data Flow:
-
Client -> Servlet (Controller).
-
Servlet calls Model (Service/DAO).
-
Model returns data (JavaBean/List).
-
Servlet stores data in request/session scope.
-
Servlet forwards (
RequestDispatcher) to JSP (View). -
JSP uses EL/JSTL to display data from scope.
-
JSP renders HTML -> Client.
-
4.2 Implementing MVC with JSP/Servlet
-
Servlet (Controller):
protected void doGet(HttpServletRequest req, HttpServletResponse resp) { List<User> users = userService.getAllUsers(); // Call Model req.setAttribute("userList", users); // Store in request scope req.getRequestDispatcher("/WEB-INF/views/users.jsp").forward(req, resp); // Forward to View } -
JSP (View): NO SCRIPTLETS. Use only JSTL/EL.
<table> <c:forEach var="user" items="${userList}"> <tr><td>${user.name}</td></tr> </c:forEach> </table> -
Key: Place JSPs under
/WEB-INF/to prevent direct access (must go through controller).
4.3 MVC Frameworks Context
-
Spring MVC: Formalizes this pattern.
DispatcherServletis front controller.@Controllerclasses handle requests.ModelisModelMap/Model. View resolvers (JSP, Thymeleaf). -
Struts (1/2): Older frameworks based on same principle.
5.0 Introduction to Persistence Frameworks (ORM)
5.1 Object-Relational Mapping (ORM) Concepts
-
Impedance Mismatch: Differences between object-oriented (Java) and relational (SQL) paradigms.
-
ORM Solution: Map Java classes to DB tables, fields to columns.
-
Relationships:
-
1:1:
@OneToOne -
1:N:
@OneToMany(withmappedByon the many side) -
N:M:
@ManyToMany(requires join table)
-
-
Inheritance Strategies:
-
SINGLE_TABLE: One table for all classes, discriminator column. -
JOINED: Separate table per class, joined via PK. -
TABLE_PER_CLASS: Separate table per concrete class.
-
5.2 Java Persistence API (JPA) Overview
-
Entity Class: Must have
@Entity,@Id, no-arg constructor.@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // getters/setters } -
EntityManagerAPI:-
persist(entity): Insert new. -
merge(entity): Update existing (or insert if transient). -
find(Class, id): Retrieve by PK. -
remove(entity): Delete. -
createQuery(String jpql): Execute JPQL.
-
-
JPQL: Object-oriented query language (operates on entities, not tables).
List<User> users = em.createQuery("SELECT u FROM User u WHERE u.name LIKE :name", User.class) .setParameter("name", "John%") .getResultList();
5.3 Hibernate as JPA Provider
-
Hibernate Core API (pre-JPA):
-
SessionFactory(heavyweight, thread-safe) ->Session(lightweight, not thread-safe). -
Sessionmethods:save(),update(),delete(),get(),load(),createQuery().
-
-
Caching:
-
First-Level (Session Cache): Mandatory, per-session, same as JPA persistence context.
-
Second-Level (SessionFactory Cache): Optional, process-wide. Shared across sessions.
-
-
Fetching Strategies:
-
Lazy (
FetchType.LAZY): Default for@OneToMany,@ManyToMany. Loads related entities on-demand (via proxy). Prevents N+1 if used correctly. -
Eager (
FetchType.EAGER): Default for@ManyToOne,@OneToOne. Loads immediately (viaJOIN). -
N+1 Select Problem: Fetching parent list, then fetching each child in a loop (N queries). Solution: Use
JOIN FETCHin JPQL.// N+1 Problem List<Department> depts = em.createQuery("SELECT d FROM Department d").getResultList(); // For each dept, dept.getEmployees() triggers new query. // Fix: JOIN FETCH List<Department> depts = em.createQuery("SELECT DISTINCT d FROM Department d JOIN FETCH d.employees").getResultList();
-
6.0 Spring Framework Core (IoC & DI)
6.1 Inversion of Control (IoC) & Dependency Injection (DI)
-
IoC: Shift control of object creation/assembly from application code to Spring Container.
-
DI: Container injects dependencies (other objects) into a bean.
-
Constructor Injection (Preferred): Dependencies provided via constructor. Ensures immutability & mandatory deps.
@Service public class OrderService { private final UserRepository repo; @Autowired // Optional if only one constructor public OrderService(UserRepository repo) { this.repo = repo; } } -
Setter Injection: Dependencies provided via setter. Allows optional/reconfigurable deps.
-
Field Injection (Discouraged):
@Autowiredon field. Hard to test, hides dependencies.
-
6.2 Spring IoC Container (ApplicationContext)
-
Bean Definition: XML, Java Config, or Annotations.
-
Bean Scopes:
| Scope | Description | | :--- | :--- | |
singleton(default) | One shared instance per container | |prototype| New instance eachgetBean()call | |request| One per HTTP request (Web context) | |session| One per HTTP session (Web context) | -
Bean Lifecycle:
-
Instantiate.
-
Populate properties (DI).
-
@PostConstruct/init-method. -
Ready for use.
-
@PreDestroy/destroy-methodon container shutdown.
-
6.3 Configuration Methods
-
XML-based:
<beans> <bean id="myBean" class="com.example.MyBean"> <property name="dependency" ref="otherBean"/> </bean> <bean id="otherBean" class="..."/> </beans> -
Java-based (
@Configuration):@Configuration @ComponentScan("com.example") // Auto-detect @Component beans public class AppConfig { @Bean public MyBean myBean(OtherBean otherBean) { MyBean bean = new MyBean(); bean.setDependency(otherBean); return bean; } } -
Annotation-based (Component Scanning):
-
@Component: Generic bean. -
@Service: Service layer. -
@Repository: DAO layer (also translates DB exceptions). -
@Controller: Web controller. -
@Autowired: Injection (on constructor, field, or setter).
-
6.4 Spring AOP (Aspect-Oriented Programming) Concepts
-
Goal: Modularize cross-cutting concerns (logging, security, transactions) separate from business logic.
-
Key Terms:
-
Aspect: Module encapsulating cross-cutting logic (
@Aspectclass). -
Join Point: Point during execution (method call, field access).
-
Advice: Action taken at join point.
-
@Before: Before method execution. -
@AfterReturning: After successful return. -
@AfterThrowing: After exception thrown. -
@After(finally): After regardless of outcome. -
@Around: Wraps method (most powerful).
-
-
Pointcut: Predicate matching join points. e.g.,
execution(* com.example.service.*.*(..)). -
Introduction: Add new methods/fields to existing types.
-
Target Object: Object being advised.
-
Proxy: Object created by AOP framework (wrap target).
-
-
@AspectJStyle (Annotation-based):@Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logMethod(JoinPoint jp) { System.out.println("Calling: " + jp.getSignature()); } }
7.0 Spring Web MVC (Spring MVC)
7.1 Front Controller Pattern: DispatcherServlet
-
Request Processing Flow:
graph LR A[Client Request] --> B[DispatcherServlet<br/>Front Controller]; B --> C[HandlerMapping<br/>Find Controller]; C --> D[Controller<br/>@Controller]; D --> E[ModelAndView]; E --> F[ViewResolver<br/>Resolve View Name]; F --> G[View<br/>JSP/Thymeleaf]; G --> H[Render Response]; -
Configured in
web.xmlor viaWebApplicationInitializer:<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
7.2 Controller Implementation
-
@Controller: Returns view name (String). -
@RestController: Combination of@Controller+@ResponseBody. Returns object directly (converted to JSON/XML byHttpMessageConverter). For REST APIs. -
Request Mapping:
@Controller @RequestMapping("/users") // Class-level base path public class UserController { @GetMapping // GET /users public String list(Model model) { model.addAttribute("users", userService.findAll()); return "user/list"; // View name (resolved by ViewResolver) } @GetMapping("/{id}") // GET /users/5 public String get(@PathVariable Long id, Model model) { model.addAttribute("user", userService.findById(id)); return "user/detail"; } @PostMapping // POST /users public String create(@ModelAttribute User user) { userService.save(user); return "redirect:/users"; // PRG pattern } } -
Key Annotations:
-
@RequestParam: Bind query parameter.?name=John. -
@PathVariable: Bind URI template variable./users/{id}. -
@RequestBody: Bind HTTP request body (JSON/XML) to object (for REST). -
@ModelAttribute: Bind form parameters to object (for MVC form posts). -
@SessionAttributes: Store model attributes in session.
-
7.3 View Resolution
-
InternalResourceViewResolver(for JSP):<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean>Logical view name
"user/list"->/WEB-INF/views/user/list.jsp.
7.4 Form Handling & Validation
-
@ModelAttribute&BindingResult:@PostMapping("/users") public String submit(@Valid @ModelAttribute("user") User user, BindingResult result) { if (result.hasErrors()) { return "user/form"; // Back to form with errors } userService.save(user); return "redirect:/users"; } -
Bean Validation (JSR-303/380): Annotations on entity/bean fields.
public class User { @NotBlank @Size(min=2, max=50) private String name; @Email private String email; @Min(18) private int age; }Spring automatically validates
@Validobjects and populatesBindingResult.
8.0 Web Services & RESTful APIs
8.1 REST Architectural Principles
-
Resource: Anything (user, order) identified by URI (
/users/5). -
Representation: JSON, XML. Same resource can have multiple representations.
-
Stateless: Each request contains all info. No server-side session.
-
Uniform Interface: Use standard HTTP methods:
| Method | CRUD | Idempotent? | Safe? | | :--- | :--- | :--- | :--- | |
GET| Read | Yes | Yes | |POST| Create | No | No | |PUT| Update (full) | Yes | No | |PATCH| Update (partial) | No | No | |DELETE| Delete | Yes | No | -
HATEOAS (Hypermedia as the Engine of Application State): Responses include links to related actions.
8.2 Building REST APIs with Spring
-
@RestController: Combines@Controller+@ResponseBody. All methods return JSON/XML directly. -
@RequestMappingat class/method level:@RestController @RequestMapping("/api/v1/users") public class UserRestController { @GetMapping // GET /api/v1/users public List<User> getAll() { ... } @PostMapping // POST /api/v1/users public ResponseEntity<User> create(@RequestBody User user) { User saved = service.save(user); return ResponseEntity.status(HttpStatus.CREATED).body(saved); } @GetMapping("/{id}") // GET /api/v1/users/5 public User getOne(@PathVariable Long id) { ... } } -
ResponseEntity<T>: Full control over response (status, headers, body). -
JSON Conversion: Spring uses Jackson library (
HttpMessageConverter) automatically ifjackson-databindJAR is in classpath.
8.3 SOAP Web Services Overview (JAX-WS)
-
Service Endpoint Interface (SEI): Java interface defining web service operations.
@WebService public interface HelloWorld { @WebMethod String sayHello(String name); } -
Implementation:
@WebService(endpointInterface = "com.example.HelloWorld") public class HelloWorldImpl implements HelloWorld { public String sayHello(String name) { return "Hello " + name; } } -
WSDL Generation: Container automatically generates WSDL at
http://host:port/app/HelloWorld?wsdl. -
Client (
wsimport): JDK tool to generate Java client stubs from WSDL.wsimport -keep -p com.example.client http://...?wsdl
9.0 Application Security (Spring Security Primer)
9.1 Core Concepts
-
Authentication: Who are you? (Login, identity verification).
-
Authorization: What can you do? (Access control, permissions).
-
SecurityFilterChain: Main Spring Security filter chain (HTTP requests pass through). -
UserDetailsService: Interface to load user-specific data (username, password, roles/authorities). -
PasswordEncoder: Encodes/verifies passwords (never store plain text). UseBCryptPasswordEncoder.
9.2 Basic Configuration
-
Java Config (Modern):
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}admin").roles("ADMIN"); // {noop} = no password encoder (for demo only) } } -
{noop}: Prefix indicating password is stored in plain text (only for testing). Always usepasswordEncoder()in production.
9.3 Method-Level Security
-
Enable with
@EnableGlobalMethodSecurity(prePostEnabled = true). -
Annotations:
-
@PreAuthorize("hasRole('ADMIN')"): Check before method execution. -
@PostAuthorize("returnObject.owner == authentication.name"): Check after. -
@Secured("ROLE_USER"): Simple role check. -
@RolesAllowed("USER"): JSR-250 standard.
-
10.0 Build Automation & Project Management
10.1 Apache Maven
-
pom.xml(Project Object Model) Core Elements:<project> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>my-app</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <!-- or war --> <dependencies>...</dependencies> <build>...</build> </project> -
Dependency Scopes:
| Scope | Available in | Exported? | Typical Use | | :--- | :--- | :--- | :--- | |
compile| All classpaths | Yes | Main code deps | |provided| Compile & test | No | Servlet API, JSP API (provided by container) | |runtime| Runtime & test | Yes | JDBC drivers | |test| Test only | No | JUnit, TestNG | -
Build Lifecycle Phases:
validate->compile->test->package->verify->install->deploy. -
Standard Directory Layout:
src/main/java // Application source src/main/resources // Config files (properties, XML) src/test/java // Test source src/test/resources // Test resources target/ // Compiled output (generated) -
Key Commands:
-
mvn clean compile: Clean & compile. -
mvn test: Run tests. -
mvn package: Create JAR/WAR intarget/. -
mvn install: Install artifact to local repo (~/.m2). -
mvn dependency:tree: View dependency tree.
-
10.2 Introduction to Gradle
-
Build Script:
build.gradle(Groovy/Kotlin DSL). More concise than XML. -
Key Differences: Convention over configuration, incremental builds, multi-project builds easier.
-
Example:
plugins { id 'java' 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' }
11.0 Logging & Application Monitoring
11.1 SLF4J & Logback/Log4j2
-
SLF4J (Simple Logging Facade for Java): Facade API. Code uses SLF4J interfaces (
Logger,LoggerFactory). Actual implementation (Logback, Log4j2) is plugged in at runtime via binding JAR.import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyClass { private static final Logger logger = LoggerFactory.getLogger(MyClass.class); public void doSomething() { logger.info("Operation started"); logger.debug("Details: {}", someObject); // Parameterized } } -
Logback: Default implementation with SLF4J. Fast, native implementation.
-
Log4j2: Alternative, high-performance. Different configuration (
log4j2.xml). -
Configuration (
logback.xml):<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> <logger name="com.example" level="DEBUG" /> // Package-specific level </configuration> -
Log Levels (increasing severity):
TRACE<DEBUG<INFO<WARN<ERROR.
11.2 Logging Best Practices
-
Use Parameterized Logging:
logger.debug("User {} logged in from {}", userId, ip);(avoids string concatenation cost if level disabled). -
Never log sensitive data: Passwords, credit cards, PII.
-
Use meaningful messages: Include context (user ID, transaction ID).
-
Log at appropriate level:
INFOfor business events,DEBUGfor troubleshooting,WARNfor recoverable issues,ERRORfor failures.
12.0 Deployment & Runtime Environments
12.1 Web Application Archive (WAR) Structure
myapp.war (zip file)
│
├── META-INF/
│ └── MANIFEST.MF
│
├── WEB-INF/
│ ├── web.xml // Deployment descriptor (optional with annotations)
│ ├── classes/ // Compiled .class files
│ │ └── com/example/...
│ ├── lib/ // Dependency JARs (excluding container-provided)
│ │ ├── spring-webmvc.jar
│ │ └── mysql-connector.jar
│ └── tags/ // JSP tag files (.tag)
│
├── static/ // Static resources (CSS, JS, images)
│ ├── css/
│ └── js/
│
└── *.jsp // JSPs (usually under /WEB-INF/ for security)
12.2 Deployment to Servlet Containers (Tomcat)
-
server.xmlKey Elements:<Server port="8005" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="8080" protocol="HTTP/1.1" ... /> <!-- Handles HTTP --> <Engine name="Catalina" defaultHost="localhost"> <Host name="localhost" appBase="webapps" ... > <!-- Apps deployed here --> </Host> </Engine> </Service> </Server> -
context.xml(Global or Per-App): Define resources like DataSource.<Context> <Resource name="jdbc/MyDB" ... /> </Context> -
Deployment Methods:
-
Auto-Deploy: Copy WAR to
$CATALINA_HOME/webapps/. Tomcat auto-explodes & deploys. -
Manager App: Use Tomcat's web manager (
/manager/html) to deploy/undeploy. -
Context XML Descriptor: Create
$CATALINA_BASE/conf/[engine]/[host]/myapp.xmlpointing to WAR location. -
IDE Integration: Eclipse/IntelliJ "Run on Server".
-
12.3 Context Parameters & Environment-Specific Configuration
-
<context-param>inweb.xml:<context-param> <param-name>appName</param-name> <param-value>My Advanced App</param-value> </context-param>Access via
ServletContext.getInitParameter("appName"). -
JNDI for External Config (DataSource): As shown in Section 3.2. Keeps DB credentials out of application code/WAR.
-
Environment-Specific Config: Use Maven profiles to generate different
web.xmlor property files fordev,test,prod. Or use JNDI environment entries in Tomcat'scontext.xml.