All Products
Search
Document Center

Function Compute:Java handlers

Last Updated:Feb 28, 2026

A handler processes incoming requests in your Function Compute (FC) function. When a function is invoked, FC routes the request to the handler specified in your function configuration.

Note

To handle HTTP requests through HTTP triggers or custom domain names, see Use an HTTP trigger to invoke a function.

Handler format

Configure the Handler parameter in the Function Compute console using the following format:

[Package name].[Class name]::[Method name]

For example, if your package is example, your class is HelloFC, and your method is handleRequest:

example.HelloFC::handleRequest

The package name and class name can be customized, but must match the Handler value in function configuration. See Create an event function.

Handler interfaces

Java handlers must implement an interface from the fc-java-core library:

InterfaceInput/OutputUse when
StreamRequestHandlerInputStream / OutputStreamProcessing raw byte streams or data that doesn't map to a POJO
PojoRequestHandler<I, O>Custom POJO typesWorking with structured JSON data that maps to Java objects

Maven dependency

Add fc-java-core to your pom.xml:

<dependency>
    <groupId>com.aliyun.fc.runtime</groupId>
    <artifactId>fc-java-core</artifactId>
    <version>1.4.1</version>
</dependency>

Check the Maven repository for the latest version.

Before creating a function, package your code and the fc-java-core dependency into a JAR file. See Compile and deploy code packages.

StreamRequestHandler

StreamRequestHandler reads input from an InputStream and writes output to an OutputStream.

package example;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class HelloFC implements StreamRequestHandler {

    @Override
    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        outputStream.write(new String("hello world").getBytes());
    }
}
  • inputStream: Contains the event data passed when the function is invoked.

  • outputStream: Receives the function return data.

  • context: Provides runtime information such as the request ID and temporary AccessKey pair. Type: com.aliyun.fc.runtime.Context. See Context.

PojoRequestHandler

PojoRequestHandler<I, O> uses generic types for input and output. Both types must be Plain Old Java Objects (POJOs) that support JSON serialization.

Handler class

// HelloFC.java
package example;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;

public class HelloFC implements PojoRequestHandler<SimpleRequest, SimpleResponse> {

    @Override
    public SimpleResponse handleRequest(SimpleRequest request, Context context) {
        String message = "Hello, " + request.getFirstName() + " " + request.getLastName();
        return new SimpleResponse(message);
    }
}

Request and response classes

// SimpleRequest.java
package example;

public class SimpleRequest {
    String firstName;
    String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public SimpleRequest() {}
    public SimpleRequest(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
// SimpleResponse.java
package example;

public class SimpleResponse {
    String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SimpleResponse() {}
    public SimpleResponse(String message) {
        this.message = message;
    }
}

Sample input event

{
  "firstName": "FC",
  "lastName": "aliyun"
}

Example: Invoke a function with an HTTP trigger

This example demonstrates a handler that processes HTTP trigger requests and returns HTTP responses.

Prerequisites

Before you begin, ensure that you have:

Sample code

The handler implements PojoRequestHandler with HTTPTriggerEvent and HTTPTriggerResponse as the input and output types. For HTTP trigger request and response formats, see Use an HTTP trigger to invoke a function.

App.java - Entry class

App.java

package example;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;

public class App implements PojoRequestHandler<HTTPTriggerEvent, HTTPTriggerResponse> {

    @Override
    public HTTPTriggerResponse handleRequest(HTTPTriggerEvent request, Context context) {
        context.getLogger().info("Receive HTTP Trigger request: " + request.toString());
        String requestBody = request.getBody();
        if (request.isIsBase64Encoded()) {
            requestBody = new String(java.util.Base64.getDecoder().decode(request.getBody()), StandardCharsets.UTF_8);
        }
        String message = "HTTP Trigger request body: " + requestBody;
        context.getLogger().info(message);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "text/plain");
        return HTTPTriggerResponse.builder().withStatusCode(200).withHeaders(headers).withBody(request.getBody())
                .withIsBase64Encoded(request.isIsBase64Encoded()).build();
    }
}

HTTPTriggerEvent.java - Request format

HTTPTriggerEvent.java

package example;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Map;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(setterPrefix = "with")
public class HTTPTriggerEvent {
    private String version;
    private String rawPath;
    private Map<String, String> headers;
    private Map<String, String> queryParameters;
    private RequestContext requestContext;

    @JsonProperty("isBase64Encoded")
    private boolean IsBase64Encoded;
    private String body;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder(setterPrefix = "with")
    public static class RequestContext {
        private String accountId;
        private String domainName;
        private String domainPrefix;
        private HttpInfo http;
        private String requestId;
        private String time;
        private String timeEpoch;

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        @Builder(setterPrefix = "with")
        public static class HttpInfo {
            private String method;
            private String path;
            private String protocol;
            private String sourceIp;
            private String userAgent;
        }
    }

}

HTTPTriggerResponse.java - Response format

HTTPTriggerResponse.java

package example;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(setterPrefix = "with")
public class HTTPTriggerResponse {
    private int statusCode;
    private Map<String, String> headers;

    @JsonProperty("isBase64Encoded")
    private boolean IsBase64Encoded;
    private String body;
}

Additional Maven dependencies

Add jackson and lombok alongside fc-java-core:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.16.1</version>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.30</version>
</dependency>

Invoke the function

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function to manage.

  3. Click the Triggers tab to obtain the public endpoint of the HTTP trigger.

  4. Run the following curl command: Replace the URL with your HTTP trigger's public endpoint. Expected response:

       curl -i "https://dev-jav-test-fc-luiqas****.cn-shanghai.fcapp.run" -d 'hello fc3.0'
       HTTP/1.1 200 OK
       Content-Disposition: attachment
       Content-Length: 11
       Content-Type: application/json
       X-Fc-Request-Id: 1-652503f2-afbfd2b1dc4dd0fcb0230959
       Date: Tue, 10 Oct 2023 07:57:38 GMT
    
       hello fc3.0%
Important
  • If the Authentication Method of the HTTP trigger is set to No Authentication, use Postman or curl to invoke the function directly.

  • If the Authentication Method is set to Signature Authentication or JWT Authentication, use the corresponding authentication method. See Authentication.

Common errors

This handler is designed for HTTP trigger invocations. Invoking it through the Test Function button in the console with a plain string input (such as "Hello, FC!") causes a deserialization error:

{
    "errorType": "com.fasterxml.jackson.databind.exc.MismatchedInputException",
    "errorMessage": "Cannot construct instance of `example.HTTPTriggerEvent` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('Hello, FC!')\n at [Source: (byte[])\"\"Hello, FC!\"\"; line: 1, column: 1]",
    "stackTrace": [
        "com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)",
        "com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1588)",
        "..."
    ]
}

To test this handler, invoke it through the HTTP trigger endpoint or provide a JSON payload that matches the HTTPTriggerEvent structure.

Sample programs

FC provides sample programs that demonstrate different handler types: