1. 댓글 달기 예제

: 댓글을 입력하면 최신글 순서로 글이 보여진다. 

: 댓글은 db에 저장하고, 브라우저에 내용을 지우고 다시 가져오는 방식으로 한다.

: AJAX에서  MVC모델 이용하여 DB 정보 가져오기.

: 서블릿에서는 페이지호출이 아니라 해당 데이터만 XML로 만들어 처리함.



예제> 

1) 테이블 : 

    comments

2) 서블릿 :

    - dao, vo, controller

3) html




[[ comments 테이블 ]]


** 테이블 생성, sequence생성,데이터입력

drop table comments;

create table comments

(

 num number primary key,

 id varchar2(10),

 comments varchar2(50)

);

create sequence seq_comments;

insert into comments values( seq_comments.nextval, 'test', 'good!');

commit;



** java파일


[[  CommentsVo.java  ]]


package test.vo;

public class CommentsVo {

    private int num;

    private String id;

    private String comments;

    public CommentsVo(){

        

    }

    

    public CommentsVo(int num, String id, String comments) {

        super();

        this.num = num;

        this.id = id;

        this.comments = comments;

    }

    public int getNum() {

        return num;

    }

    public void setNum(int num) {

        this.num = num;

    }

    public String getId() {

        return id;

    }

    public void setId(String id) {

        this.id = id;

    }

    public String getComments() {

        return comments;

    }

    public void setComments(String comments) {

        this.comments = comments;

    }

}



** db접속 정보

[[  DBConnection.java  ]]


package test.db;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class DBConnection {

    public static Connection getCon() throws SQLException{

        Connection con=null;

        try{

            Class.forName("oracle.jdbc.OracleDriver");

            String url="jdbc:oracle:thin:@localhost:1521:XE";

            con= DriverManager.getConnection(url,"scott","tiger");

            return con;

        }catch(ClassNotFoundException ce){

            System.out.println(ce.getMessage());

            return null;

        }

    }

}


** 처리 로직

[[   CommentsDao.java  ]]


package test.dao;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import test.db.DBConnection;

import test.vo.CommentsVo;

public class CommentsDao {

    public int insert(CommentsVo vo){

        Connection con = null;

        PreparedStatement pstmt=null;

        try{

            con=DBConnection.getCon();

            String sql="insert into comments values(seq_comments.nextval,?,?)";

            pstmt=con.prepareStatement(sql);

            pstmt.setString(1, vo.getId());

            pstmt.setString(2, vo.getComments());

            int n=pstmt.executeUpdate();

            return n;

        }catch(SQLException se){

            System.out.println(se.getMessage());

            return -1;

        }finally{

            try{

                if(pstmt!=null) pstmt.close();

                if(con!=null) con.close();

            }catch(SQLException se){

                System.out.println(se.getMessage());

            }

        }

    }

    public ArrayList<CommentsVo> getList(){

        Connection con = null;

        PreparedStatement pstmt=null;

        ResultSet rs = null;

        try{

            con=DBConnection.getCon();

            String sql="select * from comments";

            pstmt=con.prepareStatement(sql);

            rs=pstmt.executeQuery();

            ArrayList<CommentsVo> list = new ArrayList<>();

            while(rs.next()){

                CommentsVo vo = new CommentsVo(

                        rs.getInt("num"),

                        rs.getString("id"),

                        rs.getString("comments")

                        );

                list.add(vo);

            }

            return list;

        }catch(SQLException se){

            System.out.println(se.getMessage());

            return null;

        }finally{

            try{

                if(rs!=null) rs.close();

                if(pstmt!=null) pstmt.close();

                if(con!=null) con.close();

            }catch(SQLException se){

                System.out.println(se.getMessage());

            }

        }

    }

}




** controller

[[  CommController.java   ]]


package test.controller;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import test.dao.CommentsDao;

import test.vo.CommentsVo;

@WebServlet("/comm.do")

public class CommController extends HttpServlet {

    @Override

    protected void service(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        //1. 요청분석

        String cmd = request.getParameter("cmd");

        if(cmd.equals("insert")){

            insert(request,response);

        }

    }

    private void insert(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        //사용자가 보낸 아이디와 영화평 얻어오기.

        String id=request.getParameter("id");

        String comments=request.getParameter("comments");

        

        //정보를 vo 객체에 담기.

        CommentsVo vo=new CommentsVo(0,id,comments);

        

        //2. 요청에 따른 비즈니스로직을 처리하기 위한 자바객체 호출

        CommentsDao dao=new CommentsDao();

        

        //DB에 vo객체 추가하기.

        int n=dao.insert(vo);

        

        //3. 결과값을 xml로 응답하기 (ajax는 페이지이동하면 안된다.)

        response.setContentType("text/xml;charset=euc-kr");

        PrintWriter pw = response.getWriter();

        pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

        pw.println("<result>");

        if(n>0){

            pw.println("<info>success</info>");

        }else{

            pw.println("<info>fail</info>");

        }

        pw.println("</result>");

        pw.close();

    }

}





** html 


[[  movieinfo.html  ]]


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

    function getXHR(){

        if(window.XMLHttpRequest){

            return new XMLHttpRequest();

        }else{

            return new ActiveXObject("Microsoft.XMLHTTP");

        }        

    }

    var xhr=null;

    function addComments(){

        //1. xhr객체 얻어오기

        xhr=getXHR();


        //2. 콜백메소드 설정하기

        xhr.onreadystatechange=callback;


        //3. open함수로 초기화설정(전송방식,서버주소,..)

        xhr.open("POST","comm.do?cmd=insert",true);


        //4. send함수로 서버에 요청

        //-*-  post방식으로 전송할때는 아래와같이 콘텐츠타입을 설정해야 함!*-*-/

       xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

        

        //사용자가 입력한 아이디와 영화평 얻어오기

        var id=document.getElementById("id").value;

        var comments=document.getElementById("comments").value;

        var param="id=" +id +"&comments=" +comments;


        //send메소드를 호출하면서 파라미터 전송하기

        xhr.send(param);

    }

    function callback(){

        if(xhr.readyState==4 && xhr.status==200){

            var xml=xhr.responseXML;

            var result=xml.getElementsByTagName("info")[0].firstChild.nodeValue;

            if(result=="success"){

                //alert('등록성공');

                getList(); //댓글목록얻어오기

            }else{

                //alert("등록실패");

            }

        }

    }


    function getList(){

        xhr=getXHR();

        xhr.onreadystatechange=showList;

        xhr.open("get","comm.do?cmd=list",true);

        xhr.send(null);

    }


    //댓글 div안의 내용들 모두 제거하기.

    function listRemove(){

        //commList의 자식div의 갯수 얻어오기.(컬렉션타입으로 얻어옴)

        var childs=document.getElementById("commList").childNodes;


        //commList의 자식div들 제거하기.

        for(var i=childs.length - 1;i>=0;i--){

            //childs배열의 i번째 요소 참조값 얻어오기.

            var child=childs.item(i);


            //commList에서 child제거하기

            document.getElementById("commList").removeChild(child);

        }

    }


    // textarea에서 개행은 \n으로 db에 저장된다.

    // 가져온 데이터를 개행하기 위해서는 

    // \n을 <br/>로 바꿔줘야 한다.

    //str1문자열에서 str2를 str3문자열로 바꾸기

    //예: replace("hello \n test","\n","<br/>");

    function replace(str1, str2, str3){

        var ch="";

        var chstr="";

        for(var i=0;i<str1.length;i++){

            ch=str1.charAt(i);

            if(ch==str2){// str2 : '\n'

                chstr=chstr+str3;

            }else{

                chstr=chstr + ch;

            }

        }

        return chstr;

    }


    // 정상적이면(xhr.readyState==4 && xhr.status==200)

    // 기존 화면의 <div>삭제하고 불러와 

    // 표시한다.

    function showList(){

        if(xhr.readyState==4 && xhr.status==200){

            //commList의 자식div모두 제거하기

            listRemove();

            

            //var xml=xhr.responseText;

            //alert(xml);

            var xml=xhr.responseXML;

            var len=xml.getElementsByTagName("id").length;

            if(len>0){

                for(var i=0;i<len;i++){

                    var id=xml.getElementsByTagName("id")[i].firstChild.nodeValue;

                    var comments=xml.getElementsByTagName("comments")[i].firstChild.nodeValue;

                    comments = replace(comments,'\n','<br/>');

                    var txt= "작성자:" + id + "<br/>" +

                            "영화평:" + comments ;


                    //내용을 담을 div 생성하기

                    var div=document.createElement("div");


                    //생성된 div에 내용담기

                    div.innerHTML=txt;

                    div.style.width="300px";

                    div.style.height="80px";

                    div.style.border="1px solid blue";

                    div.style.marginTop="8px";


                    //전체 댓글을 담을 div의 참조값 얻어오기

                    var commList=document.getElementById("commList");


                    //댓글 div에 생성된 div추가하기.

                    commList.appendChild(div);

                }

            }

        }

    }

</script>

</head>

<body onload="getList()">

<div style="width:500px;height: 300px;background-color: orange">

    <h2>호빗</h2>

    <div>

        <img alt="" src="images/001.jpg" />

    </div>

</div>

<div>

    <!-- 댓글이 추가될 div -->

    <div id="commList">

    </div>

    <div id="commReg">

        아이디 <input type="text" id="id"/><br/>

        영화평 <textarea rows="3" cols="30" id="comments"></textarea>

        <br/>

        <input type="button" value="등록" onclick="addComments()"/>

    </div>

</div>

</body>

</html>

 

 


 

+ Recent posts