>  기사  >  Java  >  PlayFramework는 APP를 완벽하게 구현합니다(8)

PlayFramework는 APP를 완벽하게 구현합니다(8)

黄舟
黄舟원래의
2016-12-23 16:44:171196검색

创建Tag标签

 

1.创建Model

@Entity
@Table(name = "blog_tag")public class 태그 확장 모델 구현 비교 가능 {
   공개 문자열 이름;    
   PRivate Tag(문자열 이름) {        this.name = name;
   }    
   public String toString() {        return name;
   }    
   public int CompareTo(Tag otherTag) {        이름을 반환합니다. CompareTo(otherTag.name);
   }
   public static Tag findOrCreateByName(String name) {
       Tag tag = Tag.find("byName", name).first();        if(태그 == null) {
           tag = 새 태그(이름);
       }        return tag;
   }}

 

2.Post类添加Tag属性

@ManyToMany(cascade = CascadeType.PERSIST)public Set 태그;공개 게시물(사용자 작성자, 문자열 제목, 문자열 내용) {
       this.comments = new ArrayList();        this.tags = new TreeSet();        this.author = 저자;        this.제목 = 제목;        this.content = 내용;        this.postedAt = new Date();
}

 

3.Post类添加방법

关联Post와Tag

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

  

返回关联指定Tag的Post集合

공개 정적 목록 findTaggedWith(String... 태그) {        return Post.find(                "Post p에서 고유한 p를 선택하고 p.tags를 t로 조인합니다. 여기서 t.name은 (:tags) 그룹에서 p.id, p.author, p.title, p.content,p.posted개수(t.id) = :size"
       ).bind("tags", Tags).bind("size", tagged.length).fetch();
}

 

4.写测试用例

@Testpublic void testTags() {        // 새 사용자를 생성하고 저장
       사용자 bob = new User("bob@Gmail.com", "비밀", "Bob").save();    
       // 새 게시물 만들기
       Post bobPost = new Post(bob, "My first post", "Hello world").save();
       Post anotherBobPost = new Post(bob, "Hop" , "안녕하세요").save();        
       // 뭐
       assertEquals(0, Post.findTaggedWith("Red").size());        
       // 지금 태그하세요
       bobPost.tagItWith("Red").tagItWith("Blue").save();
       anotherBobPost.tagItWith("Red").tagItWith("Green"). 구하다();        
       // 확인
       assertEquals(1, Post.findTaggedWith("Red", "Blue").size());  
       assertEquals(1, Post.findTaggedWith("빨간색", "녹색").size());  
       assertEquals(0, Post.findTaggedWith("빨간색", "녹색", "파란색").size());  
       assertEquals(0, Post.findTaggedWith("녹색", "파란색").size());   }

测试Tag

 

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

공개 정적 목록 getCloud() {
       목록 result = Tag.find(            "Post p에서 새 맵(t.name을 태그로, count(p.id)를 파운드로) 선택 p.tags를 t.name으로 t 그룹으로 t.name으로 순서 지정"
       ) .술책();        결과 반환;
}

 

6.将Tag添加到页face上

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

태그(재생):
   이름:           Play

태그(아키텍처):
   이름:           아키텍처

태그(테스트):
   이름:           테스트

태그(mvc):
   이름:           MVC

게시물(jeffPost):
   제목:          MVC 애플리케이션
   게시 위치:       2009-06-06
 작성자:         제프
   태그:          
                   - 플레이
                   - 아키텍처
                   - mvc
   내용:       >
                   A Play

  

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


  

8.添加listTagged 방법(애플리케이션 컨트롤러)

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

public static void listTagged(String tag) {
   List 게시물 = Post.findTaggedWith(태그);
   render(태그, 게시물);
}

 

9.修改display.html,Tag显示

- 태그됨
#{목록 항목:_post.tags, as:'tag'}
   ${tag} ${tag_is마지막 ? '' : ', '}
#{/list}

  

10.添加Route

GET     /posts/{tag}                    Application.listTagged

  

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

GET     /posts/{id}                             Application.show
GET     /posts/{태그} Application.listTagged

为{id}添加规则

GET     /posts/{id}                 Application.show

  

11.添加게시물 목록页face,유상동태그의 게시물

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

#{extends 'main. html' /}
#{제목 설정:'' + 태그로 태그된 게시물 /}

*{********* 제목 ********* }*
#{if posts.size()>1}

${tag}

태그가 지정된 ${posts.size()}개의 게시물이 있습니다
#{/if }
#{elseif 게시물}
   

'${tag}'

태그가 지정된 게시물이 1개 있습니다.  
#{/elseif}
#{else}
   

'${tag}'


#{/else}

태그된 게시물이 없습니다. *{********* 게시물 목록 *********}*
   
#{목록 항목:게시물, as:'포스트'}
#{표시 포스트:포스트, as:'teaser' /}
#{/list}

  

 

效果:

PlayFramework는 APP를 완벽하게 구현합니다(8)

PlayFramework는 APP를 완벽하게 구현합니다(8)

 以上就是PlayFramework完整实现一个APP(八)的内容,更多敳关内容请关注PHP中文网(www.php.cn)! 


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.