wad-lab 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wad-lab",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "Interactive CLI for WAD Lab starter templates compatible with Node 12+",
5
5
  "bin": {
6
6
  "wad-lab": "./bin/index.js"
@@ -1,389 +0,0 @@
1
- # Complete Java Servlet Lab Exam Quick-Revision Guide
2
- > **Subject:** Web Application Development (WAD) Laboratory
3
- > **Topic:** Java Servlets, Apache Tomcat, Directory Structure & Flow of Execution
4
-
5
- ---
6
-
7
- ## 1. The Core Architecture (What Actually Happens)
8
-
9
- A **Servlet** is a server-side Java class that handles HTTP requests from a client (browser) and generates dynamic HTTP responses (HTML, JSON, etc.).
10
-
11
- ### The Servlet Lifecycle
12
- The Servlet Container (Tomcat) manages the life of a servlet:
13
- 1. **`init()`**: Called **only once** when the servlet is first loaded into memory. Used for one-time initialization (e.g., opening database connections).
14
- 2. **`service(request, response)`**: Called on **every request**. Tomcat spawns a thread and delegates to `doGet()` or `doPost()` based on the HTTP method.
15
- 3. **`destroy()`**: Called **only once** when Tomcat shuts down or unloads the servlet. Cleans up resources.
16
-
17
- ```text
18
- Browser Request ──> Tomcat Server ──> web.xml Lookup ──> Servlet.service() ──> doGet() / doPost() ──> HTML Response
19
- ```
20
-
21
- ---
22
-
23
- ## 2. The Golden Directory Structure
24
-
25
- Every Java web application inside Tomcat's `webapps/` folder **must** follow this standardized layout:
26
-
27
- ```text
28
- Tomcat/
29
- └── webapps/
30
- └── YourAppName/ <── Context Root (Determines URL prefix!)
31
- │
32
- ├── index.html <── Public files (HTML forms, CSS, JS)
33
- │
34
- └── WEB-INF/ <── PRIVATE (Hidden from direct browser access)
35
- │
36
- ├── web.xml <── Deployment Descriptor (Maps URLs to Servlets)
37
- │
38
- ├── classes/ <── Compiled bytecode (.class files go here!)
39
- │ └── HelloServlet.class
40
- │
41
- └── lib/ <── Third-party JARs only (e.g. mysql-connector.jar)
42
- (NEVER put servlet-api.jar here!)
43
- ```
44
-
45
- > [!IMPORTANT]
46
- > - **Case sensitivity matters:** `WEB-INF` must be uppercase with a hyphen. `classes` and `lib` must be lowercase.
47
- > - The folder name under `webapps/` (e.g., `YourAppName`) becomes the **Context Path** in your URL:
48
- > `http://localhost:8080/YourAppName/`
49
-
50
- ---
51
-
52
- ## 3. How the URL is Constructed
53
-
54
- ```text
55
- http://localhost:8080 / ServletFlow / hello
56
- └─────── 1 ─────────┘ └─── 2 ───┘ └── 3 ──┘
57
- Server & Port Context Path Servlet Mapping
58
- (Folder Name) (web.xml)
59
- ```
60
-
61
- 1. **`http://localhost:8080/`** &rarr; Server hostname and HTTP port.
62
- 2. **`/ServletFlow/`** &rarr; The application folder name inside `webapps/`. (You never configure this in `web.xml`—Tomcat uses the directory name automatically).
63
- 3. **`/hello`** &rarr; The `<url-pattern>` defined in `web.xml`.
64
-
65
- ---
66
-
67
- ## 4. How to Trigger a Servlet: The 4 Lab Scenarios
68
-
69
- ### Key Rules to Memorize for Lab:
70
- 1. `<a href="...">` anchor tag **always sends a `GET` request** $\rightarrow$ Tomcat invokes `doGet()`.
71
- 2. Typing a URL directly into the browser address bar **always sends a `GET` request** $\rightarrow$ invokes `doGet()`.
72
- 3. `<form method="get">` sends data in the URL query string (`?username=Simiyon`) $\rightarrow$ invokes `doGet()`.
73
- 4. `<form method="post">` sends data secretly in HTTP body $\rightarrow$ invokes `doPost()`. If only `doGet()` is present, Tomcat throws **HTTP 405 Method Not Allowed**.
74
-
75
- ---
76
-
77
- ### Scenario 1: Anchor Link `<a>` (Just "Hello World", No Form)
78
- **HTML (`index.html`):**
79
- ```html
80
- <!DOCTYPE html>
81
- <html>
82
- <body>
83
- <h2>Click below to say hello:</h2>
84
- <!-- Clicking an anchor tag sends a GET request to http://localhost:8080/YourApp/hello -->
85
- <a href="hello">Say Hello World</a>
86
- </body>
87
- </html>
88
- ```
89
-
90
- **Servlet (`HelloServlet.java`):**
91
- ```java
92
- import java.io.*;
93
- import javax.servlet.*;
94
- import javax.servlet.http.*;
95
-
96
- public class HelloServlet extends HttpServlet {
97
- @Override
98
- public void doGet(HttpServletRequest request, HttpServletResponse response)
99
- throws ServletException, IOException {
100
- response.setContentType("text/html");
101
- PrintWriter out = response.getWriter();
102
- out.println("<html><body>");
103
- out.println("<h1>Hello World!</h1>");
104
- out.println("</body></html>");
105
- out.close();
106
- }
107
- }
108
- ```
109
-
110
- ---
111
-
112
- ### Scenario 2: Form with Submit Button (Just "Hello World", No Input Fields)
113
- **HTML (`index.html`):**
114
- ```html
115
- <!DOCTYPE html>
116
- <html>
117
- <body>
118
- <!-- Simple button trigger without any text boxes -->
119
- <form action="hello" method="get">
120
- <input type="submit" value="Display Hello World" />
121
- </form>
122
- </body>
123
- </html>
124
- ```
125
- *Servlet is identical to Scenario 1 (`doGet` outputs `<h1>Hello World!</h1>`).*
126
-
127
- ---
128
-
129
- ### Scenario 3: Form using `GET` ("Hello Simiyon", Visible in URL)
130
- **HTML (`index.html`):**
131
- ```html
132
- <!DOCTYPE html>
133
- <html>
134
- <body>
135
- <form action="hello" method="get">
136
- Enter name: <input type="text" name="username" />
137
- <input type="submit" value="Submit" />
138
- </form>
139
- </body>
140
- </html>
141
- ```
142
- *Browser URL after submission:* `http://localhost:8080/YourApp/hello?username=Simiyon`
143
-
144
- **Servlet (`HelloServlet.java`):**
145
- ```java
146
- import java.io.*;
147
- import javax.servlet.*;
148
- import javax.servlet.http.*;
149
-
150
- public class HelloServlet extends HttpServlet {
151
- @Override
152
- public void doGet(HttpServletRequest request, HttpServletResponse response)
153
- throws ServletException, IOException {
154
- response.setContentType("text/html");
155
- PrintWriter out = response.getWriter();
156
-
157
- // Extracts 'username' from the URL query string (?username=...)
158
- String user = request.getParameter("username");
159
-
160
- out.println("<html><body>");
161
- out.println("<h2>Hello " + user + "!!</h2>");
162
- out.println("</body></html>");
163
- out.close();
164
- }
165
- }
166
- ```
167
-
168
- ---
169
-
170
- ### Scenario 4: Form using `POST` ("Hello Simiyon", Hidden in Body)
171
- **HTML (`index.html`):**
172
- ```html
173
- <!DOCTYPE html>
174
- <html>
175
- <body>
176
- <!-- Notice method="post" -->
177
- <form action="hello" method="post">
178
- Enter name: <input type="text" name="username" />
179
- <input type="submit" value="Submit" />
180
- </form>
181
- </body>
182
- </html>
183
- ```
184
- *Browser URL stays clean:* `http://localhost:8080/YourApp/hello` (parameters sent in HTTP body).
185
-
186
- **Servlet (`HelloServlet.java`):**
187
- ```java
188
- import java.io.*;
189
- import javax.servlet.*;
190
- import javax.servlet.http.*;
191
-
192
- public class HelloServlet extends HttpServlet {
193
-
194
- // 1. Primary logic handles form submissions with method="post"
195
- @Override
196
- public void doPost(HttpServletRequest request, HttpServletResponse response)
197
- throws ServletException, IOException {
198
- response.setContentType("text/html");
199
- PrintWriter out = response.getWriter();
200
-
201
- String user = request.getParameter("username");
202
-
203
- out.println("<html><body>");
204
- out.println("<h2>Hello " + user + " (received via POST)!!</h2>");
205
- out.println("</body></html>");
206
- out.close();
207
- }
208
-
209
- // 2. CRITICAL EXAM TRICK: Override doGet and call doPost!
210
- // Why? If someone types the URL directly in the browser bar or clicks an <a> link,
211
- // the browser sends a GET request. If you don't override doGet, Tomcat throws HTTP 405!
212
- @Override
213
- public void doGet(HttpServletRequest request, HttpServletResponse response)
214
- throws ServletException, IOException {
215
- doPost(request, response);
216
- }
217
- }
218
- ```
219
-
220
- #### Why override `doGet` and call `doPost`? (The HTTP 405 Shield)
221
- | If your Servlet implements: | HTML has `method="get"` / `<a href>` | HTML has `method="post"` | Examiner types URL in browser bar |
222
- | :--- | :---: | :---: | :---: |
223
- | **Only `doGet()`** | Works ✅ | **Throws HTTP 405** ❌ | Works ✅ |
224
- | **Only `doPost()`** | **Throws HTTP 405** ❌ | Works ✅ | **Throws HTTP 405** ❌ |
225
- | **`doPost()` + call from `doGet()`** | Works ✅ | Works ✅ | Works ✅ |
226
-
227
- ---
228
-
229
- ### Pro-Tip: The Universal Servlet Pattern (Handles Both GET & POST Safely)
230
- Forward `doGet` and `doPost` to a shared method so your servlet never throws HTTP 405 whether triggered by `<a href>`, `method="get"`, or `method="post"`:
231
-
232
- ```java
233
- import java.io.*;
234
- import javax.servlet.*;
235
- import javax.servlet.http.*;
236
-
237
- public class HelloServlet extends HttpServlet {
238
-
239
- @Override
240
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
241
- throws ServletException, IOException {
242
- processRequest(req, resp);
243
- }
244
-
245
- @Override
246
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
247
- throws ServletException, IOException {
248
- processRequest(req, resp);
249
- }
250
-
251
- private void processRequest(HttpServletRequest request, HttpServletResponse response)
252
- throws ServletException, IOException {
253
- response.setContentType("text/html");
254
- PrintWriter out = response.getWriter();
255
-
256
- String user = request.getParameter("username");
257
- if (user == null || user.trim().isEmpty()) {
258
- user = "World";
259
- }
260
-
261
- out.println("<html><body>");
262
- out.println("<h1>Hello " + user + "!</h1>");
263
- out.println("</body></html>");
264
- out.close();
265
- }
266
- }
267
- ```
268
-
269
- ---
270
-
271
- ### C. The Deployment Descriptor (`web.xml`)
272
- Placed in `webapps/YourAppName/WEB-INF/web.xml`.
273
-
274
- ```xml
275
- <web-app>
276
-
277
- <!-- 1. Default Landing Page (Optional but good practice) -->
278
- <welcome-file-list>
279
- <welcome-file>index.html</welcome-file>
280
- </welcome-file-list>
281
-
282
- <!-- 2. Register the Java Servlet Class -->
283
- <servlet>
284
- <servlet-name>HelloAlias</servlet-name>
285
- <servlet-class>HelloServlet</servlet-class>
286
- </servlet>
287
-
288
- <!-- 3. Bind the URL to that Servlet -->
289
- <servlet-mapping>
290
- <servlet-name>HelloAlias</servlet-name>
291
- <url-pattern>/hello</url-pattern>
292
- </servlet-mapping>
293
-
294
- </web-app>
295
- ```
296
-
297
- #### Tag Glossary:
298
- | Tag | Purpose |
299
- | :--- | :--- |
300
- | `<web-app>` | Root configuration tag. |
301
- | `<welcome-file>` | Default page to serve if user visits `http://localhost:8080/YourApp/`. |
302
- | `<servlet-name>` | Internal nickname / alias connecting `<servlet>` to `<servlet-mapping>`. |
303
- | `<servlet-class>` | Exact compiled class name (e.g. `HelloServlet` or `com.HelloServlet`). |
304
- | `<url-pattern>` | The browser URL path that triggers this servlet (must start with `/`). |
305
-
306
- ---
307
-
308
- ## 5. Compiling with `javac`
309
-
310
- Because `javax.servlet.*` is not part of standard Java SE, you **must** supply Tomcat's `servlet-api.jar` using `-cp` (classpath), and specify the destination folder with `-d classes`:
311
-
312
- ### In Linux / Ubuntu:
313
- ```bash
314
- cd /opt/tomcat/webapps/YourAppName/WEB-INF
315
-
316
- # Relative compilation:
317
- javac -cp "../../../lib/servlet-api.jar" -d classes HelloServlet.java
318
- ```
319
-
320
- ### In Windows PowerShell:
321
- ```powershell
322
- cd C:\apache-tomcat-9.0.122\webapps\YourAppName\WEB-INF
323
-
324
- javac -cp "..\..\..\lib\servlet-api.jar" -d classes HelloServlet.java
325
- ```
326
-
327
- #### Flag Explanations:
328
- - **`-cp`**: Points to `servlet-api.jar` where `HttpServlet` is defined.
329
- - **`-d classes`**: Tells compiler to automatically put the generated `.class` inside `WEB-INF/classes/`.
330
-
331
- ---
332
-
333
- ## 6. Tomcat Commands: Windows vs Ubuntu Linux
334
-
335
- | Action | Windows (PowerShell / CMD) | Ubuntu / Linux Terminal |
336
- | :--- | :--- | :--- |
337
- | **Set Tomcat Home** | `$env:CATALINA_HOME = "C:\apache-tomcat-9.0.122"` | `export CATALINA_HOME=$(pwd)` |
338
- | **Set Java Home** | `$env:JAVA_HOME = "C:\Program Files\Java\..."` | `export JAVA_HOME=/usr/lib/jvm/default-java` |
339
- | **Give Execute Rights** | *(Not needed)* | `chmod +x bin/*.sh` |
340
- | **Start (Background)** | `bin\startup.bat` | `./bin/startup.sh` |
341
- | **Start (Foreground / Logs)** | `bin\catalina.bat run` | `./bin/catalina.sh run` |
342
- | **Stop Server** | `bin\shutdown.bat` | `./bin/shutdown.sh` *(or Ctrl + C)* |
343
-
344
- ### How to find `JAVA_HOME` on Ubuntu in the Lab:
345
- If Tomcat says `JAVA_HOME is not defined correctly`, run this in terminal:
346
- ```bash
347
- readlink -f $(which java)
348
- ```
349
- If it prints `/usr/lib/jvm/java-17-openjdk-amd64/bin/java`, your `JAVA_HOME` is:
350
- ```bash
351
- export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
352
- ```
353
-
354
- ---
355
-
356
- ## 7. Common Lab Errors & Instant Solutions
357
-
358
- ### 1. `HTTP Status 404 – Not Found`
359
- - **Cause:** Typo in the folder name under `webapps/` or typo in `<url-pattern>`.
360
- - **Fix:** Check that your URL matches `http://localhost:8080/<ExactFolderName>/<url-pattern>`.
361
-
362
- ### 2. `HTTP Status 405 – Method Not Allowed`
363
- - **Cause:** Sent an HTTP method that your Servlet did not override (e.g. typing URL in browser sends `GET`, but Servlet only has `doPost`).
364
- - **Fix:** Either submit via form `<form method="post">` OR implement `doGet` in the servlet.
365
-
366
- ### 3. `HTTP Status 500 – java.lang.ClassNotFoundException`
367
- - **Cause:** `web.xml` `<servlet-class>` does not match where `.class` actually sits.
368
- - If `<servlet-class>com.HelloServlet</servlet-class>`, it MUST be inside `classes/com/HelloServlet.class`.
369
- - If class has no package, `<servlet-class>` must just be `HelloServlet`.
370
-
371
- ### 4. `package javax.servlet does not exist` during compilation
372
- - **Cause:** Forgot `-cp` flag when running `javac`.
373
- - **Fix:** Add `-cp "path/to/servlet-api.jar"`.
374
-
375
- ### 5. Code changes not showing in browser
376
- - **Cause:** You edited `HelloServlet.java` but forgot to recompile! Tomcat runs bytecode, not `.java`.
377
- - **Fix:** Run `javac` again, then refresh browser.
378
-
379
- ---
380
-
381
- ## 8. 30-Second Lab Walkthrough Checklist
382
-
383
- 1. Go to `tomcat/webapps/` &rarr; create `MyApp/WEB-INF/classes`.
384
- 2. In `MyApp/` &rarr; create `index.html` with `<form action="hello" method="post">`.
385
- 3. In `MyApp/WEB-INF/` &rarr; write `HelloServlet.java` extending `HttpServlet`.
386
- 4. Run `javac -cp "../../../lib/servlet-api.jar" -d classes HelloServlet.java`.
387
- 5. In `MyApp/WEB-INF/` &rarr; create `web.xml` mapping `<url-pattern>/hello</url-pattern>` to `<servlet-class>HelloServlet</servlet-class>`.
388
- 6. Start Tomcat (`./bin/startup.sh` or `startup.bat`).
389
- 7. Open browser &rarr; `http://localhost:8080/MyApp/` &rarr; submit form!