domingo, 27 de outubro de 2013

A Simple project in Grails - Portugues, LivroVisitas


Criação de um projeto/ Livro de Visitas usando Grails



Code in github/romalopes/livrovisitas

-- Criação do projeto


1:  create-project livrovisitas  



-- Criação do Controller inicial


1:  create-controller br.com.k2sistemas.Controle  

------------------------------------------------------------------
-- Implementação do Controller


1:  //ControleController.groovy  
2:  class ControleController {  
3:    def index() {   
4:          render "<h1>Inicio!</h1>"  
5:      }  
6:      def ola = {  
7:          render "<h1>Olá Pessoal da K2!</h1>"  
8:      }  
9:      def acao = {  
10:          [par1: "Hello", par2: "World!", date: new Date()]  
11:      }  
12:  }  
------------------------------------------------------------------
-- GSP chamada pelo ControlleController.acao


1:  <!-- acao.gsp -->  
2:  <!-- grails-app/views/controle -->  
3:  <html>  
4:      <body>  
5:          <p>${par1} ${par2} na data ${date}</p>  
6:      </body>  
7:  </html>  

------------------------------------------------------------------
-- Criação das classes de domínio


1:  create-domain-class br.com.k2sistemas.livroVisitas.User  
2:  create-domain-class br.com.k2sistemas.livroVisitas.Feedback  
3:  create-domain-class br.com.k2sistemas.livroVisitas.Comment  

------------------------------------------------------------------

-- Implementação das classes de domínio


1:  package br.com.k2sistemas.livroVisitas  
2:  class Feedback {  
3:   String title  
4:   String feedback  
5:   Date dateCreated // Nome predefinido pelo Grails a ser preenchido automaticamente  
6:   Date lastUpdated // Nome predefinido pelo Grails a ser preenchido automaticamente  
7:   // Relacionamento com outras classes  
8:   User user  
9:   static hasMany=[comments:Comment]  
10:   // Contrains definidas como static   
11:    static constraints = {  
12:          title(blank:false, nullable: false, size:3..80)  
13:          feedback(blank:false, nullable:false,size:3..500)  
14:          user(nullable:false)  
15:    }  
16:      String toString(){  
17:          return title;  
18:       }  
19:  }  

------------------------------------------------------------------

-- Implementação das classes de domínio


1:  package br.com.k2sistemas.livroVisitas  
2:  class User {  
3:   String name  
4:   String email  
5:   String webpage  
6:    static constraints = {  
7:          name (blank:false, nullable:false, size:3..30, matches:"[a-zA-Z1-9_]+")   
8:          email (email:true)  
9:          webpage (url:true)  
10:    }  
11:   String toString(){  
12:    return name;   
13:   }  
14:  }   
------------------------------------------------------------------

-- Implementação das classes de domínio


1:  package br.com.k2sistemas.livroVisitas  
2:  class Comment {  
3:   String comment  
4:   Date dateCreated // Nome predefinido pelo Grails a ser preenchido automaticamente  
5:   Date lastUpdated // Nome predefinido pelo Grails a ser preenchido automaticamente  
6:   User user;  
7:   // Garante que o Comment de um feedback será deletado caso o feedback seja deletado. Cascade  
8:   static belongsTo=[feedback:Feedback]  
9:    static constraints = {  
10:          comment (blank:false, nullable: false, size:5..500)  
11:          user (nullable: true) // Comments são permitidos sem User  
12:    }  
13:   String toString(){  
14:    if (comment.size()>20){  
15:     return comment.substring(0,19);  
16:    } else   
17:          return comment;   
18:     }  
19:  }   

-----------------------------------------

-- Criação dos controllers relativos às classes de domínio


1:  generate-controller br.com.k2sistemas.livroVisitas.Feedback   
2:  generate-controller br.com.k2sistemas.livroVisitas.User   
3:  generate-controller br.com.k2sistemas.livroVisitas.Comment  

-----------------------------------------

-- Scarffold stático. Modificar as classes de controle

1:   // Only change here  
2:   def scaffold = true   


-----------------------------------------

-- Criação das Views, com scaffold = false

1:  generate-views br.com.k2sistemas.livroVisitas.Feedback   
2:  generate-views br.com.k2sistemas.livroVisitas.User   
3:  generate-views br.com.k2sistemas.livroVisitas.Comment  

-----------------------------------------

-- Controllers e Views Poderiam ser geradas assim.

1:  generate-all  


-----------------------------------------

-- Mudar o DataSource para update.

-----------------------------------------

-- Autenticação

1:  create-filters security  

Create the SecurityFilters

1:  class SecurityFilters {  
2:    def filters = {  
3:      loginCheck(controller: '*', action: '*') {  
4:        before = {  
5:          if (!session.user && actionName != "login") {  
6:                redirect( controller: "controle", action: "login")  
7:            return false  
8:          }  
9:        }  
10:      }  
11:    }  
12:  }  


1:  <%--/controle/login.gsp --%>  
2:  <html>  
3:    <body>  
4:      <div class="body">  
5:        <h1>Login</h1>  
6:        <div class="message"><h3>${message}</h3></div>  
7:        <g:form action="login" method="post" >  
8:          <div class="dialog">  
9:            <table>  
10:              <tbody>  
11:                <tr class="prop">  
12:                  <td valign="top" class="name">  
13:                   <g:message code="message" default="Nome do Usuário:" />  
14:                  </td>  
15:                  <td valign="top" class="value">  
16:                    <g:textField name="username" value="${username}" />  
17:                  </td>  
18:                </tr>  
19:                <tr>  
20:                  <td>  
21:                   <g:message code="message" default="Senha: " />  
22:                  </td>  
23:                  <td valign="top" class="value ">  
24:                    <g:passwordField name="password" />  
25:                  </td>  
26:                </tr>  
27:              </tbody>  
28:            </table>  
29:          </div>  
30:          <div class="buttons">  
31:            <span class="button"><g:actionSubmit action="login" value="logado" /></span>  
32:          </div>  
33:        </g:form>  
34:      </div>  
35:    </body>  
36:  </html>  


No controleController

1:      def login() {  
2:          if(!params.username)  
3:          {  
4:              render(view: "login")  
5:              return  
6:          }  
7:          //AQUI INCLUIR TODAS AS REGRAS DE AUTENTICAÇÃO  
8:          def user = User.findByName(params.username)  
9:          if (user) {  
10:              session.user = params.username  
11:              render(view: "/index")  
12:          } else {  
13:              render(view: "login", model: [message: "Usuario ${params.username} nao encontrado"])  
14:          }  
15:      }  
16:      def logout () {  
17:          session.invalidate()  
18:          render(view: "login")  
19:      }  

UrlMappings.groovy

1:  "/"(controller: 'controle', action: 'index')  


-----------------------------------------

BootStrap


1:  class BootStrap {  
2:      def init = { servletContext ->  
3:           User user = new User(name:'anderson', email:'romalopes@romalopes.com.br', webpage:'http://www.romalopes.com.br')  
4:           if (!user.save()){  
5:               log.error "Could not save user!!"  
6:               log.error "${user.errors}"  
7:           }  
8:   }  
9:       def destroy = {  
10:       }  
11:  }  

--------------------------------------
-- Conversão e renderização de outros formatos. Inserir no ControleController.groovy

1:      def xmlList = {  
2:          render Feedback.list() as XML  
3:       }  


--------------------------------------

-- Utilização de Plugin


1:      install-plugin searchable  

-- Em cada classe de domínio que se deseja usar o searchable

1:    static searchable = true     


--------------------------------------

-- teste

1:  test-app  

--------------------------------------
-- Criação do War


1:  war  

Nenhum comentário:

Postar um comentário