Skip to main content

dawdler-client-plug-web

Module Introduction​

A web MVC module with the same usage style as Spring MVC, covering 80% of the common Spring MVC scenarios. It provides a client for remote component loading, a remote component loading notifier, a web listener, a web interceptor, and an AOP implementation.

1. Add the dependency in pom.xml​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-client-plug-web</artifactId>

2. How to use the web MVC framework​

2.1 Create a Controller​

Write a Controller class and annotate it with @Controller.

2.2 Create an API​

Define a web API with RequestMapping. RequestMapping can be applied to a class or a method. When applied to a class, every web API path must start with the RequestMapping prefix defined on the class. (When RequestMapping is applied to a class, only value takes effect, everything else is ignored.)

3. Controller annotations​

3.1 Marker annotations​

AnnotationScopeDescription
@ControllerClassMarks a class as a Controller
@RequestMappingClass or methodMarks an API
@ResponseBodyMethodOutputs the method return value of the API as JSON

3.2 Method parameter annotations​

AnnotationScopeDescriptionConversion support
@RequestParamParameterGets a request parameter; value is the parameter nameType conversion supported
@PathVariableParameterGets an antPath variable; value is the antPath variable nameType conversion supported
@RequestAttributeParameterGets an attribute from the request scope; value is the attribute nameNot supported
@SessionAttributeParameterGets an attribute from the session scope; value is the attribute nameNot supported
@RequestHeaderParameterGets an HTTP request header value; value is the header nameType conversion supported
@CookieValueParameterGets a cookie value; value is the cookie nameType conversion supported
@RequestBodyParameterString receives a JSON request body, or a custom object is mapped via JSON (the front end must submit the JSON body in the request body)Only String is supported
@QueryParamParameterAnnotation for getting query parameters during file upload (multipart/form-data)Type conversion supported
@DateTimeFormatParameterGets a date parameter; value is the date parameter nameSupports Date, LocalDateTime, LocalDate, LocalTime, ZonedDateTime, OffsetTime, OffsetDateTime

Detailed description of the DateTimeFormat annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
public @interface DateTimeFormat {

ISO iso() default ISO.NONE;

String pattern();

enum ISO {
BASED,
NONE
}

}

When iso is set to BASED, pattern has no effect; the date string is automatically converted to the ISO8601 standard format. The corresponding formats are as follows:

TypeFormat
LocalDateTimeDateTimeFormatter.ISO_LOCAL_DATE_TIME
LocalDateDateTimeFormatter.ISO_LOCAL_DATE
LocalTimeDateTimeFormatter.ISO_LOCAL_TIME
ZonedDateTimeDateTimeFormatter.ISO_ZONED_DATE_TIME
OffsetDateTimeDateTimeFormatter.ISO_OFFSET_DATE_TIME
OffsetTimeDateTimeFormatter.ISO_OFFSET_TIME
DateDateTimeFormatter.ISO_LOCAL_DATE_TIME

When iso is set to NONE (the default), formatting is performed according to the specified pattern.

3.3 RequestMapping source code comments​

public @interface RequestMapping {
String[] value() default {};//path, supports antPath; only value can be used on a class, the others below take effect only on methods

RequestMethod[] method() default {};//request methods: POST, GET and others

ViewType viewType() default ViewType.json;//response view type, supports json, jsp, velocity

boolean generateValidator() default false;//when enabled, prints the front-end js validation script according to the back-end validation rules (output via debug logs for developer reference, not automatically delivered to the front end)

String input() default "";//after the validation framework is configured, the redirect path used when validation fails; empty by default, returning a JSON-type error message; if configured, sets the attribute validate_error in the request scope and forwards to the specified path

long uploadSizeMax() default 0L;//maximum limit for the whole upload request, in bytes; 0 means use the global upload configuration in web-conf.xml, -1 means no limit

long uploadPerSizeMax() default 0L;//maximum limit for a single uploaded file, in bytes; 0 means use the global upload configuration in web-conf.xml, -1 means no limit

long bodySizeMax() default 0L;//maximum limit for the request body, in bytes; 0 means use the global request-body configuration in web-conf.xml, -1 means no limit

String exceptionHandler() default "";//exception handler; the system provides three handlers: json, jsp, velocity, which are selected automatically based on ViewType; can be extended if needed, see the register method of HttpExceptionHolder, which can be extended when a listener starts; extension was generally not expected, so SPI configuration was not used

String[] produces() default {};//sets the Content-Type of the response, mimicking Spring MVC's produces; supports Accept header content negotiation, returns 406 Not Acceptable when nothing matches

enum ViewType {
json, jsp, velocity
}
}

Detailed description of produces:

produces declares the media types the current API can produce. The framework performs content negotiation based on the request's Accept header, behaving the same way as Spring MVC:

  • When produces is not configured, the response Content-Type is determined by ViewType or by the return type of @ResponseBody (default behavior unchanged).
  • When produces is configured, the framework parses the Accept header before the method executes and matches it against the produces list. On a match, it sets the response Content-Type and executes the method; on no match, it directly returns 406 Not Acceptable without executing the method.
  • If the Accept header is absent or empty, it is treated as */* and matches any produces.
  • Wildcard matching is supported, e.g. produces = "text/*" matches Accept: text/html, Accept: text/event-stream, etc.
  • Quality factor (q value) ordering is supported, e.g. Accept: application/json;q=0.9, application/xml;q=0.8; types with a higher q value are matched first.
  • The Content-Type set by produces takes precedence over the default Content-Type of ViewType and @ResponseBody.
  • Accept header parsing and sorting results are cached by the raw header string (cache hits avoid re-parsing on every request); for the cache limit and details, see 17. Accept header parsing cache.

Common media type constants can be found in club.dawdler.util.spring.MediaType, such as MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_EVENT_STREAM_VALUE, MediaType.TEXT_HTML_VALUE, etc.

Detailed description of bodySizeMax:

The framework protects the request body size for APIs with a @RequestBody parameter, preventing malicious large bodies from exhausting memory:

  • The global default limit is 10MB and can be configured in web-conf.xml (see 15. Request body size limit).
  • bodySizeMax of @RequestMapping can override the global limit per route; unit is bytes, 0 (the default) means use the global configuration, -1 means no limit.
  • Requests exceeding the limit return 413 (Request Entity Too Large). The framework stops at the Content-Length pre-check or during counted chunked reads, and never reads the full body into memory.
  • Only APIs with a @RequestBody parameter buffer the request body, and buffering is lazy (read only on first access); unmatched routes and non-@RequestBody routes do not pre-read the body, and requests rejected by an auth interceptor's preHandle do not read the body at all.

Detailed description of uploadSizeMax/uploadPerSizeMax:

The framework protects multipart/form-data uploads with a two-level size limit, preventing malicious large files from exhausting disk and memory:

  • uploadPerSizeMax limits the size of a single uploaded file, while uploadSizeMax limits the size of the entire multipart request; both are in bytes.
  • Precedence: a non-zero value declared by @RequestMapping > <upload max-size="..." max-file-size="..."/> in web-conf.xml > default values (10MB per file, 100MB per request).
  • 0 (the default) means use the global configuration, -1 means explicitly unlimited (a warn message is logged, so confirm the business really needs it).
  • Requests exceeding the limit return 413 (Request Entity Too Large) and the controller method is not executed.
  • See 16. Upload file size limit for details.

4. Controller method parameter types​

The supported method parameter types are as follows:

4.1 Primitive types​

longintshortbytedoublefloatbooleanchar
long[]int[]short[]byte[]double[]float[]boolean[]char[]

4.2 Primitive wrapper types​

LongIntegerShortByteDoubleFloatBooleanCharacter
Long[]Integer[]Short[]Byte[]Double[]Float[]Boolean[]Character[]

4.3 Large number objects​

BigDecimalBigDecimal[]

4.4 File upload objects​

UploadFileUploadFile[]

Notes:

Some methods of the UploadFile class

getInputStream() //input stream

getBytes() //byte array

getFileName() //get the file name

getSize() //get the file size

delete() //delete the file; the framework calls this automatically, developers do not need to call it

4.5 Time types​

DateLocalDateTimeLocalDateLocalTimeZonedDateTimeOffsetTimeOffsetDateTime

Note: if a time type uses the @DateTimeFormat annotation, refer to the documentation of @DateTimeFormat.

Without @DateTimeFormat, conversion uses the following default formats:

The default format for Date, LocalDateTime, ZonedDateTime and OffsetDateTime is: yyyy-MM-dd HH:mm:ss

The default format for LocalDate is: yyyy-MM-dd

The default format for LocalTime and OffsetTime is: HH:mm:ss

To change the default formats, configure via startup variables:

dawdler.datetime.format=yyyy-MM-dd HH:mm:ss

dawdler.date.format=yyyy-MM-dd

dawdler.time.format=HH:mm:ss

4.6 Other built-in objects​

HttpServletRequestHttpServletResponseHttpSessionInputStreamReaderPrintWriterLocaleMapViewForwardAsyncContext

Notes:

Map is request.getParameterMap();

InputStream is request.getInputStream();

Reader is request.getReader();

PrintWriter is response.getWriter();

Locale is request.getLocale();

ViewForward provides a very rich API for setting data sets and template paths

AsyncContext is request.startAsync(); injecting it starts async mode, see 5. Asynchronous requests and SSE

4.7 Enum types​

| Enum | | :-: | :-: |

Notes:

Custom enum classes

4.8 Custom objects​

Marked with the @RequestBody annotation

Custom objects are bound by matching field names with request parameter names. Nested objects are supported (a nested field is bound recursively only if a request parameter with the same name as the field exists, e.g. the user field is instantiated only when a user parameter is passed). To defend against infinite recursive instantiation of self-referencing types (such as class Node { Node parent; }) when there are no request parameters, nested binding has a depth limit; exceeding it throws ConvertException:

System propertyDefaultDescription
dawdler.bind.max-nested-depth3Maximum nesting depth for binding custom objects; must be greater than 0
-Ddawdler.bind.max-nested-depth=5

4.9 Some examples​

Example 1: Demonstrates how to use @RequestParam If @RequestParam is configured with value, the parameter is obtained by value; otherwise it is obtained by parameter name, e.g.:

createOrder(@RequestParam("pid") Integer productId, @RequestParam Integer stock, @RequestParam BigDecimal amount) throws Exception {

Here productId is redefined as pid, so the form submission must pass pid.

The stock parameter requires the form submission to pass stock

Example 2: @Controller annotation

@Controller
@RequestMapping(value = "/order")
public class OrderController {

@RequestMapping(value = "/createOrder.do", viewType = ViewType.json)
public void createOrder(@RequestParam Integer productId, @RequestParam Integer stock,
@RequestParam BigDecimal amount, ViewForward viewForward) throws Exception {
Map<String, Object> result = new HashMap<>();
result.put("success", true);
viewForward.setData(result);
}


@RequestMapping(value = "/order.html", viewType = ViewType.velocity)
public void order(ViewForward viewForward) throws Exception {
viewForward.setTemplatePath("order/add.html");//inject ViewForward to set templatePath
}

}

Example 3: @ResponseBody annotation

@Controller
//@RequestMapping(value = "/order") can be commented out, so that /order is not needed
public class OrderController {

@RequestMapping(value = "/createOrder.do")
@ResponseBody
public Map createOrder(@RequestParam Integer productId, @RequestParam Integer stock,
@RequestParam BigDecimal amount, ViewForward viewForward) throws Exception {
Map<String, Object> result = new HashMap<>();
result.put("success", true);
return result;
}

}

Example 4: produces content negotiation

Example 4.1: Implementing SSE (Server-Sent Events), always returning text/event-stream:

@Controller
@RequestMapping(value = "/sse")
public class SSEController {

@RequestMapping(value = "/push", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public String push() throws Exception {
return "data: hello\n\n";
}

}

Note: produces = "text/event-stream" overrides the default application/json of @ResponseBody, and the response Content-Type is text/event-stream. If the client's Accept header does not contain text/event-stream (and is not /), 406 is returned.

This example writes the stream synchronously and occupies a container worker thread, which suits short push scenarios; for long-lived connections use the asynchronous approach, see 5. Asynchronous requests and SSE.

Example 4.2: Multi-type negotiation, returning JSON or XML based on the Accept header:

@RequestMapping(value = "/data", produces = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE
})
@ResponseBody
public Object data() {
return result;
}

Note: if the client sends Accept: application/json, the response Content-Type is application/json; if Accept: application/xml, it is application/xml; when the Accept header matches none of the produces list, 406 is returned.

5. Asynchronous requests and SSE​

The framework supports Servlet asynchronous requests, suitable for scenarios that need to occupy a connection for a long time, such as SSE (Server-Sent Events) push, long polling, and slow output of large files; request processing does not occupy container worker threads.

ViewFilter, SessionFilter, MetricsFilter and JwtFilter are all registered with asyncSupported=true, so async can be used without extra configuration.

A Controller method can simply return an SseEmitter; the framework automatically starts the async context and keeps the connection open, and business code can call send from any thread to push events.

import club.dawdler.clientplug.web.sse.SseEmitter;

@Controller
@RequestMapping(value = "/sse")
public class SSEController {

// Push 10 messages, one per second, and finish after all are pushed
@RequestMapping(value = "/stream", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter stream() {
SseEmitter emitter = new SseEmitter();//never times out by default; new SseEmitter(60000L) specifies a timeout in milliseconds
executor.execute(() -> {
try {
for (int i = 0; i < 10; i++) {
emitter.send("message", "data-" + i);//event with an event name; the client receives it via addEventListener("message", ...)
Thread.sleep(1000);
}
} catch (Exception e) {
emitter.completeWithError(e);
return;
}
emitter.complete();
});
return emitter;
}

// Send a json object with a custom event id
@RequestMapping(value = "/order", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter order() {
SseEmitter emitter = new SseEmitter();
Map<String, Object> order = new HashMap<>();
order.put("orderId", 10001L);
order.put("amount", new BigDecimal("99.9"));
emitter.send("order", "10001", order);//non-String types are serialized to json automatically; id is used for resuming via Last-Event-ID when the client reconnects after a disconnect
emitter.complete();
return emitter;
}

}

Common SseEmitter APIs:

void send(Object data) //push an event without an event name; data is output verbatim when it is a String, other types are serialized to json
void send(String eventName, Object data) //push an event with an event name
void send(String eventName, String id, Object data) //push an event with an event name and id; id is used for resumption when the client reconnects after a disconnect
void complete() //complete normally and close the connection
void completeWithError(Throwable throwable) //complete with an error and close the connection
void onCompletion(Runnable onCompletion) //register a callback after the connection ends (normal completion/timeout/error); triggered only once
void onTimeout(Runnable onTimeout) //register a timeout callback
void onError(Consumer<Throwable> onError) //register an error callback
boolean isCompleted() //whether the connection has ended

Notes:

  1. Multi-line data is output as multiple data: lines, one per line, conforming to the SSE protocol specification.
  2. When callbacks run, the context ClassLoader of the calling thread (i.e. at initialize time) is automatically restored, so there is no need to worry about dawdler plugin class loader issues.
  3. SseEmitter ends the response via AsyncContext.complete() and does not support AsyncContext.dispatch() forwarding.

5.2 Injecting AsyncContext directly​

Declare AsyncContext directly as a Controller method parameter; injecting it starts async mode, suitable for scenarios that need full control over the async lifecycle:

@RequestMapping(value = "/manual", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public void manual(AsyncContext ctx, HttpServletResponse response) throws IOException {
ctx.setTimeout(0);//0 means never time out; note that the container's default timeout (e.g. 30 seconds for tomcat) will interrupt long-lived connections
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
for (int i = 0; i < 10; i++) {
out.write("data: " + i + "\n\n");
out.flush();
}
ctx.complete();
}

Note: injecting AsyncContext calls request.startAsync(); if the method does not complete it itself, the container interrupts the connection on timeout.

5.3 Behavior of asynchronous requests​

  1. After the controller method returns, if async has started (isAsyncStarted), the framework no longer performs view rendering.
  2. HandlerInterceptor's afterCompletion is deferred until the async request ends (connection closed or timed out), consistent with Spring MVC's async interceptor semantics; preHandle and postHandle are still triggered before and after the controller method executes. afterCompletion is guaranteed to trigger exactly once (when container callbacks race), and during its execution the class loader of the controller is automatically restored as the context ClassLoader; it is likewise deferred when an exception is thrown after startAsync within the method, and the exception is passed to the interceptor after unwrapping InvocationTargetException.
  3. The ASYNC-type second dispatch caused by AsyncContext.dispatch() is short-circuited by the framework, so the controller method is not executed again.
  4. The synchronous request path is completely unaffected.

6. HandlerInterceptor interceptor​

Interceptors work the same as in Spring MVC. Implement the HandlerInterceptor interface; if there are multiple interceptors, the @Order annotation is supported for ascending sorting. Interceptors run before and after the API request is intercepted, and after the template is rendered.

Example:


@Order(1)//there can be multiple interceptors, sorting is supported and is ascending
public class UserWebInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(Object controller, ViewForward viewForward, RequestMapping requestMapping)
throws Exception {
String uri = viewForward.getRequest().getRequestURI();
System.out.println(this.getClass().getSimpleName() + " preHandle " + uri);
return true;
}

@Override
public void postHandle(Object controller, ViewForward viewForward, RequestMapping requestMapping, Throwable ex)
throws Exception {
System.out.println(this.getClass().getSimpleName() + " postHandle ");
}

@Override
public void afterCompletion(Object controller, ViewForward viewForward, RequestMapping requestMapping,
Throwable ex) {
System.out.println(this.getClass().getSimpleName() + " afterCompletion ");
}

}

7. WebContextListener listener​

Listeners work exactly the same as the ServletContextListener provided by the Servlet API. If there are multiple listeners, the @Order annotation is supported for ascending sorting. Currently only container startup and shutdown listeners are provided (HttpSessionListener, ServletRequestListener and HttpSessionActivationListener are not provided; use the ones provided by the Servlet API if needed).

Example:

package com.anywide.yyg.user.web.listener;

import jakarta.servlet.ServletContext;

import club.dawdler.clientplug.web.listener.WebContextListener;
import club.dawdler.core.annotation.Order;

@Order(2)//there can be multiple listeners, sorting is supported and is ascending
public class UserWebContextListener implements WebContextListener {

@Override
public void contextInitialized(ServletContext servletContext) {
System.out.println(this.getClass().getSimpleName() + " contextInitialized " + servletContext.getRealPath(""));
}

@Override
public void contextDestroyed(ServletContext servletContext) {
System.out.println(this.getClass().getSimpleName() + " contextDestroyed " + servletContext.getRealPath(""));
}

}

8. Introduction to ViewForward​

ViewForward is a class for passing request and response, setting template paths, specifying response statuses and so on.

ViewForward can be injected into the method parameter list.

Common methods:

String getUriShort() //get the request uri

void setInvokeException(Throwable invokeException) //set an execution exception; once set, an error log is recorded; if the response view is jsp or velocity, the http status code 500 is responded via response, specifically: response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!");

//if the response view is json, http status code 500 is responded directly with body {"msg","Internal Server Error!"}

public void putData(String key, Object value); //put data, e.g. request.setAttribute("name","jackson"); if it is a json view, outputs {"name", "jackson"}; if it is a velocity view, context.put("name", "jackson") is set in the context, so the template can access it via $name.

public void setAddRequestAttribute(boolean addRequestAttribute); //false by default; when set, automatically adds attributes from the request scope to the context, equivalent to calling putData(String key, Object value);

public void setData(Map<String, Object> data); //directly overwrites the context with the parameter data.

public String getHeader(String headerName); //get a request Header, equivalent to request.getHeader(String name);

public void setTemplatePath(String templatePath); //set the template path, for velocity or jsp; the jsp root path defaults to WEB-INF/template/ (velocity templates are loaded from the classpath, see the dawdler-client-plug-velocity module).

The param* family of methods is as follows:

Source example 1:

public short paramShort(String paramName) {
try {
return Short.parseShort(getRequest().getParameter(paramName));
} catch (Exception e) {
return 0;
}
}

Source example 2:

public long paramLong(String paramName, long value) {
try {
return Long.parseLong(getRequest().getParameter(paramName));
} catch (Exception e) {
return value;
}
}

9. RemoteClassLoaderFire class loading notifier​

To perform some operations when a class is loaded, implement the RemoteClassLoaderFire interface and extend it via SPI; the @Order annotation is supported for ascending sorting. See WebComponentClassLoaderFire; it is used to implement automatic injection of Services into Controllers, WebContextListeners and HandlerInterceptors. (Regular developers generally do not need to extend it.)

10. DisplayPlug view plugin extension​

dawdler provides three built-in view plugins: JsonDisplayPlug, JspDisplayPlug and VelocityDisplayPlug. If other needs arise, e.g. freemarker support, implement the DisplayPlug interface and extend via SPI. Refer to the three built-in plugins. (Regular developers generally do not need to extend it.)

Note: if the method is marked with @ResponseBody and the return type is a primitive type, a String or BigDecimal, the output is directly of type text/html;charset=UTF-8; other types are converted to json of type application/json;charset=UTF-8.

If @RequestMapping configures produces, the response Content-Type follows the produces negotiation result, which takes precedence over the default behavior of @ResponseBody described above and the default setting of ViewType.

11. Component scan package configuration​

web-conf.xml is the core configuration file on the web side. It covers component scanning, data source definition configuration, data source definition for specified target packages, read-write splitting configuration, and health check.

package-path configures the package scan paths in the current web environment (package paths in lib or classes deployed in the web container, antpath is supported).

Example:

<scanner>
<package-paths>
<package-path>com.dawdler.order.controller</package-path>
<package-path>com.dawdler.**.service.impl</package-path>
</package-paths>
</scanner>

request-body configures the global request body size limit (in bytes); when not configured, it defaults to 10MB:

<request-body max-body-size="10485760"/>

max-body-size is the global limit, in bytes. bodySizeMax of @RequestMapping can override this value per route; -1 means no limit. See the detailed description of bodySizeMax in 3.3 RequestMapping source code comments.

upload configures the global upload file size limit (in bytes); when not configured, the default is 10MB per file and 100MB per request:

<upload max-file-size="10485760" max-size="104857600"/>

max-file-size is the global limit for a single uploaded file, in bytes; -1 means no limit.

max-size is the global limit for the entire multipart request, in bytes; -1 means no limit.

uploadPerSizeMax/uploadSizeMax of @RequestMapping can override these two values per route; see 16. Upload file size limit.

12. How to use AOP​

dawdler's AOP is based on the AspectJ weaver: bytecode weaving is done when dawdler's custom class loader loads a class (before defineClass), i.e. load-time weaving, but the weave points are embedded in dawdler's class loader and do not depend on -javaagent. Unlike Spring's runtime proxy approach with cglib/jdk dynamic proxies, woven calls are direct code with no proxy forwarding overhead.

Applicable scope: AOP supports weaving into four types on the web side: Controller, HandlerInterceptor, WebContextListener and API interfaces (Service interfaces).

Example (intercepting a Controller):

Note: both files below need to be created on the web side

  1. Create META-INF\aop.xml
<aspectj>
<aspects>
<aspect name="com.anywide.yyg.user.controller.UserControllerAspect"/>
</aspects>
</aspectj>
  1. Create com.anywide.yyg.user.controller.UserControllerAspect
@Aspect
public class UserControllerAspect {

@Pointcut("execution(* com.anywide.yyg.user.controller..UserController.list(..))")
public void list() {
}

@Around("list()")
public Object logAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println(pjp.getSignature().getName() + ":" + pjp.getTarget());
Object o = null;
try {
o = pjp.proceed();
} catch (Throwable t) {
throw t;
}
Object[] args = pjp.getArgs();
System.out.println(o+":\t" + args);
return o;
}

}

Or intercept directly via Around without a Pointcut

@Aspect
public class UserControllerAspect {

@Around("execution(* com.anywide.yyg.user.controller..UserController.list(..))")
public Object logAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println(pjp.getSignature().getName() + ":" + pjp.getTarget());
Object o = null;
try {
o = pjp.proceed();
} catch (Throwable t) {
throw t;
}
Object[] args = pjp.getArgs();
System.out.println(o+":\t" + args);
return o;
}

}

For an example of intercepting API interfaces (Service interfaces), see the implementation of the distributed transaction interception annotation, which intercepts the DistributedTransaction annotation defined on the API.

13. Health check​

Health check means that at startup the system checks whether each component is working properly, providing this service for k8s liveness and readiness.

If (Basic Authentication) authentication is configured, add the Authorization header information via a header.

The configuration is in the health-check node of web-conf.xml, example:

<health-check check="on" uri="/health" username="jackson" password="jackson.song">
<config check="on"/>
<dataSource check="on" />
<rabbit check="on" />
<jedis check="on" />
<elasticSearch check="on" />
</health-check>

check="on" enables health check, off disables it. When disabled, the http/https service is not started.

username="jackson" is the username; if this attribute is not filled in, the authentication module is not enabled.

password="jackson.song" is the password; if this attribute is not filled in, the authentication module is not enabled.

uri="/health" is the uri of the health check, /health by default.

The following component nodes support health check; if check is set to off or the node is omitted, no health check is triggered.

elasticSearch es check

jedis redis check

rabbit rabbitmq check

dataSource data source check

config configuration center check

Verify with wget:

wget http://localhost:8082/health

Response:

{"data":{"status":"UP","dataSource":{"user_writeDataSource":{"status":"UP"},"user_readDataSource":{"status":"UP"},"status":"UP"},"config":{"consul":{"info":"srchen-dc1-1.20.1","status":"UP"},"status":"UP"}},"name":"","status":"UP"}

The /health endpoint always returns 200 (to stay compatible with existing monitoring); for k8s probes use the /live (liveness) and /ready (readiness) endpoints instead: /live returns 200 as long as the process is alive, /ready returns 200 only when the readiness check passes and 503 while being drained during shutdown; both share Basic Authentication with /health, and the uris can be overridden via dawdler.web.health.liveUri/dawdler.web.health.readyUri (defaults /live//ready). See Cloud-native k8s integration.

14. JMX monitoring system properties​

dawdler-client-plug-web has built-in JMX MBeans providing HTTP request metrics monitoring, with zero external dependencies (based on native java.lang.management JMX).

Property nameDefaultDescription
dawdler.web.metrics.enabledfalseSwitch for web metrics and JMX monitoring
dawdler.web.metrics.maxUriCardinality1000Cardinality limit for counters counted per URI; beyond this, new URIs are no longer counted separately (to prevent high-cardinality URIs from exhausting memory), while total statistics are unaffected
dawdler.web.metrics.latency.window1024Window length of the latency ring histogram, i.e. the most recent N requests included in the statistics; the value is normalized to a power of 2 within [16, 1048576]; one per global and one per URI
-Ddawdler.web.metrics.enabled=true

When enabled, MBeans are registered and metrics are collected; when disabled, all instrumentation methods are no-ops (ENABLED is static final, and JIT constant folding eliminates the hot-path overhead), and no MBeans are registered. MBeans are registered under the club.dawdler.clientplug.web domain:

  • WebStatus: HTTP request metrics (total requests, 2xx/3xx/4xx/5xx distribution, exception count, average/P50/P95/P99 processing latency within the most recent window, cumulative latency sample count, uptime, URI count and a summary grouped by URI)
  • JvmMonitor: reuses the JVM runtime metrics of dawdler-core

Latency statistics use a ring histogram: the window rolls with requests and reflects only recent traffic (for cumulative request volume, see the total request count); quantiles are the lower bounds of the power-of-2 bucket they fall in, so the true value lies within [quantile, 2 × quantile) (relative error on the 1ms scale is less than 0.1%); the global (WebStatus) and each URI each maintain an independent window.

15. Request body size limit​

The framework protects the request body size for APIs with a @RequestBody parameter, preventing unauthenticated clients from POSTing oversized bodies to arbitrary paths and exhausting heap memory (a zero-cost DoS).

Precedence: a non-zero bodySizeMax of @RequestMapping > <request-body max-body-size="..."/> in web-conf.xml > default 10MB.

Configuration itemLocationDefaultDescription
bodySizeMax@RequestMapping0Overrides the global limit per route, in bytes; 0 means use the global configuration, -1 means no limit
max-body-sizerequest-body element of web-conf.xml10485760 (10MB)Global limit, in bytes
@RequestMapping(value = "/uploadReport.do", method = RequestMethod.POST)
@ResponseBody
public Report uploadReport(@RequestBody ReportDto dto) {
...
}

Notes:

  1. Requests exceeding the limit return 413 (Request Entity Too Large) and the controller method is not executed.
  2. The framework first pre-checks against Content-Length (not a single byte is read once exceeded); without Content-Length it reads in counted chunks and stops immediately at the point of exceeding the limit, never allocating the full body.
  3. Only APIs with a @RequestBody parameter wrap the request to buffer the body, and buffering is lazy (read only on first access); unmatched routes (404/405) and non-@RequestBody routes do not pre-read the body, so downstream filters/servlets receive the unconsumed raw stream.
  4. Requests rejected by an auth interceptor's preHandle returning false do not read the body at all.
  5. File uploads (multipart/form-data) do not use this limit; use the uploadSizeMax/uploadPerSizeMax configuration instead.

16. Upload file size limit​

The framework protects multipart/form-data uploads with a two-level size limit, preventing unauthenticated clients from POSTing oversized files to arbitrary upload endpoints and filling the disk (commons-fileupload2 writes parts over the threshold to disk as temporary files).

Precedence: non-zero values declared by @RequestMapping > <upload .../> in web-conf.xml > default values.

Configuration itemLocationDefaultDescription
uploadPerSizeMax@RequestMapping0Limit for a single uploaded file, in bytes; 0 means use the global configuration, -1 means no limit
uploadSizeMax@RequestMapping0Limit for the entire multipart request, in bytes; 0 means use the global configuration, -1 means no limit
max-file-sizeupload element of web-conf.xml10485760 (10MB)Global limit for a single uploaded file, in bytes; -1 means no limit
max-sizeupload element of web-conf.xml104857600 (100MB)Global limit for the entire multipart request, in bytes; -1 means no limit
// Override per route: limit a single file to 5MB and the whole request to 20MB
@RequestMapping(value = "/uploadAvatar.do", method = RequestMethod.POST,
uploadPerSizeMax = 5L * 1024 * 1024, uploadSizeMax = 20L * 1024 * 1024)
@ResponseBody
public Map<String, Object> uploadAvatar(UploadFile avatar) {
...
}

Notes:

  1. The default (with no configuration at all) is already protected: requests with a single file over 10MB or a whole request over 100MB return 413 (Request Entity Too Large) and the controller method is not executed.
  2. "No limit" must be declared explicitly (pass -1 in the annotation or global configuration); in that case, parsing the request at startup prints a warn log for auditing; 0 no longer means no limit.
  3. The single-file limit is checked before the file content is written to the temporary directory, and the whole-request limit is checked while reading the request stream; on exceeding the limit it stops immediately and never writes the complete file to disk.
  4. After a request is rejected or processing completes, the framework automatically deletes any temporary files produced (cleaned up uniformly on release; cleanup failures are logged as errors).
  5. The request body (a non-multipart @RequestBody) does not use this limit; use the bodySizeMax configuration instead.

17. Accept header parsing cache​

After @RequestMapping declares produces, the framework parses and sorts the MimeTypes of each request's Accept header (descending q value, wildcards later) before matching content types. The Accept header from the same client is highly repetitive, so parsing and sorting results are cached by the raw header string; cache hits avoid re-parsing on every request.

Property nameDefaultDescription
dawdler.web.accept.cache.maxSize256Entry limit for the Accept header parsing result cache; beyond this, new headers are no longer cached (keyed by the raw header string, preventing forged high-cardinality headers from exhausting memory); already cached entries are unaffected
-Ddawdler.web.accept.cache.maxSize=512

Notes:

  1. Routes that do not declare produces do not parse the Accept header and produce no cache entries.
  2. The cache key is the raw Accept header string; headers that differ (including case and whitespace differences) are treated as distinct entries.
  3. The cache applies only to parsing and sorting results; matching and setContentType are still performed per request.