惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
宝玉的分享
宝玉的分享
月光博客
月光博客
B
Blog
云风的 BLOG
云风的 BLOG
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
博客园_首页
GbyAI
GbyAI
人人都是产品经理
人人都是产品经理
A
About on SuperTechFans
Y
Y Combinator Blog
L
LangChain Blog
有赞技术团队
有赞技术团队
D
Docker
爱范儿
爱范儿
博客园 - 司徒正美
H
Hackread – Cybersecurity News, Data Breaches, AI and More
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
酷 壳 – CoolShell
酷 壳 – CoolShell
Microsoft Security Blog
Microsoft Security Blog
D
DataBreaches.Net

博客园 - 页面载入出错

Grails指南摘要-403-生命周期 Grails指南摘要-402-logging Grails指南摘要-401-Controller中设置默认Action Grails指南摘要-307-测试领域类 Grails指南摘要-306-嵌入式对象 Grails指南摘要-305-扩展和继承 Grails指南摘要-304-对象关系 Grails指南摘要-303-自定义对象映射 Grails指南摘要-302-瞬时属性 Grails指南摘要-301-属性验证 20130527-jQuery in actin-看代码说事-ch01 20130518-Grails In Action-5、控制应用程序流(04小节) 20130518-Grails In Action-5、控制应用程序流(03小节) 20130517-Grails In Action-5、控制应用程序流(01小节) 20130517-Grails In Action-4、让模型工作(06小节) 20130516-Grails In Action-4、让模型工作(05小节) 20130516-Grails In Action-4、让模型工作(04小节) 20130516-Grails In Action-4、让模型工作(03小节) 20130516-Grails In Action-4、让模型工作(02小节)
20130517-Grails In Action-5、控制应用程序流(02小节)
页面载入出错 · 2013-05-19 · via 博客园 - 页面载入出错

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 }