service:让程序更健壮和可维护
1、实现PostService
grails create-service com.grailsinaction.post
1 package com.grailsinaction 2 3 class PostService { 4 /*如果发生错误,数据库回滚*/ 5 boolean transactional = true 6 7 Post createPost(String userId, String content) { 8 def user = User.findByUserId(userId) 9 if (user) { 10 def post = new Post(content: content) 11 user.addToPosts(post) 12 if (user.save()) { 13 return post 14 } else { 15 throw new PostException(message: "Invalid or empty post", post: post) 16 } 17 } 18 throw new PostException(message: "Invalid User Id") 19 } 20 } 21 22 class PostException extends RuntimeException { 23 String message 24 Post post 25 }
2、修改PostController,引入PostService,改写addPost闭包
1 package com.grailsinaction 2 3 class PostController { 4 5 def postService 6 7 ...... 8 9 def addPost = { 10 try { 11 def newPost = postService.createPost(params.id, params.content) 12 flash.message = "Added new post: ${newPost.content}" 13 } catch (PostException pe) { 14 flash.message = pe.message 15 } 16 redirect(action: 'timeline', id: params.id) 17 } 18 }