(Quick Reference)

2 GSP Basics

Version: 5.0.0.RC1

2 GSP Basics

In the next view sections we’ll go through the basics of GSP and what is available to you. First off let’s cover some basic syntax that users of JSP and ASP should be familiar with.

GSP supports the usage of <% %> scriptlet blocks to embed Groovy code (again this is discouraged):

<html>
   <body>
     <% out << "Hello GSP!" %>
   </body>
</html>

You can also use the <%= %> syntax to output values:

<html>
   <body>
     <%="Hello GSP!" %>
   </body>
</html>

GSP also supports JSP-style server-side comments (which are not rendered in the HTML response) as the following example demonstrates:

<html>
   <body>
     <%-- This is my comment --%>
     <%="Hello GSP!" %>
   </body>
</html>
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks.

2.1 Variables and Scopes

Within the <% %> brackets you can declare variables:

<% now = new Date() %>

and then access those variables later in the page:

<%=now%>

Within the scope of a GSP there are a number of pre-defined variables, including:

2.2 Logic and Iteration

Using the <% %> syntax you can embed loops and so on using this syntax:

<html>
   <body>
      <% [1,2,3,4].each { num -> %>
         <p><%="Hello ${num}!" %></p>
      <%}%>
   </body>
</html>

As well as logical branching:

<html>
   <body>
      <% if (params.hello == 'true')%>
      <%="Hello!"%>
      <% else %>
      <%="Goodbye!"%>
   </body>
</html>

2.3 Page Directives

GSP also supports a few JSP-style page directives.

The import directive lets you import classes into the page. However, it is rarely needed due to Groovy’s default imports and GSP Tags:

<%@ page import="java.awt.*" %>

GSP also supports the contentType directive:

<%@ page contentType="application/json" %>

The contentType directive allows using GSP to render other formats.

2.4 Expressions

In GSP the <%= %> syntax introduced earlier is rarely used due to the support for GSP expressions. A GSP expression is similar to a JSP EL expression or a Groovy GString and takes the form ${expr}:

<html>
  <body>
    Hello ${params.name}
  </body>
</html>

However, unlike JSP EL you can have any Groovy expression within the ${..} block.

Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks.