All Products
Search
Document Center

Function Compute:Java handlers

Last Updated:Jun 04, 2026

A Java handler processes incoming events in your Function Compute (FC) function. FC routes each invocation to the handler method specified in your function configuration.

Note

To invoke functions via HTTP triggers or custom domain names, Use an HTTP trigger to invoke a function.

Handler format

Set the Handler parameter in the Function Compute console in this 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 and class names are customizable but must match the Handler value in your function configuration. Create an event function.

Handler interfaces

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

Interface Input/Output Use when
StreamRequestHandler InputStream / OutputStream Processing raw byte streams or data that doesn't map to a POJO
PojoRequestHandler<I, O> Custom POJO types Working 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. 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. Context.

PojoRequestHandler

PojoRequestHandler<I, O> uses generic types for input and output. Both must be POJOs with JSON serialization support.

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

Demonstrates handling HTTP trigger requests and returning responses.

Prerequisites

Before you begin, ensure that you have:

Sample code

The handler uses PojoRequestHandler with HTTPTriggerEvent and HTTPTriggerResponse as input/output types. For 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 target function.

  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 trigger's public endpoint:

       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 Authentication Method is No Authentication, invoke the function directly with Postman or curl.

  • If Authentication Method is Signature Authentication or JWT Authentication, authenticate accordingly. Authentication.

Common errors

This handler expects HTTP trigger input. Invoking it via the Test Function button with a plain string (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

Sample programs for different handler types: