代码改变世界

开发一个JSP博客引擎 Active Your Action

2010-11-10 11:05  jinze  阅读(1051)  评论(1编辑  收藏  举报

上一篇文章,我们已经搭建好了一个包含 Struts2 hibernate annotation的开发框架,这次,我们仍然使用NetBeans 6.9 来继续我们的项目,为了使我们的博客引擎可以Active,我们需要两个Action,目前,MVC的设计模式已经是Web Application设计的主流模式,ASP .NET 也有相应的框架,现在,我们使用Struts2来做我们的MVCModel-View-Controller,模型-视图—控制器)框架。

使用Struts2有何好处? 

 

使用Strut2 可以使我们方便的分离请求和视图,Struts2可以很容易的将MVC中的 View Controller分离开,他们之间的相互对应关系只是体现在相应的配置文件里,对Struts2而言,是体现在 struts.xml 中,struts.xml 首先是一个格式良好的xml文件,这个文件的结构如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
      
<package name="User" namespace="/User" extends="struts-default">
          
<action name="AddBlog" class="com.deepfounder.BlogPlay.Action.AddBlog">
            
<result name="success" >
                ../admin.jsp
            
</result>
          
</action>
     
</package>
 
</struts> 

 

package 中的name 属性指定相应的包名,namespace属性指定名称空间,在package下的是action元素,用于指定具体的Action,其中的name属性指定相应的Action名称,这个名称和包名共同构成了访问这个Action的地址,比如,我们现在所定义的这个Action,访问它的地址就是

 

../User/AddBlog

 

 

 或者

../User/AddBlog.action 

*.action可写可不写。Action中的class指定了这个Action所对应的那个Java类的名称,现在,完成我们需要的Action

 

Active Your Action

首先,在我们的src目录下建立一个新的类:com.deepfounder.BlogPlay.Action.AddBlog。然后,在这个类中复制如下代码:

AddBlog
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 
*/
package com.deepfounder.BlogPlay.Action;

import com.deepfounder.BlogPlay.Entity.Blog;
import com.deepfounder.BlogPlay.Entity.Categories;
import com.deepfounder.BlogPlay.util.ChineseHandle;
import com.deepfounder.BlogPlay.util.RepleseHTML;
import com.opensymphony.xwork2.ActionContext;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import com.deepfounder.BlogPlay.Entity.Serveruser;
import com.deepfounder.BlogPlay.Entity.Userinfo;
/**
 *
 * 
@author Andy
 
*/
public class AddBlog extends SecondAction {

    
private String blogtitle;
    
private String blogtext;
    
private String blogcaption;
    
private Blog blog;
    
private List<com.deepfounder.BlogPlay.Entity.Categories> CategoriesList;
    
private String Categories;
    
private String Email;
    
private String CategoriesSEOID;
    
private String blogBuildID;
    
private Userinfo UserInfo;

    
private String PostId;

    
public String getPostId() {
        
return PostId;
    }

    
public void setPostId(String PostId) {
        
this.PostId = PostId;
    }

    

    
public String getBlogBuildID() {
        
return blogBuildID;
    }

    
public void setBlogBuildID(String blogBuildID) {
        
this.blogBuildID = blogBuildID;
    }

    
public String getCategoriesSEOID() {
        
return CategoriesSEOID;
    }

    
public void setCategoriesSEOID(String CategoriesSEOID) {
        
this.CategoriesSEOID = CategoriesSEOID;
    }

    
public String getBlogcaption() {
        
return blogcaption;
    }

    
public void setBlogcaption(String blogcaption) {
        
this.blogcaption = blogcaption;
    }
    
private java.util.Date date;

    
public String getBlogtext() {
        
return blogtext;
    }

    
public void setBlogtext(String blogtext) {
        
this.blogtext = blogtext;
    }

    
public String getBlogtitle() {
        
return blogtitle;
    }

    
public void setBlogtitle(String blogtitle) {
        
this.blogtitle = blogtitle;
    }

    @Override
    
public String execute() {

        Initblog();
        
this.SaveObject(blog);
        inItCategoriesList();
        
this.AddToRequest("CategoriesList", CategoriesList);
        
if (!CategoriesExist(this.blogcaption, this.Email)) {
            date 
= new java.util.Date();
            Categories cg 
= new Categories();
            cg.setCategories(
this.blogcaption);
            cg.setBuildID(CategoriesSEOID);
            cg.setEmail(Email);
            
this.SaveObject(cg);
        } 
else {
        }
        
// CharSetDebug();
        
// DoSomething();
        FreeSession();
        
return SUCCESS;
    }

    
public void Initblog() {
        blog 
= new Blog();
        blog.setBlogText(blogtext);
        blog.setTitle(blogtitle);
        
//ChineseHandle.SaveTo(blogtext);
        blog.setBlogText(blogtext);
        blog.setTitle(blogtitle);
        blog.setCaption(blogcaption);
        blog.setCommit(
0);
        blog.setVister(
0);
        
this.UserInfo = (Userinfo) this.GetSessionAttribute("UserInfo");
        
this.Email = ((Serveruser) this.GetSessionAttribute("ServerUser")).getEmail();
        blog.setEmail(
this.Email);
        date 
= new java.util.Date();
        blog.setBuildTime(date);
        blog.setBuildID(
this.getBlogBuildID());

        blog.setBaseURL(
this.UserInfo.getDoname() + "/" + com.deepfounder.BlogPlay.util.BlogFormatUrl.GetString(blog));

        blog.setSummary(RepleseHTML.Html2Text(blogtext));
    }

    
public String InitPage() {
        
return "ready";
    }

    
public String UpdatePostInit() {
        Blog UpBlog 
= (Blog) this.LoadEntity(Blog.classthis.PostId);
        
this.AddToRequest("Post", UpBlog);
        
return "UpData";
    }
     
public String UpdatePost() {
        
this.Initblog();
        System.out.print(
"摘要:"+this.blog.getSummary());
        
this.UpdataEntity(this.blog);
        
return "UpDataSuccess";
    }

    
public void getBaseUrl() {
    }

    
public void CharSetDebug() {
        ActionContext context 
= ActionContext.getContext();
        
// HttpSession session = (HttpSession) context.getSession();
        HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
        String str 
= ChineseHandle.SaveTo(this.blogtext);
        str 
= ChineseHandle.handleChinese(str);
        request.setAttribute(
"CharSetTest", str);
    }

    
public void inItCategoriesList() {
        
this.SessionInit();

        sess_Hib.beginTransaction();
        Criteria crit_Categories 
= sess_Hib.createCriteria(Categories.class);//
        crit_Categories.add(Expression.eq("email", Email));
        
this.CategoriesList = crit_Categories.list();

        sess_Hib.getTransaction().commit();
        sess_Hib.close();
    }

    
public boolean CategoriesExist(String CategoriesName, String Email) {
        
this.SessionInit();

        sess_Hib.beginTransaction();
        Criteria crit_Categories 
= sess_Hib.createCriteria(Categories.class);//用于显示指定日志的留言列表。
        crit_Categories.add(Expression.eq("categories", CategoriesName));
        crit_Categories.add(Expression.eq(
"email", Email));
        List
<Categories> TestLest = crit_Categories.list();
        sess_Hib.getTransaction().commit();
        sess_Hib.close();
        
if (TestLest == null) {
            
return false;
        } 
else {
            
for (int index = 0; index < TestLest.size(); index++) {
                
if (TestLest.get(index).getCategories().equals(CategoriesName)) {
                    
return true;
                } 
else {
                    
return true;
                }
            }
            
return false;
        }



    }

}

 在这段代码中,我们把用于数据持久化的代码也集成在了Action里面,曾经和一位开发人员讨论这样的问题,他的意见是数据持久化模块不应该集成在Action里面,这样会降低代码的可维护性,我赞同他的观点,但是我们目前完成的是一个(非常)简单的博客引擎,这样写应该也是可以的,下面这个类是所有Action的父类:

SecondAction
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 
*/
package com.deepfounder.BlogPlay.Action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Projections;

/**
 *
 * 
@author June
 
*/
public class SecondAction extends ActionSupport {//这个类是所有与数据库有关的Action的父类,包括分页,获取session等等。

    
private org.hibernate.cfg.AnnotationConfiguration cfg;
    
private org.hibernate.SessionFactory sf;
    
public org.hibernate.Session sess_Hib;

    
public void Load() {
        
this.SessionInit();
    }

    
public void SessionInit() {
        cfg 
= new AnnotationConfiguration();
        sf 
= cfg.configure().buildSessionFactory();//Session的产生工厂。
        sess_Hib = sf.openSession();
    }

    
public void SaveObject(Object ob) {
        
this.SessionInit();
        sess_Hib.beginTransaction();
        sess_Hib.save(ob);

        
//session.save(us);
        sess_Hib.getTransaction().commit();
        sess_Hib.close();
        
//return false;
    }

    
public void AddToRequest(String key, Object obc) {
        ActionContext context 
= ActionContext.getContext();
        Map
<String, Object> session = context.getSession();
        HttpServletRequest request 
= (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
        request.setAttribute(key, obc);
    }

    
public Object getRequestAttribute(String Key) {
        ActionContext context 
= ActionContext.getContext();
        Map
<String, Object> session = context.getSession();
        HttpServletRequest request 
= (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
        
return request.getAttribute(Key);
    }

    
public void AddToSession(String key, Object obc) {
        ActionContext context 
= ActionContext.getContext();
        Map
<String, Object> session = context.getSession();
        session.put(key, obc);
    }

    
public Object GetSessionAttribute(String key) {
        ActionContext context 
= ActionContext.getContext();
        Map
<String, Object> session = context.getSession();
        
return session.get(key);
    }

    
public List ExecuteSQLQuery(String SQLCommand) {
        
this.SessionInit();
        List list 
= this.sess_Hib.createSQLQuery(SQLCommand).list();

        
this.sess_Hib.close();
        
return list;
    }

    
public Object LoadEntity(Class EntityClass, String PrmKey) {
        
this.SessionInit();
        
this.sess_Hib.beginTransaction();
        Object ob 
= this.sess_Hib.get(EntityClass, PrmKey);

        
//session.save(us);
        this.sess_Hib.getTransaction().commit();
        
this.sess_Hib.close();
        
return ob;
    }

    
public List ExecuteHQLQuery(String SQLCommand) {
        
this.SessionInit();
        List list 
= this.sess_Hib.createQuery(SQLCommand).list();
        
this.sess_Hib.close();
        
return list;
    }

    
public List getEntityList(Class EntityClass) {
        
this.SessionInit();

        Criteria crit_Entity 
= sess_Hib.createCriteria(EntityClass);
        List list 
= crit_Entity.list();
        
this.sess_Hib.close();
        
return list;
    }

    
public List getEntityListByPage(Class EntityClass, int PageSize, int PageCount) {
        
//this.FirstResult=this.PageSize*this.PageCount;
        this.SessionInit();
        Criteria crit_Entity 
= sess_Hib.createCriteria(EntityClass);
        crit_Entity.setFirstResult(PageSize 
* (PageCount - 1));
        crit_Entity.setMaxResults(PageSize);
        List list 
= crit_Entity.list();
        
this.sess_Hib.close();
        
return list;
    }

    
public List getListHandStard(List list) {
        
//this.FirstResult=this.PageSize*this.PageCount;
        List NewList = new ArrayList();
        
for (int i = list.size() - 1; i >= 0; i--) {
            NewList.add(
0, list.get(i));
        }
        
return NewList;
    }

    
public int GetEntityCount(Class EntityClass) {
        
this.SessionInit();
        Criteria crit_Entity 
= sess_Hib.createCriteria(EntityClass);
        
int count = ((Integer) crit_Entity.setProjection(Projections.rowCount()).uniqueResult()).intValue();
        
this.sess_Hib.close();
        
return count;
    }

    
public void FreeSession() {
        
try {
            
this.sess_Hib.close();
        } 
catch (Exception ex) {
        } 
finally {
            
this.sess_Hib = null;
        }

    }

    
public boolean UpdataEntity(Object Entity) {
        
this.SessionInit();
        
try {
            
this.sess_Hib.update(Entity);
            
this.sess_Hib.close();
            
return true;
        } 
catch (Exception ex) {
            
this.sess_Hib=null;
            
return false;
        }
    }

    
public boolean DeleteEntity(Object Entity) {
        
this.SessionInit();
        
try {
            
this.sess_Hib.delete(Entity);
            
this.sess_Hib.close();
            
return true;
        } 
catch (Exception ex) {
            ex.printStackTrace();
            
this.sess_Hib.close();
            
return false;
        }
    }

    
public List ExecuteEntityQuery(Class EntityClass, String Key, String Value) {
        
this.SessionInit();
        Criteria crit_BlogList 
= sess_Hib.createCriteria(EntityClass);//也用于显示随笔列表,但是是一个侧边框列表,只显示标题和链接
        
//crit_BlogList.setFirstResult(0);
        
//crit_BlogList.setMaxResults(10);
        crit_BlogList.add(Expression.eq(Key, Value));
        sess_Hib.getTransaction().commit();
        List list 
= crit_BlogList.list();
        sess_Hib.close();
        
return list;
    }
}

 

 在我们的AddBlog中,包含了一些私有的变量,大家一定奇怪这些变量时做什么用的,这些变量的目的是从前端的View页面的Post中得到相应的参数,比如 

    private String blogtitle;
    
private String blogtext;
    
private String blogcaption;
    
private Blog blog;
    
private String Categories;
    
private String Email;
    
private String CategoriesSEOID;
    
private String blogBuildID;
    
private Userinfo UserInfo; 

 

 而在相应的前端页面中,也包含了全部这些变量:

admin.jsp
<%-- 
    Document   : admin
    Created on : 
2010-9-29:36:20
    Author     : Andy
--%>

<%@page import="com.deepfounder.BlogPlay.Entity.Categories"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    
"http://www.w3.org/TR/html4/loose.dtd">
<%
                    String path 
= request.getContextPath();
                    String basePath 
= request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
                    response.setCharacterEncoding(
"utf-8");
                    request.setCharacterEncoding(
"utf-8");
                    List
<Categories> CategoriesList=(List<Categories>)request.getAttribute("CategoriesList");
                    
if(session.getAttribute("ServerUser")==null)
                    {
                        response.sendRedirect(basePath
+"Login.jsp");
                    }

        
%>

<html>
    
<head>
        
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        
<script type="text/javascript" src="<%=basePath%>/ckeditor/ckeditor.js"></script>
        
<title>后台管理</title>
        
<style>
            #AddNewCatrage{
                 border
-color: #000;
                 color: #316ac5;
                 background
-color: #996644;
                 width: 
40%;
                 visibility:  hidden;



}
        
</style>
         
<script>
            var c 
= function(o) {
return document.getElementById(o)
};

if (window.addEventListener) {
$(
'blogtitle').addEventListener('input', function() {$('blogcaption').value = this.value}, false);
}

$(
'blogtitle').onpropertychange = function() {
    $(
'blogcaption').value=$('blogtitle').value;
}
       
function addOptionToSelect()
{
   AddIEAndGoogleChorm();
}
function AddbuyFireFox(){

}
function AddIEAndGoogleChorm(){
    var slt
=document.getElementById("blogcaption");
   var objOption
=document.createElement("OPTION");
   objOption.value
=document.getElementById("Categories").value;
   objOption.text
=document.getElementById("Categories").value;
   slt.add(objOption);
   
//alert(slt.options.length);
   slt.options[slt.options.length-1].selected='selected';
}

function getvalue()
{
   var slt
=document.getElementById("blogcaption");
   alert(slt.value);
}
function ChangeVisionAble()
{
    document.getElementById(
"AddNewCatrage").style.append("visibility:visible;");
    
//document.getElementById("Temp")
    document.getElementById("Temp").append(Document.getElementById("AddNewCatrage"));
}
</script>

    
</head>
    
<body>
        
<br>
        
<form action="<%= basePath%>User/AddBlog.action" method="post" >
            
<a>您的随笔标题:</a><input id="blogtitle" name="blogtitle"/><br/>
            
<a>您的随笔标识:</a><input id="blogBuildID" name="blogBuildID"/><br/>
            
<a>您的随笔标签:</a>
            
<select name="blogcaption" id="blogcaption" >
               
                
<%
                   
if(CategoriesList!=null)
                       {
                          
for(int index=CategoriesList.size()-1;index>0;index--)
                              {
                                 out.print(
"<option>");
                                 out.print(CategoriesList.get(index).getCategories());
                                 out.print(
"</option>");
                              }
                       }
                
%>
            
</select>

            或者您也可以添加一个新标签,标签名:
<input type="text" id="Categories" name="Categories" >标签标识符:<input type="text" id="CategoriesSEOID" name="CategoriesSEOID" ><input type="button" name="Temp" id="Temp" value="添加" onclick="addOptionToSelect()" >
            
<br/><textarea id="blogtext" name="blogtext" cols="80" rows="10" ></textarea>
            
<input type="submit" >
        
</form>
            
<div id="AddNewCatrage" name="AddNewCatrage" >
                添加一个新的标签:
<br/>
                标签名:
<input type="text" id="CatrageName" name="CatrageName"/>
                标签标示符:
<input type="text" id="CatrageID" name="CatrageID"/>
                
<input type="button" value="添加"/>
            
</div>
    
</body>
     
<script type="text/javascript">
        
//<![CDATA[
        
// Replace the <textarea id="editor1"> with an CKEditor instance.
        var editor = CKEDITOR.replace('blogtext' );

       
// var aboutme = CKEDITOR.replace( 'aboutme' );


        
//]]>

    
</script>
    
<script type="text/javascript">

</script>
</html>

  这样,我们已近完成了发布博客的相关功能,下一篇文章,让我们一起讨论一下如何更好的显示我们的博客文章,让前端更富亲和力。

 

 

用电子邮件联系Andy