or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

error-handling.mdfilter-handling.mdindex.mdlisteners.mdmonitoring.mdservlet-context.mdservlet-handling.mdtesting.md

servlet-context.mddocs/

0

# Servlet Context Management

1

2

Servlet context management in Eclipse Jetty provides comprehensive functionality for creating, configuring, and managing servlet contexts with support for sessions, security, error handling, and dynamic registration.

3

4

## ServletContextHandler

5

6

The `ServletContextHandler` is the main class for servlet context management, extending Jetty's `ContextHandler` to provide servlet-specific functionality.

7

8

```java { .api }

9

public class ServletContextHandler extends ContextHandler {

10

// Options constants

11

public static final int SESSIONS = 1;

12

public static final int SECURITY = 2;

13

public static final int NO_SESSIONS = 0;

14

public static final int NO_SECURITY = 0;

15

16

// Constructors

17

public ServletContextHandler();

18

public ServletContextHandler(int options);

19

public ServletContextHandler(HandlerContainer parent, String contextPath);

20

public ServletContextHandler(HandlerContainer parent, String contextPath, int options);

21

public ServletContextHandler(HandlerContainer parent, String contextPath,

22

boolean sessions, boolean security);

23

public ServletContextHandler(HandlerContainer parent,

24

SessionHandler sessionHandler,

25

SecurityHandler securityHandler,

26

ServletHandler servletHandler,

27

ErrorHandler errorHandler);

28

public ServletContextHandler(HandlerContainer parent, String contextPath,

29

SessionHandler sessionHandler,

30

SecurityHandler securityHandler,

31

ServletHandler servletHandler,

32

ErrorHandler errorHandler);

33

public ServletContextHandler(HandlerContainer parent, String contextPath,

34

SessionHandler sessionHandler,

35

SecurityHandler securityHandler,

36

ServletHandler servletHandler,

37

ErrorHandler errorHandler, int options);

38

}

39

```

40

41

### Basic Context Creation

42

43

```java

44

// Simple context with default configuration

45

ServletContextHandler context = new ServletContextHandler("/myapp");

46

47

// Context with sessions enabled

48

ServletContextHandler contextWithSessions =

49

new ServletContextHandler(ServletContextHandler.SESSIONS);

50

51

// Context with both sessions and security

52

ServletContextHandler fullContext =

53

new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);

54

55

// Context with parent handler and path

56

Server server = new Server(8080);

57

ServletContextHandler context = new ServletContextHandler(server, "/api");

58

```

59

60

### Servlet Registration

61

62

```java { .api }

63

// Add servlet methods

64

public ServletHolder addServlet(String className, String pathSpec);

65

public ServletHolder addServlet(Class<? extends Servlet> servlet, String pathSpec);

66

public void addServlet(ServletHolder servlet, String pathSpec);

67

68

// Filter methods

69

public void addFilter(FilterHolder holder, String pathSpec,

70

EnumSet<DispatcherType> dispatches);

71

public FilterHolder addFilter(Class<? extends Filter> filterClass, String pathSpec,

72

EnumSet<DispatcherType> dispatches);

73

public FilterHolder addFilter(String filterClass, String pathSpec,

74

EnumSet<DispatcherType> dispatches);

75

```

76

77

### Handler Management

78

79

```java { .api }

80

// Handler access methods

81

public ServletHandler getServletHandler();

82

public SessionHandler getSessionHandler();

83

public SecurityHandler getSecurityHandler();

84

85

// Handler configuration

86

public void setSessionHandler(SessionHandler sessionHandler);

87

public void setSecurityHandler(SecurityHandler securityHandler);

88

public void setServletHandler(ServletHandler servletHandler);

89

public void insertHandler(HandlerWrapper handler);

90

91

// Handler creation hooks

92

protected SessionHandler newSessionHandler();

93

protected SecurityHandler newSecurityHandler();

94

protected ServletHandler newServletHandler();

95

```

96

97

### Lifecycle Management

98

99

```java { .api }

100

// Lifecycle methods

101

protected void startContext();

102

protected void stopContext();

103

104

// Context listener support

105

public boolean addEventListener(EventListener listener);

106

public void callContextInitialized(ServletContextListener l, ServletContextEvent e);

107

public void callContextDestroyed(ServletContextListener l, ServletContextEvent e);

108

```

109

110

### ServletContainerInitializer Support

111

112

```java { .api }

113

// SCI registration methods

114

public ServletContainerInitializerHolder addServletContainerInitializer(

115

ServletContainerInitializer sci);

116

public ServletContainerInitializerHolder addServletContainerInitializer(

117

ServletContainerInitializer sci, Class<?>... classes);

118

public void addServletContainerInitializer(

119

ServletContainerInitializerHolder... sciHolders);

120

```

121

122

### Security Integration

123

124

```java { .api }

125

// Security configuration

126

public Class<? extends SecurityHandler> getDefaultSecurityHandlerClass();

127

public void setDefaultSecurityHandlerClass(

128

Class<? extends SecurityHandler> defaultSecurityHandlerClass);

129

public Set<String> setServletSecurity(

130

ServletRegistration.Dynamic registration,

131

ServletSecurityElement servletSecurityElement);

132

protected void addRoles(String... roleNames);

133

```

134

135

### Utility Methods

136

137

```java { .api }

138

// Static utility methods

139

public static ServletContextHandler getServletContextHandler(

140

ServletContext servletContext, String purpose);

141

public static ServletContextHandler getServletContextHandler(ServletContext context);

142

143

// Object factory access

144

public DecoratedObjectFactory getObjectFactory();

145

146

// Dynamic registration support

147

protected ServletRegistration.Dynamic dynamicHolderAdded(ServletHolder holder);

148

```

149

150

## Usage Examples

151

152

### Complete Context Setup

153

154

```java

155

import org.eclipse.jetty.servlet.ServletContextHandler;

156

import org.eclipse.jetty.servlet.FilterHolder;

157

import org.eclipse.jetty.server.Server;

158

import jakarta.servlet.DispatcherType;

159

import java.util.EnumSet;

160

161

// Create server and context

162

Server server = new Server(8080);

163

ServletContextHandler context = new ServletContextHandler("/webapp");

164

165

// Add servlets

166

context.addServlet(MyServlet.class, "/data/*");

167

context.addServlet("com.example.ConfigServlet", "/config");

168

169

// Add filters

170

FilterHolder filterHolder = new FilterHolder(LoggingFilter.class);

171

filterHolder.setInitParameter("logLevel", "INFO");

172

context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));

173

174

// Add context to server

175

server.setHandler(context);

176

server.start();

177

```

178

179

### Context with Custom Handlers

180

181

```java

182

import org.eclipse.jetty.security.SecurityHandler;

183

import org.eclipse.jetty.server.session.SessionHandler;

184

import org.eclipse.jetty.servlet.ServletHandler;

185

186

// Create custom handlers

187

SessionHandler sessionHandler = new SessionHandler();

188

SecurityHandler securityHandler = new MySecurityHandler();

189

ServletHandler servletHandler = new ServletHandler();

190

191

// Create context with custom handlers

192

ServletContextHandler context = new ServletContextHandler(

193

null, // no parent

194

"/secure",

195

sessionHandler,

196

securityHandler,

197

servletHandler,

198

null // default error handler

199

);

200

201

// Configure session timeout

202

sessionHandler.setMaxInactiveInterval(1800); // 30 minutes

203

204

// Register servlets through the servlet handler

205

servletHandler.addServletWithMapping(SecureServlet.class, "/secure/*");

206

```

207

208

### ServletContainerInitializer Registration

209

210

```java

211

import jakarta.servlet.ServletContainerInitializer;

212

import jakarta.servlet.ServletContext;

213

import jakarta.servlet.annotation.HandlesTypes;

214

import java.util.Set;

215

216

@HandlesTypes({WebServlet.class, WebFilter.class})

217

public class MyInitializer implements ServletContainerInitializer {

218

@Override

219

public void onStartup(Set<Class<?>> webAppInitializerClasses,

220

ServletContext servletContext) {

221

// Initialize web components

222

for (Class<?> clazz : webAppInitializerClasses) {

223

// Process annotated classes

224

}

225

}

226

}

227

228

// Register the initializer

229

ServletContextHandler context = new ServletContextHandler("/app");

230

context.addServletContainerInitializer(new MyInitializer(),

231

WebServlet.class, WebFilter.class);

232

```

233

234

## Inner Classes and Interfaces

235

236

### Context Implementation

237

238

```java { .api }

239

public class Context extends ContextHandler.Context {

240

// Extended ServletContext implementation

241

// Provides servlet-specific context functionality

242

}

243

```

244

245

### JSP Support Classes

246

247

```java { .api }

248

public static class JspPropertyGroup implements JspPropertyGroupDescriptor {

249

// JSP property group implementation

250

}

251

252

public static class TagLib implements TaglibDescriptor {

253

// Tag library descriptor implementation

254

}

255

256

public static class JspConfig implements JspConfigDescriptor {

257

// JSP configuration descriptor implementation

258

}

259

```

260

261

### ServletContainerInitializer Support

262

263

```java { .api }

264

public interface ServletContainerInitializerCaller extends LifeCycle {

265

// Interface for SCI caller implementations

266

}

267

268

public static class ServletContainerInitializerStarter extends ContainerLifeCycle

269

implements ServletContainerInitializerCaller {

270

// SCI starter bean implementation

271

}

272

```

273

274

## Configuration Patterns

275

276

### Programmatic Configuration

277

278

```java

279

// Create context with all features enabled

280

ServletContextHandler context = new ServletContextHandler(

281

ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);

282

context.setContextPath("/myapp");

283

284

// Configure display name

285

context.setDisplayName("My Application");

286

287

// Set context parameters

288

context.setInitParameter("config.location", "/etc/myapp/config.xml");

289

context.setInitParameter("debug.enabled", "true");

290

291

// Add error pages

292

ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();

293

errorHandler.addErrorPage(404, "/error/404.html");

294

errorHandler.addErrorPage(500, "/error/500.html");

295

context.setErrorHandler(errorHandler);

296

```

297

298

### Handler Chain Configuration

299

300

```java

301

// Create handlers in order

302

ServletContextHandler context = new ServletContextHandler("/app");

303

304

// Insert additional handlers

305

GzipHandler gzipHandler = new GzipHandler();

306

context.insertHandler(gzipHandler);

307

308

// Configure security

309

LoginService loginService = new HashLoginService("MyRealm", "realm.properties");

310

ConstraintSecurityHandler security = new ConstraintSecurityHandler();

311

security.setLoginService(loginService);

312

context.setSecurityHandler(security);

313

```

314

315

### Event Listener Registration

316

317

```java

318

// Add various types of listeners

319

context.addEventListener(new MyServletContextListener());

320

context.addEventListener(new MyHttpSessionListener());

321

context.addEventListener(new MyServletRequestListener());

322

323

// Use decorating listener for dependency injection

324

DecoratingListener decorator = new DecoratingListener(context, "dependencyInjector");

325

context.addEventListener(decorator);

326

```