* XML 태그를 만들어 호출한 곳으로 전송하는 예제

 


test02.html  --> server2.jsp ( 결과를 xml 태그로 만들어 전송 ) --> test02.html

 

오늘날짜출력 버튼을 클릭

 


< test02.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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">

    var xhr=null;

    function getXHR(){

        //1. XMLHttpRequest객체 얻어오기

        if(window.XMLHttpRequest){

            //IE 7.0이상, Chrome, FireFox, safari,..

            return new XMLHttpRequest();

        }else{

            //IE 하위버전(6.0이하)

            return new ActiveXObject("Microsoft.XMLHTTP");

        }

    }

    function getToday(){

        //1. xhr객체 얻어오기

        xhr=getXHR();


        //2. callback메소드 설정

        xhr.onreadystatechange=getServerDate;


        //3. open설정(서버주소,..)

        xhr.open("GET","server2.jsp",true);


        //4. send메소드로 서버에 요청.

        xhr.send(null);

    }

    //서버로 부터 응답이 오면 자동호출

    function getServerDate(){

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

            var xml=xhr.responseXML;

            // firstChild는 객체. 그 값은 .nodeValue를 사용.

            var tt=xml.getElementsByTagName("today")[0].firstChild.nodeValue;

            var div=document.getElementById("today");

            div.innerHTML=tt;

        }

    }

</script>

</head>

<body>

<input type="button" value="오늘날짜출력" onclick="getToday()"/>

<div id="today">

</div>

</body>

</html>


 


 

< server2.jsp >

<%@page import="java.io.PrintWriter"%>

<%@page import="java.util.Calendar"%>

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//오늘날짜 구하기

Calendar gg=Calendar.getInstance();

//오늘날짜를 문자열에 담기

String str=gg.get(Calendar.YEAR) +"년" + 

           (gg.get(Calendar.MONTH)+1) +"월" +

         gg.get(Calendar.DATE) + "일";

//xml로 응답하기위한 문자열객체 만들기

StringBuffer sb=new StringBuffer();

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

sb.append("<data>");

sb.append("<today>" + str +"</today>");

sb.append("</data>");

//xml로 응답하기위한 콘텐츠타입설정

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

//xml로 응답하기위한 스트림객체 얻어오기

PrintWriter pw=response.getWriter();

//xml로 클라이언트에 응답하기

pw.write(sb.toString());

pw.close();

%>

 

 

 

'WEB > Ajax Json' 카테고리의 다른 글

AJAX #06 JSON 관련 jar, javascript파일  (0) 2013.05.04
AJAX #05 JSON  (0) 2013.05.04
AJAX #04 댓글 달기 예제  (1) 2013.05.04
AJAX #02 xml파일을 읽어서 화면에 표시하는 예제  (0) 2013.05.04
AJAX #01 설명  (0) 2013.05.04


1. Ajax (Asynchronous Javascript XML)
 - 비동기 방식의 자바스트립트와  XML
 - 웹브라우져가 아닌 XMLHttpRequest객체를 통해 웹서버와 통신한다.
 - 웹서버의 응답결과는 html이 아닌 xml또는 단순 텍스트이다.
 - 페이지의 이동없이 결과가 화면에 반영된다.
 
 2. XMLHttpRequest를 사용한 프로그래밍 순서
 1) 웹브라우져에 내장하고 있는 XHR객체 얻어오기
 2) XHR객체를 이용해 웹서버에 요청 전송하기
 3) 콜백메소드를 통해 웹서버에서 응답된 정보를 화면에 반영하기


 


* xml파일을 읽어서 화면에 표시하는 예제


 

 


 

* title, price 태그의 내용을 읽어서 보여줌.


< server1.xml >


<?xml version="1.0" encoding="UTF-8"?>
<result>
    <title>ajax test</title>
    <price>10000</price>
</result>




< test01.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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">

    var xhr=null;

    function getXHR(){

        if(window.XMLHttpRequest){

            //IE 7.0이상,Chrome,Firefox,Safari,...

            return new XMLHttpRequest();

        }else{

            //IE 하위버전(6.0이하)

            return new ActiveXObject("Microsoft.XMLHTTP");

        }        

    }

    function getData(){

        //1. XMLHttpRequest객체 얻어오기

        xhr=getXHR();

        //alert(xhr);

        //2. 콜백메소드 설정하기(서버로부터 응답이 오면 자동호출되는 메소드)

        xhr.onreadystatechange=callback;

        //3. open메소드로 초기화작업 설정하기

        //xhr.open("요청방식","서버주소",비동기통신방식인지)

        xhr.open("GET","server1.xml",true);

        //4. send메소드를 통해서 서버에 요청하기

        xhr.send(null);

    }

    //서버로부터 응답이 오면 자동 호출!

    function callback(){

        //readyState==4 : 서버로부터 응답이 완료된 경우

        //status==200 : 서버로부터 응답이 성공적으로 이루어진 경우

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

            //응답된 값은 responseText라는 속성으로 얻어옴:텍스트형태로 얻어옴

            //var xml=xhr.responseText;

            //응답된 값을 XML형태로 얻어옴

            var xml=xhr.responseXML;

            //alert(xml);    

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

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

            //alert(title +"," + price);

            //div참조값 얻어오기

            var div=document.getElementById("result");

            //div에 서버로부터 전송된 데이터 보이기

            div.innerHTML="도서제목:" + title +"<br/>" +

                          "가격:" + price;

        }

    }

</script>

</head>

<body>

<input type="button" value="서버로부터 전송받기" onclick="getData()"/>

<div id="result">

</div>

</body>

</html>











'WEB > Ajax Json' 카테고리의 다른 글

AJAX #06 JSON 관련 jar, javascript파일  (0) 2013.05.04
AJAX #05 JSON  (0) 2013.05.04
AJAX #04 댓글 달기 예제  (1) 2013.05.04
AJAX #03 XML 태그를 만들어 호출한 곳으로 전송하는 예제  (0) 2013.05.04
AJAX #01 설명  (0) 2013.05.04




1. Ajax (Asynchronous Javascript XML)


 - 비동기 방식의 자바스트립트와  XML

 ( 비동기 방식 : 서버에 요청 후 결과와 상관없이 진행하는 경우.

   동기 방식 : 서버에 요청 후 결과를 받아야 다음 일이 진행되는 경우 )

   

 - 웹브라우져가 아닌 XMLHttpRequest객체를 통해 웹서버와 통신한다.

 - 웹서버의 응답결과는 html이 아닌 xml또는 단순 텍스트이다.

 - 페이지의 이동없이 결과가 화면에 반영된다.

 


 2. XMLHttpRequest를 사용한 프로그래밍 순서


 1) 웹브라우져에 내장하고 있는 XHR객체 얻어오기

 2) XHR객체를 이용해 웹서버에 요청 전송하기

 3) 콜백메소드를 통해 웹서버에서 응답된 정보를 화면에 반영하기 

 

db접속 정보를 저장한 db.properties파일을 읽어오기

 

- db.properties 파일에 db접속과 관련된 정보를 넣어둔다. 접속 시 파일을 읽어서 내용을 가져온다.

 

 

EX> db.properties

## Database Connect Info
url=jdbc:oracle:thin:@127.0.0.1:1521:xe
user=hr
pwd=hr

 

 

EX> Test05_Properties.java

package test01.jdbc;

 

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

 

class MyJdbc05{
    Connection con;
    public MyJdbc05() {

        Properties prop=new Properties();

        try{
            //db접속 정보를 저장한 db.properties파일을 읽어오기
            Reader reader=new FileReader("db.properties");
           
            //prop객체가 properties파일을 읽어와 Key와 Value형태로 분리해서 Map에 저장함.
           prop.load(reader);

            //Key에 해당하는 Value값 얻어오기
            String url=prop.getProperty("url");
            String user=prop.getProperty("user");
            String pwd=prop.getProperty("pwd");

            System.out.println("url==>" + url);
            System.out.println("user==>" + user);
            System.out.println("pwd==>" + pwd);
           
            // 설정된 정보로 db접속하기
            Class.forName("oracle.jdbc.OracleDriver");
            con=DriverManager.getConnection(url,user,pwd);
            System.out.println("db접속성공 ");
            System.out.println("con:" + con);
        }catch(FileNotFoundException fe){
            System.out.println(fe.getMessage());
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }catch(Exception ce){
            System.out.println(ce.getMessage());
        }
    }
}
public class Test05_Properties {
    public static void main(String[] args) {
        new MyJdbc05();
    }
}

 

 

 

[[ Dynamic query ]]

- 동적으로 조건이 변해야 하는 경우 Mybatis에서 사용 예제
- 두가지 : 
 (1) select 로 하나만 선택하는 경우
 (2) checkbox로 여러개 선택하는 경우



(1)  main.jsp

검색( select ) ,검색2 (checkbox)










<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
</head>
<body>
<a href="MemberCon?cmd=list1">검색</a><br/>
<a href="MemberCon?cmd=list2">검색2</a><br/>
</body>
</html>



(2) list1.jsp











<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
</head>
<body>
<div><!-- 조회된 목록이 보여질 div -->
    <table border="1" width="600">
        <tr>
            <th>아이디</th><th>비밀번호</th><th>이메일</th>
            <th>전화번호</th><th>가입일</th>
        </tr>
        <c:forEach var="vo" items="${list }">
            <tr>
                <td>${vo.id }</td>
                <td>${vo.pwd }</td>
                <td>${vo.email }</td>
                <td>${vo.phone }</td>
                <td>${vo.regdate }</td>
            </tr>
        </c:forEach>
    </table>
</div>
<div>
    <form method="post" action="MemberCon?cmd=list1">
        <select name="field">
            <option value="id">아이디</option>
            <option value="email">이메일</option>
            <option value="phone">전화번호</option>
        </select>
        <input type="text" name="keyword"/>
        <input type="submit" value="검색"/>
    </form>
</div>
</body>
</html>



(3) list2.jsp









<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
</head>
<body>
<div>
    <table border="1" width="600">
        <tr>
            <th>아이디</th><th>비밀번호</th><th>이메일</th>
            <th>전화번호</th><th>가입일</th>
        </tr>
        <c:forEach var="vo" items="${list }">
            <tr>
                <td>${vo.id }</td>
                <td>${vo.pwd }</td>
                <td>${vo.email }</td>
                <td>${vo.phone }</td>
                <td>${vo.regdate }</td>
            </tr>
        </c:forEach>
    </table>
</div>
<div>
    <form method="post" action="MemberCon?cmd=list2">
        <input type="checkbox" name="chkId" value="id" checked="checked">아이디
        <input type="checkbox" name="chkEmail" value="email" >이메일
        <input type="checkbox" name="chkPhone" value="phone" >전화번호
        <input type="text" name="keyword"/>
        <input type="submit" value="검색"/>
    </form>
</div>
</body>
</html>


---------------------------------------------------------------------------------











  : lib에 jar파일 복사
----------------------------------------------------------------------------------
















 : controller, Dao, vo, sqlsession생성, xml, log4j 기본파일
----------------------------------------------------------------------------------

(1) test.orm.mybatis-config.xml
;
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
   
    <!--////   접속할 DB서버에 대한 정보 설정  ////-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
                <property name="username" value="scott" />
                <property name="password" value="tiger" />
            </dataSource>
        </environment>
    </environments>
    <!--///////  sql구문이 들어있는 SQL Mapper파일 포함 ////////// -->
    <mappers>
        <mapper resource="test/orm/BoardMapper.xml" />
    </mappers>
</configuration>




(2) test.orm.BoardMapper.xml
;

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test.orm.BoardMapper">
    <!--
        where id like '%aa%'   
        where ${field} like '%'||#{keyword}||'%'
        ${}는 미리 컴파일 됨.컬럼명등은 ?로 쓸수 없으므로 ${}로 처리해야 함
     -->
    <select id="findList1" resultType="test.vo.MembersVo"
                                        parameterType="hashmap">
        select * from members
        <if test="field != null">
            where ${field} like '%'||#{keyword}||'%'
       </if>
    </select>
    <!--
        String ss =" select * from members ";
        if(id!=null){
            ss+="where id=keyword";
        }
        if(pwd!=null){
            ss+="or pwd=keyword";
        }
      이와 같이 경우
     -->
    <select id="findList2" parameterType="hashmap"
                           resultType="test.vo.MembersVo">
        select * from members
        <where>
            <!--
                where 다음에 if문에 해당하는 조건이 하나라도 있으면 select뒤에 where가 붙는다.
                or는 붙이며, 이전 항목이 없으면 자동으로 빼고 실행한다.
             -->
            <if test="id!=null">
                id=#{keyword}
           </if>
            <if test="email!=null">
               or email=#{keyword}
            </if>
            <if test="phone!=null">
               or phone=#{keyword}
            </if>
        </where>
    </select>
</mapper>




(3) test.orm.SqlSessionFactoryService
;
package test.orm;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlSessionFactoryService {
    private static SqlSessionFactory sqlSessionFactory;   
    //static멤버변수를 초기화할때는 static블록을 사용한다.(생성자x)
    static{
        try{
            InputStream is=
                    Resources.getResourceAsStream("test/orm/mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }
    }   
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}



(4) test.vo.MembersVo
; getter, setter

package test.vo;

import java.sql.Date;
public class MembersVo {
    private String id;
    private String pwd;
    private String email;
    private String phone;
    private Date regdate;
   
    public MembersVo() {}

    public MembersVo(String id, String pwd, String email, String phone,
            Date regdate) {
        super();
        this.id = id;
        this.pwd = pwd;
        this.email = email;
        this.phone = phone;
        this.regdate = regdate;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Date getRegdate() {
        return regdate;
    }

    public void setRegdate(Date regdate) {
        this.regdate = regdate;
    }
   
}



(5) test.dao.MembersDao
;

package test.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import test.orm.SqlSessionFactoryService;
import test.vo.MembersVo;

public class MembersDao {
    private SqlSessionFactory sqlSessionFactory;
    public MembersDao(){
        sqlSessionFactory=SqlSessionFactoryService.getSqlSessionFactory();
    }
    public List<MembersVo> getList(Map<String,String> map){
        SqlSession sqlSession=null;
        try{
            sqlSession=sqlSessionFactory.openSession();
            return sqlSession.selectList("findList1",map);
        }finally{
            if(sqlSession!=null) sqlSession.close();
        }
    }
    public List<MembersVo> getList1(HashMap<String,String> map){
        SqlSession sqlSession = null;
        try{
            sqlSession=sqlSessionFactory.openSession();
            return sqlSession.selectList("findList2", map);
        }finally{
            if(sqlSession!=null) sqlSession.close();
        }
    }
}



(6) test.controller.MemberController

;

package test.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.MembersDao;
import test.vo.MembersVo;

@WebServlet("/MemberCon")
public class MemberController extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String cmd=req.getParameter("cmd");
        if(cmd.equals("list1")){
            list1(req,resp);
        }else if(cmd.equals("list2")){
            list2(req,resp);
        }
    }
    // 체크박스로 선택된 조건 ( 여러개 인 경우 )
    protected void list2(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 전송된 체크박스의 value값들 얻어오기.
        // 체크가 안된것은 null이 들어온다.
        String id = req.getParameter("chkId");
        String email = req.getParameter("chkEmail");
        String phone = req.getParameter("chkPhone");
        String keyword=req.getParameter("keyword");
       
        //검색조건을 HashMap에 담기.
        HashMap<String,String> map=new HashMap<>();
        map.put("id", id);
        map.put("email", email);
        map.put("phone", phone);
        map.put("keyword", keyword);
       
        // dao를 통해서 조건에 해당하는 데이터 얻어오기.
        MembersDao dao = new MembersDao();
        List<MembersVo> list=dao.getList1(map);
       
        //결과값을 가지고 뷰페이지로 이동하기.
        req.setAttribute("list", list);
        req.getRequestDispatcher("/list2.jsp").forward(req, resp);
    }
    // 셀렉트로 선택한 조건 ( 하나 )
    protected void list1(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //검색필드 얻어오기
        String field=req.getParameter("field");
        //검색어 얻어오기
        String keyword=req.getParameter("keyword");
        //검색조건을 HashMap에 담기
        Map<String,String> map=new HashMap<>();
        map.put("field",field);
        map.put("keyword",keyword);
       
        //DAO를 통해서 DB에서 조회하기
        MembersDao dao=new MembersDao();
        List<MembersVo> list=dao.getList(map);
       
        //결과값을 가지고 뷰페이지로 이동하기
        req.setAttribute("list",list);
        req.getRequestDispatcher("/list1.jsp").forward(req, resp);
    }
}



(7) log4j.properties
; 로그 확인용

# \uC804\uC5ED \uB85C\uAE45 \uC124\uC815
log4j.rootLogger=ERROR, stdout
# MyBatis \uB85C\uAE45 \uC124\uC815...
log4j.logger.org.apache.ibatis=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=TRACE
# Console \uCD9C\uB825...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n



'WEB > MyBatis' 카테고리의 다른 글

log4j.properties  (0) 2013.05.04
3. MyBatis 사용 간한한 방명록 예제  (0) 2013.04.24
2. java 에서 mybatis 사용한 예제  (0) 2013.04.24
1. 라이브러리 다운 및 환경설정(xml)  (0) 2013.04.24

+ Recent posts