Play Framework 完整实现一个APP(八)

创建Tag标签

1.创建Model

@Entity
@Table(name = "blog_tag")
public class Tag extends Model implements Comparable<Tag> {

    public String name;

    private Tag(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }

    public int compareTo(Tag otherTag) {
        return name.compareTo(otherTag.name);
    }

    public static Tag findOrCreateByName(String name) {
        Tag tag = Tag.find("byName", name).first();
        if(tag == null) {
            tag = new Tag(name);
        }
        return tag;
    }
}

2.Post类添加Tag属性

@ManyToMany(cascade = CascadeType.PERSIST)
public Set<Tag> tags;

public Post(User author, String title, String content) {
        this.comments = new ArrayList<Comment>();
        this.tags = new TreeSet<Tag>();
        this.author = author;
        this.title = title;
        this.content = content;
        this.postedAt = new Date();
}

 

3.Post类添加方法

关联Post和Tag

public Post tagItWith(String name) {
        tags.add(Tag.findOrCreateByName(name));
        return this;
}

  

返回关联指定Tag的Post集合

public static List<Post> findTaggedWith(String... tags) {
        return Post.find(
                "select distinct p from Post p join p.tags as t where t.name in (:tags) group by p.id, p.author, p.title, p.content,p.postedAt having count(t.id) = :size"
        ).bind("tags", tags).bind("size", tags.length).fetch();
}

4.写测试用例

@Test
public void testTags() {
        // Create a new user and save it
        User bob = new User("[email protected]", "secret", "Bob").save();

        // Create a new post
        Post bobPost = new Post(bob, "My first post", "Hello world").save();
        Post anotherBobPost = new Post(bob, "Hop", "Hello world").save();

        // Well
        assertEquals(0, Post.findTaggedWith("Red").size());

        // Tag it now
        bobPost.tagItWith("Red").tagItWith("Blue").save();
        anotherBobPost.tagItWith("Red").tagItWith("Green").save();

        // Check
        assertEquals(1, Post.findTaggedWith("Red", "Blue").size());
        assertEquals(1, Post.findTaggedWith("Red", "Green").size());
        assertEquals(0, Post.findTaggedWith("Red", "Green", "Blue").size());
        assertEquals(0, Post.findTaggedWith("Green", "Blue").size());
}

测试Tag

5.继续修改Tag类,添加方法

public static List<Map> getCloud() {
        List<Map> result = Tag.find(
            "select new map(t.name as tag, count(p.id) as pound) from Post p join p.tags as t group by t.name order by t.name"
        ).fetch();
        return result;
}

6.将Tag添加到页面上

/yabe/conf/initial-data.yml 添加预置数据

Tag(play):
    name:           Play

Tag(architecture):
    name:           Architecture

Tag(test):
    name:           Test

Tag(mvc):
    name:           MVC 

Post(jeffPost):
    title:          The MVC application
    postedAt:       2009-06-06
    author:         jeff
    tags:
                    - play
                    - architecture
                    - mvc
    content:        >
                    A Play

  

7.修改display.html将tag显示出来

<div class="post-metadata">
        <span class="post-author">by ${_post.author.fullname}</span>,
        <span class="post-date">${_post.postedAt.format(‘dd MMM yy‘)}</span>
	    #{if _as != ‘full‘}
			<span class="post-comments">
				 |  ${_post.comments.size() ?: ‘no‘}
				comment${_post.comments.size().pluralize()}
				 #{if _post.comments}
				 	 , latest by ${_post.comments[0].author}
				 #{/if}
			</span>
		#{/if}
		#{elseif _post.tags}
			<span class="post-tags">
				- Tagged
				#{list items:_post.tags, as:‘tag‘}
					<a href="#">${tag}</a>${tag_isLast ? ‘‘ : ‘, ‘}
				#{/list}
			</span>
		#{/elseif}
 </div>

  

8.添加listTagged 方法(Application Controller)

点击Tagged,显示所有带有Tag的Post列表

public static void listTagged(String tag) {
    List<Post> posts = Post.findTaggedWith(tag);
    render(tag, posts);
}

9.修改display.html,Tag显示

- Tagged
#{list items:_post.tags, as:‘tag‘}
    <a href="@{Application.listTagged(tag.name)}">${tag}</a>${tag_isLast ? ‘‘ : ‘, ‘}
#{/list}

  

10.添加Route

GET     /posts/{tag}                    Application.listTagged

  

现在有两条Route规则URL无法区分

GET     /posts/{id}                             Application.show
GET     /posts/{tag}                    	Application.listTagged

为{id}添加规则

GET     /posts/{<[0-9]+>id}                 Application.show

  

11.添加Post list页面,有相同Tag的Post

创建/app/views/Application/listTagged.html

#{extends ‘main.html‘ /}
#{set title:‘Posts tagged with ‘ + tag /}

*{********* Title ********* }*
#{if posts.size()>1}
	<h3>There are ${posts.size()} posts tagged ${tag}</h3>
#{/if}
#{elseif posts}
    <h3>There is 1 post tagged ‘${tag}‘</h3>
#{/elseif}
#{else}
    <h3>No post tagged ‘${tag}‘</h3>
#{/else}

*{********* Posts list *********}*
<div class="older-posts">
	#{list items:posts, as:‘post‘}
		#{display post:post, as:‘teaser‘ /}
	#{/list}
</div>

  

效果:

  

。。

时间: 2024-08-25 14:00:52

Play Framework 完整实现一个APP(八)的相关文章

Play Framework 完整实现一个APP(二)

1.开发DataModel 在app\moders 下新建User.java package models; import java.util.*; import javax.persistence.*; import play.db.jpa.*; @Entity public class User extends Model { public String email; public String password; public String fullname; public String

Play Framework 完整实现一个APP(十一)

添加权限控制 1.导入Secure module,该模块提供了一个controllers.Secure控制器. /conf/application.conf # Import the secure module module.secure=${play.path}/modules/secure /conf/routes # Import Secure routes * / module:secure 2.在Post Comment User Tag控制器上添加标签 @With(Secure.cl

Play Framework 完整实现一个APP(十四)

添加测试 ApplicationTest.java @Test public void testAdminSecurity() { Response response = GET("/admin"); assertStatus(302, response); assertHeaderEquals("Location", "http://localhost/login", response); } 更多测试介绍 http://play-framew

Play Framework 完整实现一个APP(十三)

添加用户编辑区 1.修改Admin.index() public static void index() { List<Post> posts = Post.find("author.email", Security.connected()).fetch(); render(posts); } 2.修改页面 app/views/Admin/index.html #{extends 'admin.html' /} <h3>Welcome ${user}, <

Play Framework 完整实现一个APP(九)

添加增删改查操作 1.开启CRUD Module 在/conf/application.conf 中添加 # Import the crud module module.crud=${play.path}/modules/crud 在/conf/routes 中添加 # Import CRUD routes * /admin module:crud 需要重启Server,导入CRUD Module 2.添加控制器 /app/controllers import play.*; import pl

一个App项目设计开发完整流程

作为一个PHP程序猿想转行APP开发可不是件容易的事情,话说隔行如隔山,这隔着一层语言也是多东西需要学习啊,一直对APP开发很感兴趣,最近请教了几个做移动开发的朋友,看了很多的资料,决定把自己学到的东西总结一下分享给和我一样刚做开发的菜鸟们. 1. idea形成——APP项目雏形 一个APP项目的最初首先要确定项目整体方案,整个项目的规划,大体框架,做成文档展现出来,以便大家提意见和更好的改进.也就是说首先要确立产品原型,进入项目评估阶段.经过反复确认,最终形成产品脑图和完整的需求文档. 2.功

Android实战技巧之二十八:启动另一个App/apk中的Activity

Android提供了在一个App中启动另一个App中的Activity的能力,这使我们的程序很容易就可以调用其他程序的功能,从而就丰富了我们App的功能.比如在微信中发送一个位置信息,对方可以点击这个位置信息启动腾讯地图并导航.这个场景在现实中作用很大,尤其是朋友在陌生的环境找不到对方时,这个功能简直就是救星. 本来想把本文的名字叫启动另一个进程中的Activity,觉得这样才有逼格.因为每个App都会运行在自己的虚拟机中,每个虚拟机跑在一个进程中.但仔细一想,能够称为一个进程,前提是这个App

论一个APP从启动到主页面显示经历的过程?

前言 (个人观点.不喜勿喷) 本部分内容是关于Android进阶的一些知识总结,涉及到的知识点比较杂,不过都 是面试中几乎常问的知识点,也是加分的点. 关于这部分内容,可能需要有一些具体的项目实践.在面试的过程中,结合具体自 身实践经历,才能更加深入透彻的描绘出来. (顺手留下GitHub链接,需要获取相关面试等内容的可以自己去找)https://github.com/xiangjiana/Android-MS 一.流程概述 启动流程: ① 点击桌面App图标,Launcher进程采用Binde

如何使用viewpager与fragment写一个app导航activity

今天我们来看一下如何使用viewpager和fragment组合来写一个app导航activity,这里使用到了android开源控件viewpagerindicator,有兴趣的同学可以去它网站上看看它的介绍. 附上效果截图一张: demo中只有一个activity,是用activity_main.xml来布局,其内容如下: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:and