MyBatis 사용하기
DAOMyBatisBase

package common.base;

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

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

public class DAOMyBatisBase {
	   /**사용자 정의 메소드: SqlSessionFactory객체를 반환하는 메소드*/
	   public SqlSessionFactory getSqlSessionFactory() {
	      String resource="common/config/mybatis-config.xml"; 
	      //설계도 역할을 하는 파일(mybatis환경설정 파일)
	      InputStream is=null;
	      try {
	         is=Resources.getResourceAsStream(resource);
	         SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); //건축가
	         SqlSessionFactory factory=builder.build(is);
	         return factory;         
	      } catch (IOException e) {
	         e.printStackTrace();
	         return null;
	      }
	      
	   }//----------------------------
         public void close(SqlSession ses) {
         	if(ses!=null) ses.close();
         }
}

ProductDAOMyBatis

package shop.persistence;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import common.base.DAOMyBatisBase;
import shop.domain.ProductVO;

public class ProductDAOMyBatis extends DAOMyBatisBase{

	private final String NS="common.mapper.ProductMapper";
	private SqlSession ses;
	
	public List<ProductVO> selectByPspec(String pspec){
		try {
			ses=this.getSqlSessionFactory().openSession();
			List<ProductVO> arr=ses.selectList(NS+".selectByPspec",pspec);
			return arr;
		}finally {
			close(ses);
		}
	}
}

ProductMapper

<?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="common.mapper.ProductMapper">
	<!-- pspec별로 상품정보 가져오기 -->
	<select id="selectByPspec" parameterType="java.lang.String" resultType="shop.domain.ProductVO">
		select * from product where pspec=#{value}
	</select>
</mapper>

DisplayAction

package shop.controller;

import java.util.List;

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

import common.controller.AbstractAction;
import shop.domain.ProductVO;
import shop.persistence.ProductDAOMyBatis;

public class DisplayAction extends AbstractAction {

	ProductDAOMyBatis pdao = new ProductDAOMyBatis();
	@Override
	public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
		List<ProductVO> pList=pdao.selectByPspec("HIT"); 
		req.setAttribute("hitList", pList);
		this.setViewPage("mallHit.jsp");
		this.setRedirect(false);
	}

}

mallHit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<jsp:include page="/top.jsp"/>
<div class="text-left p-5">
	<h1>HIT 상품</h1>
	${hitList} 
</div>
<jsp:include page="/foot.jsp"/>

Alias
자료형의 패키지까지 기술해야 쓸 수 있지만 alias를 이용해서 간단하게 이용할 수 있다.

<?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>
	<typeAliases>
		<typeAlias type="shop.domain.ProductVO" alias="Product"/>
		<typeAlias type="shop.domain.CategoryVO" alias="Category"/>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
				<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
				<property name="username" value="myshop" />
				<property name="password" value="tiger" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="common/mapper/SampleMapper.xml" />
		<mapper resource="common/mapper/ProductMapper.xml" />
	</mappers>
</configuration>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
Ajax
DB에서 JSON 만들기

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*, ajax.book.*"%>
<jsp:useBean id="bDao" class="ajax.book.BookDAO" scope="session"/>
<%
	List<BookDTO> arr= bDao.getAllBook();
	out.println("[");
	if(arr!=null){
		for(int i=0;i<arr.size();i++){
			BookDTO b= arr.get(i);
			%>
			{
				"isbn":"<%=b.getIsbn()%>",
				"title":"<%=b.getTitle()%>",
				"publish":"<%=b.getPublish()%>",
				"price":"<%=b.getPrice()%>",
				"published":"<%=b.getPublished()%>",
				"bimage":"<%=b.getBimage()%>" 
			}
			<%
			if(i!=arr.size()-1){
				out.println(",");
			}
		}
	}
	out.println("]");
%>

라이브러리로 JOSN만들기

1) JSON 라이브러리 다운
https://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/
https://sheplim.tistory.com/entry/JSON-lib

2) 프로젝트/WEB-INF/lib 아래 7개의 jar파일을 붙여넣는다.

3) import="net.sf.json.*"
    -  Java Bean객체를 JSON형태로 변환해주는 라이브러리

jsonData5

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8" import="ajax.book.*,net.sf.json.*"%>
<%-- <%
	//객체유형
	JSONObject obj = new JSONObject();
	obj.put("isbn","112233");
	obj.put("title","JSON라이브러리 활용");
	obj.put("price","2000");
	obj.put("publish","정보문화사");
	obj.put("published","2020-07-30");
	obj.put("bimage","f.jpg");
	String str=obj.toString();
%> --%>

<%
	//배열유형
	JSONArray arr = new JSONArray();
	BookDTO b1 = new BookDTO("1122","책제목1","출판사1",25000,null,"a.jpg");
	BookDTO b2 = new BookDTO("2222","책제목2","출판사2",15000,null,"b.jpg");
	BookDTO b3 = new BookDTO("3322","책제목3","출판사3",35000,null,"c.jpg");
	
	arr.add(b1);
	arr.add(b2);
	arr.add(b3);
	
	String str = arr.toString();
%>
<%=str %>

jsonData6.jsp

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*,ajax.book.*,net.sf.json.*"%>
<jsp:useBean id="bDao" class="ajax.book.BookDAO" scope="session"/>
<%
	List<BookDTO> arr = bDao.getAllBook();
	JSONArray jsonArr = JSONArray.fromObject(arr);
	String str = jsonArr.toString();
%>
<%=str %>

 

+ Recent posts