8.2.1 GSP Basics - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.4
8.2.1 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>
<%= %>
syntax to output values:<html> <body> <%="Hello GSP!" %> </body> </html>
<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.
8.2.1.1 Variables and Scopes
Within the<% %>
brackets you can declare variables:<% now = new Date() %>
<%=now%>
application
- The javax.servlet.ServletContext instanceapplicationContext
The Spring ApplicationContext instanceflash
- The flash objectgrailsApplication
- The GrailsApplication instanceout
- The response writer for writing to the output streamparams
- The params object for retrieving request parametersrequest
- The HttpServletRequest instanceresponse
- The HttpServletResponse instancesession
- The HttpSession instancewebRequest
- The GrailsWebRequest instance
8.2.1.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>
<html> <body> <% if (params.hello == 'true')%> <%="Hello!"%> <% else %> <%="Goodbye!"%> </body> </html>
8.2.1.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.*" %>
<%@ page contentType="application/json" %>
8.2.1.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>
${..}
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.