sessionHiddenInputElement method

String sessionHiddenInputElement()

Returns HTML for a hidden form input for the session parameter.

If there is no session (i.e. session is null) or cookies are being used to preserve the session, returns the empty string.

This method can be used to maintain the session across form submissions when URL rewriting is being used (i.e. cookies are not being used).

There are two ways to preserve the session when using forms. Applications must use one of these methods, if it needs to preserve sessions and cookies might not be available.

Method 1: Rewrite the method URL, to preserve the session with a query parameter.

<form method="POST" action="${HEsc.attr(req.rewriteUrl("~/form/processing/url"))}">
  ...
</form>

Method 2: Add a hidden input, to preserve the session with a POST parameter.

<form method="POST" action="${HEsc.rewriteUrl("~/form/processing/url", includeSession: false)}">
  ${req.sessionHiddenInputElement()}
  ...
</form>

The first method is consistent with how links are outputted when not using forms, but it is inconsistent to use both query parameters with a POST request. The second method does not mix both query and POST parameters. Both methods work on most browsers with the "POST" method.

The second method must be used when the method is "GET". This is because the Chrome browser drops the query parameters found in the "action" attribute when the method is "GET".

The second method is recommended, because the pattern will be consistent between POST and GET methods, even though it is slightly different from when a URL is used outside a form's method attribute.

If cookies are being used to preserve the session, either method will produce the same HTML.

Note: this method is on the request object, even though it ultimately affects the HTTP response. This is because the request object carries the context for the request and the response. The session is a part of that context.

Implementation

String sessionHiddenInputElement() {
  final _server = server;
  final _session = session;

  if (_session != null && !_sessionUsingCookies) {
    // Require hidden POST form parameter to preserve session
    final name = HEsc.attr(_server.sessionParamName);
    final value = HEsc.attr(_session.id);
    return '<input type="hidden" name="$name" value="$value"/>';
  } else {
    return ''; // hidden POST form parameter not required
  }
}