A jsp + Ajax comment system page 1 / 2

Time:2021-10-12

This is a simple comment system, which uses JDOM (jdom-b9 is used here), the instance uses JSP as the view, AJAX (prototype-1.4 is used), servlet and JavaBean as the background processing, and XML files are used to store data.
1. The application directory structure is as follows:
data
  |–comment.xml
js
  |–prototype.js
  |– Ufo.js (UTF-8 format)                                                                      
css
  |–ufo.css
images
  |–loading.gif
Ufo.jsp (UTF-8 format)
WEB-INF
  |-lib
      |-jdom.jar    
  |-classes
     …
  |-web.xml

/*********************************************
*Author:Java619
*Time:2007-02-14
**********************************************/

2. Background JavaBeans    CommentBean.java

/** *//**
 * < P> Is there a comment system</p>
 * @author ceun
 *  Contact the author: < br >
 *    <a href=”mailto:[email protected]”>ceun</a><br>
 * @ version   one   2007-01-30   Realize basic functions < br >
 * CommentBean.java
 * Created on Jan 30, 2007 9:39:19 AM
 */
package com.ceun.bean;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/** *//**
 *< p>   Encapsulating operations on XML</p>
 * @author ceun
 *  Contact the author: < br >
 *    <a href=”mailto:[email protected]”>ceun</a><br>
 * @ version   one   2007-01-30   Realize basic functions < br >
 */
public class CommentBean …{
    private String filepath;

    private SAXBuilder builder = null;

    private Document doc = null;

    public CommentBean() …{

    }
/** *//**
 *  Initialize the XML file path and load the file
 * */
    public CommentBean(String path) …{
        this.filepath = path;
        builder = new SAXBuilder();
        try …{
            doc = builder.build(filepath);
        } catch (JDOMException e) …{
             System.out.print (“the specified XML file cannot be found”);
            e.printStackTrace();
        } catch (IOException e) …{
             System.out.print (“the specified file cannot be found”);
            e.printStackTrace();
        }
    }
 /** *//**
  *  Add comments
  * @ param   nikename   Reviewer nickname
  * @ param   comment   Comment content
  * @ param   attitude   Commentator’s conclusion (yes – exists, no – does not exist)
  * */
    public String addComment(String nikename, String comment, String attitude) …{
        Element root = doc.getRootElement();

        Element el = new Element(“comment”);
        Random rand = new Random();
        int id = rand.nextInt(10000);
        el.setAttribute(“id”, “comment_” + id);
        el.setAttribute(“attitude”, attitude);

        Element name = new Element(“nikename”);
        CDATA cname = new CDATA(nikename);
        name.addContent(cname);

        Element data = new Element(“data”);
        CDATA ctext = new CDATA(comment);
        data.addContent(ctext);

        SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
        Date date = new Date();
        Text tdate = new Text(format.format(date));
        Element pubdate = new Element(“pubdate”);
        pubdate.addContent(tdate);

        el.addContent(name);
        el.addContent(data);
        el.addContent(pubdate);
        root.addContent(el);
        XMLOutputter outputter = new XMLOutputter(”  “, true, “GB2312”);
        //  Clear spaces between comment elements
        outputter.setTrimAllWhite(true);
        try …{
            outputter.output(doc, new FileWriter(filepath));
        } catch (IOException e) …{
             System.out.println (“there is an error in the specified path”);
            e.printStackTrace();
        }
        return tdate.getText();
    }
/** *//**
 *  Delete comments with the specified ID
 * @ param   commentId   Comment ID
 * @ return   Returns the operation result string (success or failure)
 * */
    public String removeComment(String commentId) …{
        Element root = doc.getRootElement();
        List comments = root.getChildren();
        int size = comments.size();
        Element dist = null;
        for (int i = 0; i < size; i++) …{
            Element comment = (Element) comments.get(i);
            String id = comment.getAttributeValue(“id”);
            if (id.equals(commentId)) …{
                dist = comment;
                break;
            }
        }
        if (dist != null) …{
            root.removeContent(dist);
            XMLOutputter outputter = new XMLOutputter(”  “, true, “GB2312”);
            //  Clear spaces between comment elements
            outputter.setTrimAllWhite(true);
            try …{
                outputter.output(doc, new FileWriter(filepath));
            } catch (IOException e) …{
                 System.out.println (“error in rewriting file”);
                e.printStackTrace();
            }
             return   “The specified element was deleted successfully!”;
        } else
             return   “The specified element does not exist!”;
    }
/** *//**
 *  Batch delete comments
 * @ param   commentIdArgs   Comment ID array
 * @ return   Returns the operation result string (success or failure)
 * */
    public String removeComments(String[] commentIdArgs) …{
        Element root = doc.getRootElement();
        List comments = root.getChildren();
        int size = comments.size();
        int len = commentIdArgs.length;
        List<Element> dist = new ArrayList<Element>();
        outer:for (int i = 0; i < size; i++) …{
            Element comment = (Element) comments.get(i);
            String id = comment.getAttributeValue(“id”);

            for (int j = 0; j < len; j++)
                if (id.equals(commentIdArgs[j])) …{
                    dist.add(comment);
                    continue outer;
                }
        }
        int dist_size=dist.size();
        if (dist_size != 0) …{
            for (int i = 0; i < dist_size; i++)
                root.removeContent(dist.get(i));
            XMLOutputter outputter = new XMLOutputter(”  “, true, “GB2312”);
            //  Clear spaces between comment elements
            outputter.setTrimAllWhite(true);
            try …{
                outputter.output(doc, new FileWriter(filepath));
            } catch (IOException e) …{
                 System.out.println (“error in rewriting file”);
                e.printStackTrace();
            }
             return   “The specified element collection was deleted successfully!”;
        } else
             return   “The specified element collection does not exist!”;
    }

    /** *//**
     * @return the filepath
     */
    public String getFilepath() …{
        return filepath;
    }

    /** *//**
     * @param filepath
     *            the filepath to set
     */
    public void setFilepath(String filepath) …{
        this.filepath = filepath;
    }

    /** *//**
     * @return the builder
     */
    public SAXBuilder getBuilder() …{
        return builder;
    }

    /** *//**
     * @param builder
     *            the builder to set
     */
    public void setBuilder(SAXBuilder builder) …{
        this.builder = builder;
    }
}

3. Servlet for handling Ajax requests    AddCommentServlet.java

package com.ceun.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ceun.bean.CommentBean;
/** *//**
 * < p> Background processing Servlet</p>
 *2007-01-30
 * * @author ceun
 *  Contact the author: < br >
 *    <a href=”mailto:[email protected]”>ceun</a><br>
 * @ version   one   2007-01-30   Realize basic functions < br >
 * */
public class AddCommentServlet extends HttpServlet …{

    /** *//**
     * serialVersionUID long
     */
    private static final long serialVersionUID = 1L;

    /** *//**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException …{
        request.setCharacterEncoding(“UTF-8”);
        response.setContentType(“text/html;charset=UTF-8”);
        response.setHeader(“Cache-Control”, “no-cache”);

        PrintWriter out = response.getWriter();
        String nikename = request.getParameter(“nn”);

        String comment = request.getParameter(“rsn”);
        String attitude = request.getParameter(“atti”);
        String filepath = request.getSession().getServletContext().getRealPath(
                “data/comment.xml”);
        CommentBean bean = new CommentBean(filepath);
        String str = bean.addComment(nikename, comment, attitude);
        out.println(str);
    }

    /** *//**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException …{

        doGet(request, response);
    }

}

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]