or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdcontroller-annotations.mdfunctional-web.mdindex.mdresource-handling.mdservlet-framework.mdsupport-utilities.mdview-resolution.md

servlet-framework.mddocs/

0

# Core Servlet Framework

1

2

The core servlet framework provides the foundation of Spring MVC's request processing infrastructure. It centers around the DispatcherServlet front controller and implements the Strategy pattern through key interfaces for handler mapping, adaptation, view resolution, and exception handling.

3

4

## Capabilities

5

6

### DispatcherServlet

7

8

The central dispatcher that receives all HTTP requests and coordinates their processing through various pluggable strategies. Acts as the front controller in the MVC pattern, managing the request-response lifecycle.

9

10

```java { .api }

11

/**

12

* Central dispatcher for HTTP request handlers/controllers.

13

* Integrates with Spring IoC container for dependency injection.

14

*/

15

public class DispatcherServlet extends FrameworkServlet {

16

17

/** Default constructor - initializes with empty WebApplicationContext */

18

public DispatcherServlet();

19

20

/** Constructor with existing WebApplicationContext */

21

public DispatcherServlet(WebApplicationContext webApplicationContext);

22

23

/** Configure whether to detect all HandlerMapping beans (default: true) */

24

public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings);

25

26

/** Configure whether to detect all HandlerAdapter beans (default: true) */

27

public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters);

28

29

/** Configure whether to detect all HandlerExceptionResolver beans (default: true) */

30

public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers);

31

32

/** Configure whether to detect all ViewResolver beans (default: true) */

33

public void setDetectAllViewResolvers(boolean detectAllViewResolvers);

34

35

/** Get the configured MultipartResolver (may be null) */

36

public final MultipartResolver getMultipartResolver();

37

38

/** Get all configured HandlerMapping instances */

39

public final List<HandlerMapping> getHandlerMappings();

40

41

// Constants for bean names

42

public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver";

43

public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver";

44

public static final String THEME_RESOLVER_BEAN_NAME = "themeResolver";

45

public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping";

46

public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";

47

public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";

48

public static final String REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator";

49

public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver";

50

public static final String FLASH_MAP_MANAGER_BEAN_NAME = "flashMapManager";

51

}

52

```

53

54

**Usage Example:**

55

56

```java

57

// Programmatic configuration

58

@Configuration

59

public class WebConfig {

60

61

@Bean

62

public DispatcherServlet dispatcherServlet() {

63

DispatcherServlet servlet = new DispatcherServlet();

64

servlet.setDetectAllHandlerMappings(true);

65

servlet.setDetectAllViewResolvers(true);

66

return servlet;

67

}

68

}

69

70

// Web.xml configuration

71

<servlet>

72

<servlet-name>springDispatcher</servlet-name>

73

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

74

<init-param>

75

<param-name>contextConfigLocation</param-name>

76

<param-value>/WEB-INF/spring-mvc-config.xml</param-value>

77

</init-param>

78

<load-on-startup>1</load-on-startup>

79

</servlet>

80

```

81

82

### FrameworkServlet

83

84

Abstract base class providing the foundation for Spring's servlet framework. Manages the WebApplicationContext lifecycle and provides hooks for customization.

85

86

```java { .api }

87

/**

88

* Base class for Spring's servlet framework providing WebApplicationContext integration.

89

*/

90

public abstract class FrameworkServlet extends HttpServletBean {

91

92

/** Set the context class to use for creating the WebApplicationContext */

93

public void setContextClass(Class<?> contextClass);

94

95

/** Set the config location for the WebApplicationContext */

96

public void setContextConfigLocation(String contextConfigLocation);

97

98

/** Set the namespace for this servlet (defaults to servlet name + "-servlet") */

99

public void setNamespace(String namespace);

100

101

/** Get the WebApplicationContext for this servlet */

102

public final WebApplicationContext getWebApplicationContext();

103

104

/** Called to initialize the FrameworkServlet (template method) */

105

protected abstract void initFrameworkServlet() throws ServletException;

106

}

107

```

108

109

### HandlerMapping

110

111

Strategy interface that defines the mapping between requests and handler objects. Implementations determine how URLs are mapped to controllers or handler functions.

112

113

```java { .api }

114

/**

115

* Interface for objects that define a mapping between requests and handler objects.

116

*/

117

public interface HandlerMapping {

118

119

/**

120

* Return a handler and any interceptors for this request.

121

* Returns null if no mapping found.

122

*/

123

HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;

124

125

/**

126

* Whether this HandlerMapping uses parsed PathPatterns or String pattern matching.

127

* Default implementation returns false for String pattern matching.

128

*/

129

default boolean usesPathPatterns() {

130

return false;

131

}

132

133

// Request attribute names

134

String BEST_MATCHING_HANDLER_ATTRIBUTE = HandlerMapping.class.getName() + ".bestMatchingHandler";

135

String LOOKUP_PATH = HandlerMapping.class.getName() + ".lookupPath";

136

String PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE = HandlerMapping.class.getName() + ".pathWithinHandlerMapping";

137

String BEST_MATCHING_PATTERN_ATTRIBUTE = HandlerMapping.class.getName() + ".bestMatchingPattern";

138

String INTROSPECT_TYPE_LEVEL_MAPPING = HandlerMapping.class.getName() + ".introspectTypeLevelMapping";

139

String URI_TEMPLATE_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".uriTemplateVariables";

140

String MATRIX_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".matrixVariables";

141

String PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE = HandlerMapping.class.getName() + ".producibleMediaTypes";

142

}

143

```

144

145

### HandlerAdapter

146

147

Strategy interface that allows the DispatcherServlet to be parameterized with different types of handlers. Adapts various handler types to a common interface.

148

149

```java { .api }

150

/**

151

* MVC framework SPI, allowing parameterization of the core MVC workflow.

152

*/

153

public interface HandlerAdapter {

154

155

/** Return whether this adapter can handle the given handler instance */

156

boolean supports(Object handler);

157

158

/**

159

* Handle the request with the given handler.

160

* Returns ModelAndView for view rendering, or null for direct response handling.

161

*/

162

ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)

163

throws Exception;

164

165

/**

166

* Return the last-modified timestamp for the given handler.

167

* Deprecated as of Spring 4.3 in favor of HTTP caching support.

168

*/

169

@Deprecated

170

long getLastModified(HttpServletRequest request, Object handler);

171

}

172

```

173

174

### ViewResolver

175

176

Strategy interface for resolving view names returned by controllers into actual View objects that can render the response.

177

178

```java { .api }

179

/**

180

* Interface to be implemented by objects that can resolve views by name.

181

*/

182

public interface ViewResolver {

183

184

/**

185

* Resolve the given view name into a View object.

186

* Returns null if the view name cannot be resolved.

187

*/

188

View resolveViewName(String viewName, Locale locale) throws Exception;

189

}

190

```

191

192

### View

193

194

Interface that represents a view in the MVC framework. Responsible for rendering output using the provided model data.

195

196

```java { .api }

197

/**

198

* MVC View for a web interaction.

199

*/

200

public interface View {

201

202

/** Return the content type of the view (may be null) */

203

String getContentType();

204

205

/**

206

* Render the view given the specified model.

207

* Implementations should write to the response OutputStream or Writer.

208

*/

209

void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)

210

throws Exception;

211

212

// Attribute names for response status and path variables

213

String RESPONSE_STATUS_ATTRIBUTE = View.class.getName() + ".responseStatus";

214

String PATH_VARIABLES = View.class.getName() + ".pathVariables";

215

String SELECTED_CONTENT_TYPE = View.class.getName() + ".selectedContentType";

216

}

217

```

218

219

### HandlerExceptionResolver

220

221

Strategy interface for resolving exceptions thrown during handler execution. Allows for consistent error handling across the application.

222

223

```java { .api }

224

/**

225

* Interface to be implemented by objects that can resolve exceptions thrown during handler execution.

226

*/

227

public interface HandlerExceptionResolver {

228

229

/**

230

* Try to resolve the given exception, returning a ModelAndView for error display.

231

* Returns null if the exception should be propagated up the call stack.

232

*/

233

ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,

234

Object handler, Exception ex);

235

}

236

```

237

238

### HandlerExecutionChain

239

240

Represents a handler execution chain consisting of a handler object and optional interceptors. Manages the execution lifecycle including pre/post processing.

241

242

```java { .api }

243

/**

244

* Handler execution chain consisting of handler object and any handler interceptors.

245

*/

246

public class HandlerExecutionChain {

247

248

/** Create with handler only (no interceptors) */

249

public HandlerExecutionChain(Object handler);

250

251

/** Create with handler and interceptors */

252

public HandlerExecutionChain(Object handler, HandlerInterceptor... interceptors);

253

254

/** Get the handler object */

255

public Object getHandler();

256

257

/** Get the array of interceptors (may be null) */

258

public HandlerInterceptor[] getInterceptors();

259

260

/**

261

* Apply preHandle methods of registered interceptors.

262

* Returns false if execution should not proceed.

263

*/

264

public boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response)

265

throws Exception;

266

267

/** Apply postHandle methods of registered interceptors */

268

public void applyPostHandle(HttpServletRequest request, HttpServletResponse response,

269

ModelAndView mv) throws Exception;

270

271

/** Apply afterCompletion methods of registered interceptors */

272

public void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response,

273

Exception ex) throws Exception;

274

}

275

```

276

277

### ModelAndView

278

279

Container for both model data and view information. Used by controllers to return both the data to display and the view that should render it.

280

281

```java { .api }

282

/**

283

* Holder for both Model and View in the web MVC framework.

284

*/

285

public class ModelAndView {

286

287

/** Create empty ModelAndView */

288

public ModelAndView();

289

290

/** Create with view name */

291

public ModelAndView(String viewName);

292

293

/** Create with View object */

294

public ModelAndView(View view);

295

296

/** Create with view name and model */

297

public ModelAndView(String viewName, Map<String, ?> model);

298

299

/** Create with view name and single model object */

300

public ModelAndView(String viewName, String modelName, Object modelObject);

301

302

/** Set the view name */

303

public void setViewName(String viewName);

304

305

/** Get the view name */

306

public String getViewName();

307

308

/** Set the View object */

309

public void setView(View view);

310

311

/** Get the View object */

312

public View getView();

313

314

/** Add an attribute to the model */

315

public ModelAndView addObject(String attributeName, Object attributeValue);

316

317

/** Add multiple attributes to the model */

318

public ModelAndView addAllObjects(Map<String, ?> modelMap);

319

320

/** Get the model Map */

321

public Map<String, Object> getModel();

322

323

/** Set HTTP status for the response */

324

public void setStatus(HttpStatusCode status);

325

326

/** Get the HTTP status */

327

public HttpStatusCode getStatus();

328

329

/** Return whether this ModelAndView has a view */

330

public boolean hasView();

331

332

/** Return whether the view reference is by name or object */

333

public boolean isReference();

334

335

/** Clear the ModelAndView */

336

public void clear();

337

}

338

```

339

340

**Usage Examples:**

341

342

```java

343

@Controller

344

public class BookController {

345

346

@Autowired

347

private BookService bookService;

348

349

@RequestMapping("/books/{id}")

350

public ModelAndView getBook(@PathVariable Long id) {

351

Book book = bookService.findById(id);

352

ModelAndView mv = new ModelAndView("book-details");

353

mv.addObject("book", book);

354

mv.addObject("title", "Book Details");

355

return mv;

356

}

357

358

@RequestMapping("/books")

359

public ModelAndView listBooks() {

360

List<Book> books = bookService.findAll();

361

return new ModelAndView("book-list", "books", books);

362

}

363

364

@ExceptionHandler(BookNotFoundException.class)

365

public ModelAndView handleBookNotFound(BookNotFoundException ex) {

366

ModelAndView mv = new ModelAndView("error");

367

mv.addObject("message", ex.getMessage());

368

mv.setStatus(HttpStatus.NOT_FOUND);

369

return mv;

370

}

371

}

372

```

373

374

## Handler Mapping Implementations

375

376

### SimpleUrlHandlerMapping

377

378

Direct URL pattern to handler bean mapping using a properties-style configuration or Map.

379

380

```java { .api }

381

/**

382

* Implementation of HandlerMapping that takes a Map of URL patterns to handler beans.

383

*/

384

public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {

385

386

/** Set URL mappings from Properties object */

387

public void setMappings(Properties mappings);

388

389

/** Set URL mappings from Map */

390

public void setUrlMap(Map<String, ?> urlMap);

391

392

/** Get the configured URL mappings */

393

public Map<String, ?> getUrlMap();

394

}

395

```

396

397

### BeanNameUrlHandlerMapping

398

399

Maps URL paths to Spring bean names, automatically detecting beans whose names start with "/".

400

401

```java { .api }

402

/**

403

* Implementation that interprets URL paths as Spring bean names.

404

*/

405

public class BeanNameUrlHandlerMapping extends AbstractDetectingUrlHandlerMapping {

406

// Automatically detects beans with names starting with "/"

407

// No additional public methods beyond parent classes

408

}

409

```

410

411

## Exception Resolution Implementations

412

413

### SimpleMappingExceptionResolver

414

415

Maps exception class names to view names using a properties-style configuration.

416

417

```java { .api }

418

/**

419

* Simple HandlerExceptionResolver that allows for mapping exception class names to view names.

420

*/

421

public class SimpleMappingExceptionResolver extends AbstractHandlerExceptionResolver {

422

423

/** Set exception class name to view name mappings */

424

public void setExceptionMappings(Properties mappings);

425

426

/** Set exception class name to HTTP status code mappings */

427

public void setStatusCodes(Properties statusCodes);

428

429

/** Set default view name for unmapped exceptions */

430

public void setDefaultErrorView(String defaultErrorView);

431

432

/** Set default HTTP status code for unmapped exceptions */

433

public void setDefaultStatusCode(int defaultStatusCode);

434

435

/** Set name of exception attribute in model */

436

public void setExceptionAttribute(String exceptionAttribute);

437

}

438

```

439

440

**Usage Example:**

441

442

```java

443

@Configuration

444

public class WebConfig {

445

446

@Bean

447

public SimpleMappingExceptionResolver exceptionResolver() {

448

SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();

449

450

Properties mappings = new Properties();

451

mappings.setProperty("java.lang.Exception", "error");

452

mappings.setProperty("java.lang.RuntimeException", "error");

453

resolver.setExceptionMappings(mappings);

454

455

Properties statusCodes = new Properties();

456

statusCodes.setProperty("error", "500");

457

resolver.setStatusCodes(statusCodes);

458

459

resolver.setDefaultErrorView("error");

460

resolver.setDefaultStatusCode(500);

461

462

return resolver;

463

}

464

}

465

```