到11节基本的东西都已经实现了,剩下的都是一点细节问题;比如由于注册用户和普通浏览用户权限不同,所以大家看的也有所不同;
在项目设计的时候,普通用户可以看博客,发表评论;为了避免不必要的麻烦,将普通用户的操作特别的写一个servlet,这样也比较容易控制。
HomeServlet主要就是负责这个任务。
在HomeServlet里面主要就是两个方法,为了配合以后的页面设计,相对之前的BlogServlet等等,相对复杂一点(其实还好)。
让我们来看看这个Sql语句的作用
sql= select b.id as id,b.title as title,b.content as content,b.date as date,c.name as category,categoryId,comments from 
(select blog.id as id ,blog.title as title,blog.category_id as categoryId,count(comment.blog_id) as comments,blog.content as content,blog.date as date from blog 
left join comment on blog.id = comment.blog_id group by blog.id) as b, category c 
where categoryId = c.id 
order by date desc;
首先
select blog.id as id ,blog.title as title,blog.category_id as categoryId,count(comment.blog_id) as comments,blog.content as content,blog.date as date from blog
left join comment on blog.id = comment.blog_id group by blog.id
comment表中对blog_id一致的记录做统计,与blog表左连接;
然后再blog新表与category根据categoryId做连接。
然后修改一下Blog类,添加一个comments属性(记录此blog对象所包含的评论数目)。
2.对blog.content做下处理,在显示所有博文的时候,对blog.content的内容做一个简报。
很简单的一个
getBriefContent()方法:
public String getBriefContent() {
        StringBuffer briefContent = new StringBuffer(content);
        int length = 200;
        if (briefContent.length() < length) {
            length = briefContent.length();
        }
        briefContent = briefContent.delete(length, briefContent.length());
        //filter html mark;
        briefContent.append("  ..");
..");
        return briefContent.toString();
    } 
限定200字符长度,如果博文内容多于200字符,那么取前200字符;否则直接贴上博文内容。
3.对blog.content另一个修改。因为写博文的时候,可能所选用的字体啊什么每次都不同,以至于在浏览所有博文的时候会很乱;
所以以下doFilter(StringBuffer sb)方法,主要对文字进行过滤,将充满HTML MARK的文章过滤一下。
private StringBuffer doFilter(StringBuffer source) {
        StringBuffer header = new StringBuffer(source);
        while((header.indexOf("<")!=-1)&&(header.indexOf(">")!=-1)){
           int startPos = header.indexOf("<");
           int endPos = header.indexOf(">");
            header = header.delete(startPos, endPos+1);
        }
        return header;
    }
因此
getBriefContent()方法也要插上一句(Line 3):
 1 public String getBriefContent() {
 2         StringBuffer briefContent = new StringBuffer(content);
 3         briefContent = doFilter(briefContent);
 4         int length = 200;
 5         if (briefContent.length() < length) {
 6             length = briefContent.length();
 7         }
 8         briefContent = briefContent.delete(length, briefContent.length());
 9 
10         //filter html mark;
11         briefContent.append("  ..");
..");
12         return briefContent.toString();
13     }