简体   繁体   中英

How to pass params into Services that I get from the gsp and I have in my Controller in Grails

I've got the params that a user enter in a g:textField in my controller when I call method save() , and I need to use this value in my services. How can I pass the params that I have in my controller to my services or is possible pass this data directly to my services from my gsp??

I'm trying to pass the params equal than the gsp-Controller When I'm trying to access to the params in my Services, but I get an error: No such property: params

GSP:

<g:textField name="enterEmail" required=""/>

Controller:

save(){
    def enterMail = params.enterEmail   
}

Services:

def sendYourEmail(EmailTemplate emailTemplateInstance){     
    ....            
    def enterMail = params.enterEmail   
    log.info "Sending email"
    String source = 'myEmail'
    Destination destination = new Destination([enterMail])
    Content subject = new Content('test')
    Body body = new Body().withHtml(new Content(output.toString()))
    Message message = new Message(subject, body)
    amazonWebService.ses.sendEmail(new SendEmailRequest(source, destination, message))  
}

The params attribute you are using in your controllers is a dynamic attribute Grails added for you at runtime. You can't use from a service class.

It's a bad idea to get the params from a service, but you can do that using this line:

org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes().params

A good idea is to use a command: a plain groovy/java object with your parameters bound from the request, and send this command to the service. Doing that, you remove the dependency between your service class (business layer) and the params map (web layer): it will be easier to test and reusable from other parts (you can create the command whatever you want).

Command:

class MailCommand {
    String enterEmail
}

Controller:

def mailService
def save(MailCommand mailCommand){
    mailService.sendYourEmail(mailCommand, mailTemplate)
}

MailService class:

def sendYourEmail(MailCommand mailCommand, EmailTemplate emailTemplateInstance){
    def enterMail = mailCommand.enterEmail   
    ...
}

More information: http://grails.github.io/grails-doc/latest/guide/single.html#commandObjects

pass params as an argument to your service method, as it's only accessible from controllers or taglibs

UPDATE:

code sample

controller

def yourService
def save(){
  service.sendYourEmail emailTemplateInstance, params
}

service:

def sendYourEmail( EmailTemplate emailTemplateInstance, params ){
   def enterMail = params.enterEmail
   ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM