Create Grails Project:
I am using GGST. before going to IDE, create one folder for workspace in your drive. open IDE and switch workspace to IDE.
Step 1 : Integrate JDK for that workspace.
- Goto window -> Preferences -> Java -> Installed JREs -> Add JDK
Step 2 : Goto File -> New -> Grails Project
Open the project, it shows the project structure like domains,controllers,services etc..
In Grails, Provide Spring Security for an application follow these steps.
Step 1 : create grails project
Step 2 : after creation of project, we want to change three groovy files in Conf. they are
1. BuildConfig
2. Config
3. DataSource
Step 3 : In BuildConfig,
- comment the 'test' dependency in dependencies
- uncomment mysql connector ( runtime 'mysql:mysql-connector-java:5.1.29' ) in dependencies
- in plugins add ( compile ":spring-security-core:2.0-RC4" )
Step 4 : In config,
// Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.gb.vamsi.Account' //Create package with com.gb.vamsi Name in domain
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.gb.vamsi.AccountRole'
grails.plugin.springsecurity.authority.className = 'com.gb.vamsi.Role'
grails.plugin.springsecurity.successHandler.defaultTargetUrl = '/welcome'
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
'/**': ['permitAll'],
'/index': ['permitAll'],
'/index.gsp': ['permitAll'],
'/assets/**': ['permitAll'],
'/**/js/**': ['permitAll'],
'/**/css/**': ['permitAll'],
'/**/images/**': ['permitAll'],
'/**/favicon.ico': ['permitAll']
]
grails.plugin.springsecurity.useSecurityEventListener = true
grails.plugin.springsecurity.onInteractiveAuthenticationSuccessEvent = { e, appCtx ->
com.gb.ems.Activity.withTransaction {
// TO DO Login date & time saving actions here
}
}
Step 5 : In DataSource, the code like
dataSource {
pooled = true
jmxExport = true
driverClassName = "com.mysql.jdbc.Driver"
username = "root"
password = "root"
}
In devlopment in environments,
development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:mysql://localhost:3306/vamsi" // Create database name with vamsi
// Optional
pooled = true
jmxExport = true
driverClassName = "com.mysql.jdbc.Driver"
username = "root"
password = "root"
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
jmxEnabled = true
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 5000
minEvictableIdleTimeMillis = 60000
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
}
}
Step 6 : Create DB in mysql with name 'vamsi' as we given step 5
Step 7 : Create package as given in step 4
Step 8 : clean the project : click grails command history icon, type 'clean' and then click 'Enter'
refresh the dependencies : Right click on project -> Grails Tools -> Refresh Dependencies
Step 9 : Execute command in grails command history as Like ( s2-quickstart com.gb.vamsi Account Role )
Step 10: In our package created Account, Role and AccountRole domain classes
step 11: run the project ( Right click on project -> Run as -> run-app )
// Steps to Spring security service
// In BootStrap,
// Login purpose
Step 1 : Create roles
// Mentions Roles Here
def roles = [
"ROLE_ADMIN",
"ROLE_SCHOOL_ADMIN",
"ROLE_SCHOOL_SUB_ADMIN",
"ROLE_USER",
"ROLE_TEACHER",
"ROLE_WARDEN",
"ROLE_ACCOUNTANT",
"ROLE_DIRECTOR",
"ROLE_PARENT",
"ROLE_ADMISSION_USER",
"ROLE_FEE_USER"
]
// create roles which are not existed in role table
def dbRoles = Role.findAll()*.authority
if(!dbRoles.containsAll(roles)){
roles.each{ def role = new Role(authority:it).save(flush:true) }
}
// create the admin account if it doesn't exists
def admin = Account.findByUsername("admin")
if(!admin){
//create an account
admin = new Account()
admin.username = "admin"
admin.password = "admin"
admin.save(flush:true)
roles.each{
def role = Role.findByAuthority(it)
AccountRole.create(admin, role)
}
}
Step 2 : run the project. main page will be displayed. click on login controller it renders login page.
Step 3 : give user name & password it checks those parameters in account table in database.
if login is valid it calls the controller what we given at defaultTargetUrl in config. otherwise it shows error
message
// Logout Purpose
Step 4 : For Logout, first we override the existing logout controller.
with CTRL + SHIFT + R, first find out the logout controller. copy that code. create one new logout controller
in our package com.gb.vamsi and then paste the code. overriding is completed.
Step 5 : Create on button in gsp, call index of logout controller on clicking on that. you terminated from your
application and grails main page will be displayed. in this index, you want update logout time details.
Step 6 : after logout, you want to redirect your application to some other page. for that purpose, you make a change '/'
mapping in UrlMappings.groovy.
Step 7 : Example, after logout i want to display login page. the code like as follows:
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/"(controller:"/login") // Here we modify the code
"500"(view:'/error')
}
}
Steps to creation of loggers in grails:
// we inject the loggers in config.groovy
Step 1 : By default, loggers will be injected. For maintain of information in some file we will follow like this.
Add these 3 steps in log4j.main as follows.
// step 1
appenders {
console name: 'stdout', layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n')
file name:'file', maxFileSize: 1024, file:'/practice_project/greenbuds/logs/projectLog.log', layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n')
}
// By default, messages are logged at the error level to both the console and hibe.log
// step 2
root {
error 'stdout', 'file'
additivity = true
}
//step 3
info "grails.app.controllers.com.gb.vamsi"
debug "grails.app.controllers.com.gb.vamsi"
info "grails.app.services.com.gb.vamsi"
debug "grails.app.services.com.gb.vamsi"
Step 2 : After running the application, projectLog.log file created in project drive. the filename is given in step1 appenders -> filename
Step 3 : For every action, the information tracked in logs.
Filters:
Although Grails controllers support fine grained interceptors, these are only really useful when applied to a
few controllers and become difficult to manage with larger applications. Filters on the other hand can be applied
across a whole group of controllers, a URI space or to a specific action. Filters are far easier to plugin and
maintain completely separately to your main controller logic and are useful for all sorts of cross cutting concerns
such as security, logging, and so on.
To create a filter create a class that ends with the convention Filters in the grails-app/conf directory.
Filter Types:
Within the body of the filter you can then define one or several of the following interceptor types for the filter:
before - Executed before the action. Return false to indicate that the response has been handled that that all
future filters and the action should not execute
after - Executed after an action. Takes a first argument as the view model to allow modification of the model
before rendering the view
afterView - Executed after view rendering. Takes an Exception as an argument which will be non-null if an exception
occurs during processing. Note: this Closure is called before the layout is applied.
Note : Every action comes under filter