Introduction to Groovy Server Pages (GSP)

Introduction

This article is about Groovy Server Pages basic concepts. Groovy Server Pages (GSP) is a view technology which can be used for designing web application using Grails Framework. Developing GSP are very much similar to that of designing web pages with Active Server Pages (ASP) and Java Server Pages (JSP) but coding is very much simpler and easier than both of them.
Users are provided with facility of having static, dynamic as well as mix of both contents at a time in a single application.

also read:

The output can be dynamically rendered to different forms like : HTML, XML, text and any other format based on Web client request object.If you are beginner in learning groovy, please read Introduction to Groovy – Scripting Language.

Advantages of using GSP using Grails

  1. A GSP uses Groovy GString for evaluation of expression generally using ${….} but whereas in JSP EL expressions are used for the same purpose but they are restricted only to object navigation to overcome this disadvantage JSTL functions can to be written for creating static helper methods, registering them through a taglib descriptor, adding a taglib declaration and finally implementing them using the function.
  2. A developer has been provided with Logical and Iterative tags in GSP with safe navigation operator and Elvis operator which can be implemented easily to fetch the needed results according to their requirement. For example these operators can be implemented in this manner:
    • Safe navigation operator :
      ${book.pages?.no()}
  3. Elvis operator : ${totalpages ?: 100}
  4. A GSPhas ability for invoking methods through Grails dynamic tags which makes it easier to produce well-formed markup:<!– With a regular tag
    <!-- With a regular tag -->
              <a href="<g:createLink action="list" />">Click here</a>
              <!-- As a method call -->
               <a href="${createLink(action:'list')}">Click here</a>
  5. Creating and testing custom tag libraries using GSP are very easier then JSP since there is no need for developer to code tld files and taglib declarations.

Basic Setup

  1. Install Java SDK 1.4 or above and set the JAVA_HOME environment variable to the location of that SDK.

The minimum required version of the SDK depends on which version of Grails you are using:

  • Java SDK 1.4+ for Grails 1.0.x and 1.1.x
  • Java SDK 1.5+ for Grails 1.2 or greater
  • Download the latest Grails release and set the GRAILS_HOME and Path environment variable to the extracted archive folder and Grails bin folder respectively.
  • An integrated development environment like NetBeans 6.5 or above, Eclipse 3.1 or above and plugins has to be download, IntelliJ IDEA, or UltraEdit.

A Simple Example for rendering different outputs to an HTML page

<html>
	<head>
		<title>GSP</title>
	</head>
	<body>
		Welcome!
		<% print 'Welcome!' %> ------------> print method
		<% out << 'Welcome' %> ------------> out object
		<%= '!' %> ------------> Scriplet
		${'Welcome!'} ------------> GString (Groovy String) style
	</body>
</html>

Output:

Comments

There are three ways of commenting code in GSP.

  • HTML Style: The code commented using this style will be seen in source code as well as data will be sent to browser, but its impact over the output will be disabled.
    Example:<!– out <<code–!>
  • JSP Style: It can be used for commenting a single line of code.
    Example:
    <%– out <<code –%>
  • GSP Style: It can be used for commenting larger/multiple block of code.
    Example:
    %{– code –}%

Variables and Scope

A user can declare variable with in a Scriplet block in this manner: <% vname %> and the same can be accessed using <%= vname %>.

Please note: vname indicates variable name.

Example to declare a variable of date category can be done like this <%d = new Date() %> and to access the same we can use <%= d %>.

Predefined Variables and Scope

  • request: This variable can be used as one of argument for invoking other service methods like doGet, doPost, etc.. of underlying Servlet in the project since this variable is the instance of HttpServletRequest interface which extends ServletRequest interface to provide request information for HTTP Servlets.
  • response: This variable is the instance of HttpServletResponse interface which extends ServletResponse interface and can be
    used for sending HTTP specific response for other service methods like doGet, doPost, etc… This variable can also access different methods of HTTP cookies and header information of web application.
  • out: This variable is the instance of responeWriter and can be used for sending response to output stream.
  • session: This variable is the instance of HttpSession and can be used for maintaining history of the visitor of that web-site since a unique id per visit is maintained for every web application.
  • params: Is a map object which can be used for retrieving request parameters.
  • flash: Is a temporary storage map object which can be used for working with flash scope. It maintains key value pairs within session which points to next request value and this value will be cleared out once the request is executed by an application.
  • application: It defines a set of methods for communicating with Servlet container through a Servlet. It is instance of
    javax.servlet.ServletContext.
  • applicationContext: Is the instance of Spring ApplicationContext which extends ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver classes to provide configuration for an application. This object is read-only but can be reloaded if needed.
  • grailsApplication:This object is the instance of GrailsApplication which extends ApplicationContextAware class
    and can be used to analysis artifacts of Grails Application since user can
    access metadata i.e., information regarding controllers, domain classes etc..
  • webRequest: Is instance of GrailsWebRequest.

Looping

Looping in GSP can be achieved in two ways.

  • By Embedding code between Scriplet i.e.., <% %>. For
    example consider a scenario where user wants to iterate through a list of two values i.e., User1 and User2 then same can be achieved through below mentioned sample code :
  • <html>
    <head> <title> GSP </title></head>
    <body>
    <% ["User1",User2""].each { num -> %>
    <p><%="Welcome ${num}!" %></p>
    <%}%>
    </body>
    </html>

Output:

    • Logical Branching is another way for looping.
      For example if the user wants to compare two variable values then the same can be
      done as mentioned below.
      <html>
      <head >
      <title> Looping Branching</title>
      </head>
      <body>
      <% def a =10 %> ------------> declaring variable can be done by 'def' also.
      <% def b =20 %>
      <% if (a==b) %>
      the given numbers are equal
      <% else %>
      the given numbers are not equal
      </body>
      </html> 

Output:

Page Directives:

By default all the JSP page directives are supported by GSP and user are provided with facility for creating their own tags according to the requirement by using GSP Tags. The import directive can be used for importing the necessary classes into a page but by default all the Groovy and GSP tags are available.
<%@page import =’groovy.sql.Sql’ %>
The contentType directive allows response to render to any other format than HTML i.e.., output can be render as a plain text or XML format.
<%@page contentType=’text/html; charset=UTF-8 %>

Scripting:

A multiple line/block of code can be enclosed between Scriplet i.e.., <% ……. %>.

A Sample example of Scripting:

<head>
<title>Scriptlet Demo</title>
</head>
<body>
<% def var = 'test'
if (var == 'test') out<< 'scriptlet demo' %>
</body>
</html>

Output:

Conclusion:

This article is all about basic concepts of Groovy Server Pages (GSP) and explain concepts like Output Rendering, Comments, Variable declarations, Predefined Variables as well as Scope, Looping, Page directives and Scripting with the related demos.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*