项目组分配了一个博客添加的功能模块,考虑到表现层面向于用户,采用ajax技术能给用户好的使用体验,所以决定使用初学相关的ajax技术给实例应用一下,顺便当做一个学习总结。
先描述一下项目基本情况,项目基于J2EE下。采用MVC结构,使用了当前流行的struts+hibernate+spring框架。ajax方面主要用prototype.js 1.5,这些东西我BLOG里面都有。
主要总结几个方面的内容:
blog.js : javascript脚本代码,用于实例化prototype里面ajax对象,进行调用。
addBlogUser.jsp : 表现层jsp代码,用于显示用户查询数据。
listCategory.jsp : 生成XML结构数据,供addBlogUser.jsp调用。
rssCategory.jsp : 生成表格数据,供addBlogUser.jsp显示。
struts-config.xml : 部分struts配置。
BlogAction.java : action文件。
Dao层,Service层就暂时不提供了。一些hibernate和spring的配置和代码,以后的总结再慢慢写。
by : jadesun;QQ:280155
2006-10-22
==========================================
blog.js:
var params = "";
$(rssContent).innerHTML = viewWaitString();
var hrefname = document.getElementsByTagName("A")
for(var i=0;i<hrefname.length;i++) ...{
hrefname[i].className="empty";
}
$(categoryID).className = "col";
//异步调用ajax查询url数据。
var myAjax = new Ajax.Request(url,
...{method: 'get', parameters: params, onComplete:showResponse});
}
function submitSearchForm() ... {
url ="/users/blog/rssList/rssSearch.html";
var title = $("blogForm_id").title.value;
var params = "title="+encodeURI(title);
var myAjax = new Ajax.Request( url,
...{method: 'get', parameters: params, onComplete:showResponse});
}
function addBlogByUrl(name,url,id) ... {
$(id+"_span").innerHTML="add....";
params = "blog.url="+encodeURI(url)+"&feed.name="+encodeURI(name)+"&blog.id="+encodeURI(id);
var myAjax = new Ajax.Request( "/users/blog/save.html",
...{method: 'get', parameters: params, onComplete: function()...{
$(id+"_span").innerHTML="<font color=red>已加入</font>";
}});
}
function viewWaitString() ... {
return "<table border='0' cellpadding='0' cellspacing='0'>"+
"<tr>"+
"<td width='100%'>正在加载中......</td>"+
"</tr>"+
"</table>";
}
==========================================
addBlogUser.jsp:
< script type ="text/javascript" src ="/script/blog.js" ></ script >
< div id ="manageAdd" >
< div id ="MAddBackg" >
< div id ="topbg01" ></ div >
< div id ="topbg02" ></ div >
</ div >
< div id ="MAddBackg" >
< div id ="queque_left" >
< ul >
< li > ==控制台== </ li >
<!-- 调用/users/blog/rssList/listCategory.html下面的数据,根据Struts-config.xml中的配置,该项将执行action:listCategory,将结果转向给/xml/blog/listCategory.jsp生成的xml数据。 -->
< c:import url ="/users/blog/rssList/listCategory.html" var ="category" />
< x:parse var ="CategoryDoc" xml ="${category}" />
< x:forEach select ="$CategoryDoc/categorys/category" var ="category" >
< li >
<!-- 读取listCategory.jsp生成的xml中的categorys/category/url节点的数据,生成的连接方面如下:
http:/xxxxx/users/blog/rssList/listRss.html?blogtid=12397&categoryid=123,将连接给blog.js进行ajax异步调用。
然后根据struts-config.xml中的配置,查找/users/blog/rssList/listRss相应的action-mapping,执行action:viewCategoryRss,将结果转 向给/xml/blog/rssCategory.jsp文件,rssCategory.jsp文件将表格化的显示相应的结果给用户。 -->
< a href ="#" id ="category_<x:out select=" $category/id" /> " onClick="viewCategoryRss(' < x:out select ="$category/url" /> ','category_ < x:out select ="$category/id" /> ');return false">
< x:out select ="$category/name" />
</ a >
</ li >
</ x:forEach >
</ ul >
</ div >
<!-- 将title表单内容提交给/users/blog/rssList/rssSearch.html路径,根据Struts-config.xml中的配置执行action:categoryRssSearch,同样将结果转向给/xml/blog/rssCategory.jsp文件,rssCategory.jsp文件将表格化的显示相应的结果给用户。 -->
< html:form action ="/users/blog/rssList/rssSearch.html" styleId ="blogForm_id" onsubmit ="submitSearchForm()" >
< div id ="table_div" >
< html:text property ="title" value ="请输入搜索内容" styleClass ="text_01" />< a href ="javascript:submitSearchForm()" >< html:img src ="/images/default/gooweb_20_2.gif" align ="absmiddle" /></ a >
< span id ="rssContent" ></ span >
</ div >
</ html:form >
</ div >
< div id ="MAddBackg" class ="Hsiza" >
< div id ="bottombg03" ></ div >
< div id ="bottombg04" ></ div >
</ div >
==============================================
listCategory.jsp :
< %@ page language ="java" contentType ="text/xml; charset=gb2312" % >
< %@ taglib uri ="/tags/struts-bean" prefix ="bean" % >
< %@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix ="c" % >
< %@ taglib uri ="http://java.sun.com/jsp/jstl/fmt" prefix ="fmt" % >
< %
response .setHeader("Cache-Control","no-store");
response.setHeader("Pragrma","no-cache");
response.setDateHeader("Expires",0);
% >
< categorys >
< c:forEach var ="categorys" items ="${category}" >
< c:if test ="${categorys.name != '博客'}" >
< category >
< id > ${categorys.id} </ id >
< url > <![CDATA[ /users/blog/rssList/listRss.html?blogtid=12397&categoryid=${categorys.id} ]]> </ url >
< name > ${categorys.name} </ name >
</ category >
</ c:if >
</ c:forEach >
</ categorys >
==============================================
rssCategory.jsp :
<% ... @ page language="java" contentType="text/html; charset=gb2312" %>
<% ... @ taglib uri="/tags/struts-bean" prefix="bean" %>
<% ... @ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<% ...
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragrma","no-cache");
response.setDateHeader("Expires",0);
%>
< c:choose >
< c:when test ="${not empty rsslist}" >
< table border ="0" cellpadding ="0" cellspacing ="0" >
< tr class ="BGCOLOR" >
< c:forEach var ="rssLists" items ="${rsslist}" varStatus ="status" >
< td width ="33%" > ${rssLists.title} < a href ="javascript:addBlogByUrl('${rssLists.title}','${rssLists.url}','${rssLists.id}')" >< span id ="${rssLists.id}_span" > 添加 </ span ></ a ></ td >
< c:choose >
< c:when test ="${status.count % 3 == 0}" >
</ tr >
< tr <c:if test ="${status.count % 6 == 0}" > class="BGCOLOR" </ c:if > >
</ c:when >
< c:otherwise >
</ c:otherwise >
</ c:choose >
</ c:forEach >
<% ...
int size = 3 - ((java.util.List)request.getAttribute("rsslist")).size()%3;
if (size < 3) {
for(int i=0; i < size; i++) out.println("<td></td>");
out.println("</tr>");
}
%>
</ table >
</ c:when >
< c:otherwise >
< table border ="0" cellpadding ="0" cellspacing ="0" >
< tr >
< td width ="100%" > 您所点击栏目没有相应的Rss资源 </ td >
</ tr >
</ table >
</ c:otherwise >
</ c:choose >
====================================================
Struts-config.xml:
< form-bean name ="categoryRssForm" type ="org.apache.struts.validator.DynaValidatorForm" >
< form-property name ="blogtid" type ="java.lang.Integer" />
< form-property name ="categoryid" type ="java.lang.Integer" />
< form-property name ="title" type ="java.lang.String" />
</ form-bean >
<!-- 定义Action Mapping: -->
< action path ="/users/blog/rssList/listCategory" type ="gooweb.web.action.BlogAction" parameter ="listCategory" >
< forward name ="display" path ="/xml/blog/listCategory.jsp" />
</ action >
< action path ="/users/blog/rssList/rssSearch" type ="gooweb.web.action.BlogAction" scope ="request" validate ="false" name ="categoryRssForm" parameter ="categoryRssSearch" >
< forward name ="display" path ="/xml/blog/rssCategory.jsp" />
</ action >
< action path ="/users/blog/rssList/listRss" type ="gooweb.web.action.BlogAction" name ="categoryRssForm" validate ="false" parameter ="viewCategoryRss" >
< forward name ="display" path ="/xml/blog/rssCategory.jsp" />
</ action >
=====================================================
BlogAction.java :
/** */ /**
* @title listCategory
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward listCategory(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception ... {
BaseTagManager manager =(BaseTagManager)getBean("baseTagManager");
Collection<Category> category = manager.findAllCategory().values();
request.setAttribute("category", category);
return mapping.findForward("display");
}
/** */ /**
* @title viewCategoryRss
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward viewCategoryRss(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception ... {
DynaValidatorForm df = (DynaValidatorForm) form;
Integer blogtid = Integer.valueOf(df.get("blogtid").toString());
Integer categoryid = Integer.valueOf(df.get("categoryid").toString());
if (blogtid != 0 && categoryid !=0)...{
String sql="select r.rssid as rssid,r.rssname as rssname,r.rssurl from rss r, rsstagsrelation rt1, rsstagsrelation rt2, tags t1, tags t2 " +
"where r.rssid=rt1.rssid and rt1.rssid = rt2.rssid " +
"and rt1.tid=t1.tid and t1.tid="+blogtid+" and rt2.tid=t2.tid and t2.tid="+categoryid+"";
List<Rss> rsslist = new ArrayList<Rss>();
if (sql != null && sql.toString() != "") ...{
try ...{
DataSource dataSource = (DataSource) getBean("dataSource");
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) ...{
while (rs.next()) ...{
Rss rss = new Rss();
rss.setId(rs.getLong("rssid"));
rss.setTitle(rs.getString("rssname"));
rss.setUrl(rs.getString("rssurl"));
rsslist.add(rss);
}
}
rs.close();
stmt.close();
conn.close();
}catch(Exception error)...{
error.printStackTrace();
}
}
request.setAttribute("rsslist", rsslist);
}
return mapping.findForward("display");
}
/** */ /**
* @title categoryRssSearch
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward categoryRssSearch(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception ... {
DynaValidatorForm df = (DynaValidatorForm) form;
RssManager manager = (RssManager)getBean("rssManager");
List<Rss> rsslist = manager.findByTitle(RequestUtil.encodingUTF(df.getString("title").trim()));
request.setAttribute("rsslist", rsslist);
return mapping.findForward("display");
}