Using the HttpServlet class to set a handler
You can set a handler by overriding the selected methods of the HttpServlet class.
Cloud Functions will automatically redirect each HTTP
request to your handler, depending on the HTTP
method that this request was initiated with.For example, a GET
request is redirected to your handler's doGet
method and a POST
request to the doPost
method. For a successful redirect, the corresponding handler methods must exist, otherwise the function returns the HTTP method XXX is not supported by this URL
message with code 405
.
Unsupported methods
When using this model, please note that some methods of the HttpServletRequest and HttpServletResponse classes are not supported by Cloud Functions.
HttpServletRequest
:
- getAuthType
- getCookies
- upgrade
- authenticate
- login
- logout
- getContextPath
- getServletPath
- getPathTranslated
- getRealPath
- getRemotePort
- getLocalAddr
- getLocalPort
- getServerPort
- isUserInRole
- getUserPrincipal
- getRequestedSessionId
- getSession
- changeSessionId
- isRequestedSessionIdValid
- isRequestedSessionIdFromCookie
- isRequestedSessionIdFromURL
- isRequestedSessionIdFromUrl
HttpServletResponse
:
- encodeURL
- encodeRedirectURL
- encodeUrl
- encodeRedirectUrl
Example of modeling various function behaviors when invoked using different HTTP methods
Warning
Don't use the integration=raw
parameter to call this function. If you do, the function won't get any data about the original request's methods, headers, and parameters.
The Handler.java
file:
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Handler extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// by setting the Content-Type to text/html, we let the browser render the HTML code
response.setContentType("text/html");
// displayed in bold when the function is invoked from the browser
response.getOutputStream().print("<b>Hello, world. In bold.</b>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
var name = request.getParameter("name");
response.getWriter().println("Hello, " + name);
// the printWriter class returned by the getWriter method, make sure it's closed
response.getWriter().close();
}
}
Sample requests:
The GET
method:
<b>Hello, world. In bold.</b>
Note
When executing a GET
request, this string is displayed in bold and the tags disappear in the browser, because Content-Type: text/html
was specified in the handler code.
The POST
method, the name=Anonymous
request parameter:
Hello, Anonymous
The PUT
method:
HTTP method PUT is not supported by this URL