0
# Web Technologies
1
2
Web layer APIs for building user interfaces and handling HTTP requests. This includes the Servlet API, JavaServer Pages (JSP), JavaServer Faces (JSF), Expression Language (EL), and WebSocket support.
3
4
## Servlet API
5
6
Core HTTP servlet programming interface for handling web requests and responses.
7
8
### HttpServlet
9
10
```java { .api }
11
public abstract class HttpServlet extends GenericServlet {
12
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
13
throws ServletException, IOException;
14
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
15
throws ServletException, IOException;
16
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
17
throws ServletException, IOException;
18
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
19
throws ServletException, IOException;
20
protected void doHead(HttpServletRequest req, HttpServletResponse resp)
21
throws ServletException, IOException;
22
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
23
throws ServletException, IOException;
24
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
25
throws ServletException, IOException;
26
}
27
```
28
29
### HttpServletRequest
30
31
```java { .api }
32
public interface HttpServletRequest extends ServletRequest {
33
String getMethod();
34
String getRequestURI();
35
StringBuffer getRequestURL();
36
String getContextPath();
37
String getServletPath();
38
String getPathInfo();
39
String getQueryString();
40
String getRemoteUser();
41
String getAuthType();
42
String getHeader(String name);
43
Enumeration<String> getHeaders(String name);
44
Enumeration<String> getHeaderNames();
45
int getIntHeader(String name);
46
long getDateHeader(String name);
47
Cookie[] getCookies();
48
HttpSession getSession();
49
HttpSession getSession(boolean create);
50
String getRequestedSessionId();
51
boolean isRequestedSessionIdValid();
52
boolean isRequestedSessionIdFromCookie();
53
boolean isRequestedSessionIdFromURL();
54
Part getPart(String name) throws IOException, ServletException;
55
Collection<Part> getParts() throws IOException, ServletException;
56
}
57
```
58
59
### HttpServletResponse
60
61
```java { .api }
62
public interface HttpServletResponse extends ServletResponse {
63
void addCookie(Cookie cookie);
64
boolean containsHeader(String name);
65
void setHeader(String name, String value);
66
void addHeader(String name, String value);
67
void setIntHeader(String name, int value);
68
void addIntHeader(String name, int value);
69
void setDateHeader(String name, long date);
70
void addDateHeader(String name, long date);
71
void setStatus(int sc);
72
void sendError(int sc, String msg) throws IOException;
73
void sendError(int sc) throws IOException;
74
void sendRedirect(String location) throws IOException;
75
String encodeURL(String url);
76
String encodeRedirectURL(String url);
77
}
78
```
79
80
### Servlet Annotations
81
82
```java { .api }
83
@Target({ElementType.TYPE})
84
@Retention(RetentionPolicy.RUNTIME)
85
public @interface WebServlet {
86
String[] value() default {};
87
String[] urlPatterns() default {};
88
int loadOnStartup() default -1;
89
WebInitParam[] initParams() default {};
90
boolean asyncSupported() default false;
91
String smallIcon() default "";
92
String largeIcon() default "";
93
String description() default "";
94
String displayName() default "";
95
}
96
97
@Target({ElementType.TYPE})
98
@Retention(RetentionPolicy.RUNTIME)
99
public @interface WebFilter {
100
String[] value() default {};
101
String[] urlPatterns() default {};
102
DispatcherType[] dispatcherTypes() default {DispatcherType.REQUEST};
103
String[] servletNames() default {};
104
WebInitParam[] initParams() default {};
105
boolean asyncSupported() default false;
106
}
107
```
108
109
## JavaServer Pages (JSP)
110
111
API for creating dynamic web pages using Java code embedded in HTML.
112
113
### JspPage
114
115
```java { .api }
116
public interface JspPage extends Servlet {
117
void jspInit();
118
void jspDestroy();
119
}
120
121
public interface HttpJspPage extends JspPage {
122
void _jspService(HttpServletRequest request, HttpServletResponse response)
123
throws ServletException, IOException;
124
}
125
```
126
127
### PageContext
128
129
```java { .api }
130
public abstract class PageContext extends JspContext {
131
public static final int PAGE_SCOPE = 1;
132
public static final int REQUEST_SCOPE = 2;
133
public static final int SESSION_SCOPE = 3;
134
public static final int APPLICATION_SCOPE = 4;
135
136
public abstract void initialize(Servlet servlet, ServletRequest request,
137
ServletResponse response, String errorPageURL, boolean needsSession,
138
int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException;
139
public abstract void release();
140
public abstract HttpSession getSession();
141
public abstract Object getPage();
142
public abstract ServletRequest getRequest();
143
public abstract ServletResponse getResponse();
144
public abstract Exception getException();
145
public abstract ServletConfig getServletConfig();
146
public abstract ServletContext getServletContext();
147
public abstract void forward(String relativeUrlPath) throws ServletException, IOException;
148
public abstract void include(String relativeUrlPath) throws ServletException, IOException;
149
public abstract void include(String relativeUrlPath, boolean flush) throws ServletException, IOException;
150
public abstract void handlePageException(Exception e) throws ServletException, IOException;
151
public abstract void handlePageException(Throwable t) throws ServletException, IOException;
152
}
153
```
154
155
## JavaServer Faces (JSF)
156
157
Component-based web application framework for building user interfaces.
158
159
### UIComponent
160
161
```java { .api }
162
public abstract class UIComponent implements StateHolder {
163
public abstract Map<String, Object> getAttributes();
164
public abstract ValueExpression getValueExpression(String name);
165
public abstract void setValueExpression(String name, ValueExpression binding);
166
public abstract String getClientId(FacesContext context);
167
public abstract String getFamily();
168
public abstract String getId();
169
public abstract void setId(String id);
170
public abstract UIComponent getParent();
171
public abstract void setParent(UIComponent parent);
172
public abstract boolean isRendered();
173
public abstract void setRendered(boolean rendered);
174
public abstract String getRendererType();
175
public abstract void setRendererType(String rendererType);
176
public abstract boolean getRendersChildren();
177
public abstract List<UIComponent> getChildren();
178
public abstract int getChildCount();
179
public abstract UIComponent findComponent(String expr);
180
public abstract Map<String, UIComponent> getFacets();
181
public abstract UIComponent getFacet(String name);
182
public abstract Iterator<UIComponent> getFacetsAndChildren();
183
public abstract void broadcast(FacesEvent event) throws AbortProcessingException;
184
public abstract void decode(FacesContext context);
185
public abstract void encodeBegin(FacesContext context) throws IOException;
186
public abstract void encodeChildren(FacesContext context) throws IOException;
187
public abstract void encodeEnd(FacesContext context) throws IOException;
188
protected abstract FacesContext getFacesContext();
189
protected abstract Renderer getRenderer(FacesContext context);
190
}
191
```
192
193
### FacesContext
194
195
```java { .api }
196
public abstract class FacesContext {
197
public static FacesContext getCurrentInstance();
198
public abstract Application getApplication();
199
public abstract Iterator<String> getClientIdsWithMessages();
200
public abstract ExternalContext getExternalContext();
201
public abstract FacesMessage.Severity getMaximumSeverity();
202
public abstract Iterator<FacesMessage> getMessages();
203
public abstract Iterator<FacesMessage> getMessages(String clientId);
204
public abstract RenderKit getRenderKit();
205
public abstract boolean getRenderResponse();
206
public abstract boolean getResponseComplete();
207
public abstract ResponseStream getResponseStream();
208
public abstract void setResponseStream(ResponseStream responseStream);
209
public abstract ResponseWriter getResponseWriter();
210
public abstract void setResponseWriter(ResponseWriter responseWriter);
211
public abstract UIViewRoot getViewRoot();
212
public abstract void setViewRoot(UIViewRoot root);
213
public abstract void addMessage(String clientId, FacesMessage message);
214
public abstract void release();
215
public abstract void renderResponse();
216
public abstract void responseComplete();
217
}
218
```
219
220
## Expression Language (EL)
221
222
Unified Expression Language for web applications.
223
224
### ELContext
225
226
```java { .api }
227
public abstract class ELContext {
228
public static final String TYPE_OBJECT = "javax.el.TYPE_OBJECT";
229
230
public abstract ELResolver getELResolver();
231
public abstract FunctionMapper getFunctionMapper();
232
public abstract VariableMapper getVariableMapper();
233
public abstract boolean isPropertyResolved();
234
public abstract void setPropertyResolved(boolean resolved);
235
public abstract void putContext(Class<?> key, Object contextObject);
236
public abstract Object getContext(Class<?> key);
237
public abstract Locale getLocale();
238
public abstract void setLocale(Locale locale);
239
}
240
```
241
242
### ValueExpression
243
244
```java { .api }
245
public abstract class ValueExpression extends Expression {
246
public abstract Object getValue(ELContext context);
247
public abstract void setValue(ELContext context, Object value);
248
public abstract boolean isReadOnly(ELContext context);
249
public abstract Class<?> getType(ELContext context);
250
public abstract Class<?> getExpectedType();
251
}
252
```
253
254
## WebSocket API
255
256
Java API for WebSocket endpoints and bidirectional communication.
257
258
### ServerEndpoint
259
260
```java { .api }
261
@Target({ElementType.TYPE})
262
@Retention(RetentionPolicy.RUNTIME)
263
public @interface ServerEndpoint {
264
String value();
265
String[] subprotocols() default {};
266
Class<?>[] decoders() default {};
267
Class<?>[] encoders() default {};
268
Class<? extends ServerEndpointConfig.Configurator> configurator()
269
default ServerEndpointConfig.Configurator.class;
270
}
271
```
272
273
### Session
274
275
```java { .api }
276
public interface Session extends Closeable {
277
RemoteEndpoint.Basic getBasicRemote();
278
RemoteEndpoint.Async getAsyncRemote();
279
boolean isOpen();
280
boolean isSecure();
281
WebSocketContainer getContainer();
282
void addMessageHandler(MessageHandler handler);
283
Set<MessageHandler> getMessageHandlers();
284
void removeMessageHandler(MessageHandler handler);
285
String getProtocolVersion();
286
String getNegotiatedSubprotocol();
287
List<Extension> getNegotiatedExtensions();
288
Map<String, Object> getUserProperties();
289
Principal getUserPrincipal();
290
URI getRequestURI();
291
Map<String, List<String>> getRequestParameterMap();
292
String getQueryString();
293
Map<String, String> getPathParameters();
294
String getId();
295
void close() throws IOException;
296
void close(CloseReason closeReason) throws IOException;
297
}
298
```
299
300
### Lifecycle Annotations
301
302
```java { .api }
303
@Target({ElementType.METHOD})
304
@Retention(RetentionPolicy.RUNTIME)
305
public @interface OnOpen {
306
}
307
308
@Target({ElementType.METHOD})
309
@Retention(RetentionPolicy.RUNTIME)
310
public @interface OnClose {
311
}
312
313
@Target({ElementType.METHOD})
314
@Retention(RetentionPolicy.RUNTIME)
315
public @interface OnMessage {
316
}
317
318
@Target({ElementType.METHOD})
319
@Retention(RetentionPolicy.RUNTIME)
320
public @interface OnError {
321
}
322
```
323
324
### Message Handlers
325
326
```java { .api }
327
public interface MessageHandler {
328
interface Whole<T> extends MessageHandler {
329
void onMessage(T message);
330
}
331
332
interface Partial<T> extends MessageHandler {
333
void onMessage(T partialMessage, boolean last);
334
}
335
}
336
337
public interface RemoteEndpoint {
338
void sendString(String text) throws IOException;
339
void sendBytes(ByteBuffer data) throws IOException;
340
void sendPartialString(String fragment, boolean isLast) throws IOException;
341
void sendPartialBytes(ByteBuffer partialByte, boolean isLast) throws IOException;
342
void sendPing(ByteBuffer applicationData) throws IOException;
343
void sendPong(ByteBuffer applicationData) throws IOException;
344
void sendObject(Object data) throws IOException, EncodeException;
345
346
interface Basic extends RemoteEndpoint {
347
Writer getSendWriter() throws IOException;
348
OutputStream getSendStream() throws IOException;
349
}
350
351
interface Async extends RemoteEndpoint {
352
long getSendTimeout();
353
void setSendTimeout(long timeoutmillis);
354
Future<Void> sendText(String text);
355
Future<Void> sendBinary(ByteBuffer data);
356
Future<Void> sendObject(Object data);
357
}
358
}
359
```
360
361
### WebSocket Container
362
363
```java { .api }
364
public interface WebSocketContainer {
365
long getDefaultMaxSessionIdleTimeout();
366
void setDefaultMaxSessionIdleTimeout(long timeout);
367
int getDefaultMaxBinaryMessageBufferSize();
368
void setDefaultMaxBinaryMessageBufferSize(int max);
369
int getDefaultMaxTextMessageBufferSize();
370
void setDefaultMaxTextMessageBufferSize(int max);
371
Set<Extension> getInstalledExtensions();
372
373
Session connectToServer(Object annotatedEndpointInstance, URI path) throws DeploymentException, IOException;
374
Session connectToServer(Class<?> annotatedEndpointClass, URI path) throws DeploymentException, IOException;
375
Session connectToServer(Endpoint endpointInstance, ClientEndpointConfig cec, URI path) throws DeploymentException, IOException;
376
Session connectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path) throws DeploymentException, IOException;
377
}
378
```
379
380
## Usage Examples
381
382
### Basic Servlet
383
384
```java
385
@WebServlet("/hello")
386
public class HelloServlet extends HttpServlet {
387
@Override
388
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
389
throws ServletException, IOException {
390
resp.setContentType("text/html");
391
resp.getWriter().println("<h1>Hello, World!</h1>");
392
}
393
}
394
```
395
396
### JSF Managed Bean
397
398
```java
399
@Named
400
@ViewScoped
401
public class UserBean implements Serializable {
402
private String name;
403
private List<User> users;
404
405
@PostConstruct
406
public void init() {
407
loadUsers();
408
}
409
410
public String save() {
411
// Save user logic
412
return "success";
413
}
414
415
// getters and setters
416
}
417
```
418
419
### WebSocket Endpoint
420
421
```java
422
@ServerEndpoint("/websocket")
423
public class EchoEndpoint {
424
425
@OnOpen
426
public void onOpen(Session session) {
427
System.out.println("WebSocket opened: " + session.getId());
428
}
429
430
@OnMessage
431
public String onMessage(String message, Session session) {
432
return "Echo: " + message;
433
}
434
435
@OnClose
436
public void onClose(Session session, CloseReason closeReason) {
437
System.out.println("WebSocket closed: " + closeReason.getReasonPhrase());
438
}
439
440
@OnError
441
public void onError(Session session, Throwable throwable) {
442
throwable.printStackTrace();
443
}
444
}