728x90

컨트롤러 클래스에서 입력받은 객체 전달

modelMap.addAttribute("userinfo", new UserInfo()); 내용 추가

package com.iot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.iot.db.domain.UserInfo;
import com.iot.db.service.UserInfoService;

@Controller
public class IotController {

	@Autowired
	private UserInfoService service;

	@RequestMapping(value = "/hello_world.iot", method = RequestMethod.GET)
	public String hello_world(ModelMap modelMap) throws Exception {
		
		// 사용자 목록 출력
		List<UserInfo> userlist = service.listUserInfoFormData();
		modelMap.addAttribute("userlist", userlist);
		
		// 사용자 추가용 객체 설정
		modelMap.addAttribute("userinfo", new UserInfo());
		
		return "/hello_world";
	}

}

JSP에 Form 테그 추가

참고 : 쉼, 그리고 망설임 없는 마침표. :: [toby의스프링] 13장 - 스프링 @MVC #3

<%@ 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="form" uri="http://www.springframework.org/tags/form"%>

<!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>

Hello World

<h1>사용자 조회</h1>
<table border="1">
	<c:forEach items="${userlist}" var="data" varStatus="loop">
		<tr>
			<td>${data.user_id}</td>
			<td>${data.password}</td>
			<td>${data.name}</td>
			<td>${data.nickname}</td>
		</tr>
	</c:forEach>
</table>

<h1>사용자 추가</h1>
<form:form id="dataForm" name="dataForm" modelAttribute="userinfo" action="user_add.iot" method="post">
	<table border="1">
		<tr>
			<td>사용자ID</td>
			<td>
				<form:input path="user_id"/>
			</td>
		</tr>
		<tr>
			<td>암호</td>
			<td>
				<form:input path="password"/>
			</td>
		</tr>
		<tr>
			<td>사용자이름</td>
			<td>
				<form:input path="name"/>
			</td>
		</tr>
		<tr>
			<td>별명</td>
			<td>
				<form:input path="nickname"/>
			</td>
		</tr>
	</table>
	<br/>
	<input type="submit"/>
</form:form>

</body>
</html>

컨트롤러 클래스에 사용자 추가 메소드 생성

UserInfo 객체를 인자로 받음

	// 사용자 추가
	@RequestMapping(value = "/user_add.iot", method = RequestMethod.POST)
	public String user_add(UserInfo userinfo, ModelMap modelMap) throws Exception {

		service.insertUserInfo(userinfo);

		// 사용자 목록 출력
		List<UserInfo> userlist = service.listUserInfoFormData();
		modelMap.addAttribute("userlist", userlist);

		// 사용자 추가용 객체 설정
		modelMap.addAttribute("userinfo", new UserInfo());

		return "/hello_world";
	}

서비스 클래스에 메소드 추가

	public void insertUserInfo(UserInfo userInfo) {
		userInfoMapper.insertUserInfo(userInfo);
	}

Mapper 인터페이스에 메소드 추가

public void insertUserInfo(UserInfo userInfo);

Mapper XML에 Insert질의문 추가

	<!-- insertUserInfo -->
	<insert id="insertUserInfo" parameterType="com.iot.db.domain.UserInfo"
		statementType="PREPARED">
		insert into user_info(
		<trim suffixOverrides=",">
			<if test="user_id != null">user_id ,</if>
			<if test="password != null">password ,</if>
			<if test="name != null">name ,</if>
			<if test="nickname != null">nickname ,</if>
		</trim>
		) values (
		<trim suffixOverrides=",">
			<if test="user_id != null">#{user_id, jdbcType=VARCHAR} ,</if>
			<if test="password != null">#{password, jdbcType=VARCHAR} ,</if>
			<if test="name != null">#{name, jdbcType=VARCHAR} ,</if>
			<if test="nickname != null">#{nickname, jdbcType=VARCHAR} ,</if>
		</trim>
		)
	</insert>

최종 IotController.java

package com.iot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.iot.db.domain.UserInfo;
import com.iot.db.service.UserInfoService;

@Controller
public class IotController {

	@Autowired
	private UserInfoService service;

	@RequestMapping(value = "/hello_world.iot", method = RequestMethod.GET)
	public String hello_world(ModelMap modelMap) throws Exception {

		// 사용자 목록 출력
		List<UserInfo> userlist = service.listUserInfoFormData();
		modelMap.addAttribute("userlist", userlist);

		// 사용자 추가용 객체 설정
		modelMap.addAttribute("userinfo", new UserInfo());

		return "/hello_world";
	}

	// 사용자 추가
	@RequestMapping(value = "/user_add.iot", method = RequestMethod.POST)
	public String user_add(UserInfo userinfo, ModelMap modelMap) throws Exception {

		service.insertUserInfo(userinfo);

		// 사용자 목록 출력
		List<UserInfo> userlist = service.listUserInfoFormData();
		modelMap.addAttribute("userlist", userlist);

		// 사용자 추가용 객체 설정
		modelMap.addAttribute("userinfo", new UserInfo());

		return "/hello_world";
	}

}

최종 UserInfoMapper.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="com.iot.db.mapper.UserInfoMapper">

	<!-- insertUserInfo -->
	<insert id="insertUserInfo" parameterType="com.iot.db.domain.UserInfo"
		statementType="PREPARED">
		insert into user_info(
		<trim suffixOverrides=",">
			<if test="user_id != null">user_id ,</if>
			<if test="password != null">password ,</if>
			<if test="name != null">name ,</if>
			<if test="nickname != null">nickname ,</if>
		</trim>
		) values (
		<trim suffixOverrides=",">
			<if test="user_id != null">#{user_id, jdbcType=VARCHAR} ,</if>
			<if test="password != null">#{password, jdbcType=VARCHAR} ,</if>
			<if test="name != null">#{name, jdbcType=VARCHAR} ,</if>
			<if test="nickname != null">#{nickname, jdbcType=VARCHAR} ,</if>
		</trim>
		)
	</insert>

	<!-- listUserInfo -->
	<select id="listUserInfo" parameterType="map" resultType="com.iot.db.domain.UserInfo">
		select *
		  from user_info
	</select>

</mapper>
728x90
728x90

출처 : mybatis-spring – 마이바티스 스프링 연동모듈 | 매퍼 주입

DB 접속 설정(WebContent\WEB-INF\iot-datasource.xml)

데이터베이스 접속 정보(JDBC) 설정
JDBC는 각 데이터베이스 마다 제공되고 있고, 연결방식도 달라 따로 검색이 필요

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">

	<!-- ========================= Resource Definitions ========================= --> 
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
		<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/iot_db?user=iot&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull"/>
		<property name="username" value="iot"/>
		<property name="password" value="iot"/>
		<property name="maxActive" value="20"/>
		<property name="maxIdle" value="5"/>
		<property name="maxWait" value="2000"/>
		<property name="validationQuery" value="select 1"/>
		<property name="testWhileIdle" value="true"/>
		<property name="timeBetweenEvictionRunsMillis" value="7200000"/>        
	</bean>
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>	

	<tx:annotation-driven transaction-manager="transactionManager" />

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="transactionFactory">
			<bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />
		</property>
	</bean>

	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
	
</beans>

DB 접속정보 iot-servlet.xml에 추가

    <!-- ========================= Import Definitions ========================= -->
	<import resource="iot-datasource.xml" />

MyBatis Domain 패키지 생성

MyBatis Mapper 패키지 생성

MyBatis Service 패키지 생성

MyBatis 설정 파일 작성(WebContent\WEB-INF\iot-mybatis.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
    <!-- enable component scanning (beware that this does not enable mapper scanning!) -->   
    <context:component-scan base-package="com.iot.db.service" />
         
    <!-- enable autowire -->
    <context:annotation-config />
 
    <!-- enable transaction demarcation with annotations -->
    <tx:annotation-driven />
 
    <!-- define the SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.iot.db.domain" />
    </bean>
 
    <!-- scan for mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.iot.db.mapper" />
    </bean>
</beans>

user_info 예제 테이블 생성

CREATE TABLE `user_info` (
  `user_id` varchar(20) NOT NULL,
  `password` varchar(20) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `nickname` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
);

INSERT INTO `user_info` (`user_id`, `password`, `name`, `nickname`) VALUES
  ('test1', '1111', 'test1', NULL),
  ('test2', '1111', 'test2', NULL),
  ('test3', '1111', 'test3', NULL);

MyBatis Domain 클래스 생성

package com.iot.db.domain;

public class UserInfo {

	// pk
	private String user_id;

	private String password;
	private String name;
	private String nickname;

	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}

	public String getUser_id() {
		return this.user_id;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return this.password;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getNickname() {
		return this.nickname;
	}
}

MyBatis Mapper 인터페이스 생성

package com.iot.db.mapper;

import java.util.List;

import com.iot.db.domain.UserInfo;

public interface UserInfoMapper {

	public List<UserInfo> listUserInfo();

}

MyBatis Mapper 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="com.iot.db.mapper.UserInfoMapper">

	<!-- listUserInfo -->
	<select id="listUserInfo" parameterType="map" resultType="com.iot.db.domain.UserInfo">
		select *
		  from user_info
	</select>

</mapper>

MyBatis Service 클래스 생성

package com.iot.db.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iot.db.domain.UserInfo;
import com.iot.db.mapper.UserInfoMapper;

@Service
public class UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	public List<UserInfo> listUserInfoFormData() throws Exception {
		return userInfoMapper.listUserInfo();
	}

}

컨트롤러 클래스 수정

서비스로 사용자리스트를 조회해서 modelMap에 사용자리스트(userlist)를 설정

package com.iot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.iot.db.domain.UserInfo;
import com.iot.db.service.UserInfoService;

@Controller
public class IotController {

	@Autowired
	private UserInfoService service;

	@RequestMapping(value = "/hello_world.iot", method = RequestMethod.GET)
	public String hello_world(ModelMap modelMap) throws Exception {
		List<UserInfo> userlist = service.listUserInfoFormData();
		modelMap.addAttribute("userlist", userlist);
		return "/hello_world";
	}

}

hello_world.jsp에 데이터 전달

컨트롤러에서 전달받은 사용자리스트(userlist)를 반복해서 사용자정보를 출력

<%@ 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>

Hello World

<p></p>
<table border="1">
	<c:forEach items="${userlist}" var="data" varStatus="loop">
		<tr>
			<td>${data.user_id}</td>
			<td>${data.password}</td>
			<td>${data.name}</td>
			<td>${data.nickname}</td>
		</tr>
	</c:forEach>
</table>

</body>
</html>

실행결과

MyBatis 설정 파일 iot-servlet.xml에 추가

    <!-- ========================= Import Definitions ========================= -->
	<import resource="iot-mybatis.xml" />

최종 WebContent\WEB-INF\iot-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">
 
 
	<!-- 컨트롤러 package 자동으로 스프링 컨테이너 등록 -->
	<context:component-scan base-package="com.iot.controller"/>
 
    <!-- ========================= JSP View Resolver ========================= -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <!-- ========================= Import Definitions ========================= -->
	<import resource="iot-datasource.xml" />
	<import resource="iot-mybatis.xml" />
 
</beans>


728x90
728x90

QueryTool 실행해서 테이블 목록에서 테이블를 오른쪽 마우스를 선택해서 MyBatis Java Class 생성를 선택한다.

MyBatis Java Class 생성 선택

옵션 설정

MyBatis Java 패키지 경로 설정

게시판 정보 설정

테이블 타이블 : 게시판 이름으로 사용됨
Comment에 반경 버튼 : 테이블 타이틀에 작성한 내용을 선택한 테이블의 주석으로 반영(Database에 반영)
페이지 사이즈 : 게시판 리스트의 한 페이지당 개수
기본폴더 : Web 주소의 prefix

게시판 리스트 설정

View : 리스트에 출력되는 컬럼 선택
Mian : 리스트의 메인(타이틀이나 제목)이 되는 컬럼 선택
Column : 컬럼명
Title : 게시판 저장 화면에서 출력되는 타이블명
Title값 Comment에 반영 : 작성한 주석의 내용을 Database에 반영

게시판 저장 항목 선택

게시판에 저장할 컬럼을 선택한다.

OK 버튼을 선택하면 MyBatis 텝에 MyBastic 관련 Java 클래스와 xml 파일이 생성됨

 

domain 클래스(자동으로 생성된 코드)

package itg.retis.db.domain;

import java.sql.Date;
import java.sql.Timestamp;

import bluexmas.util.DateUtils;
import net.sf.json.JSONObject;

public class CodeType {

  // pk
  private String type_id;
  
  private String type_name;
  private String type_desc;
  private String is_lock;
  private String is_visible;
  
  public void setType_id(String type_id) {
    this.type_id = type_id;
  }
  public String getType_id() {
    return this.type_id;
  }
  public void setType_name(String type_name) {
    this.type_name = type_name;
  }
  public String getType_name() {
    return this.type_name;
  }
  public void setType_desc(String type_desc) {
    this.type_desc = type_desc;
  }
  public String getType_desc() {
    return this.type_desc;
  }
  public void setIs_lock(String is_lock) {
    this.is_lock = is_lock;
  }
  public String getIs_lock() {
    return this.is_lock;
  }
  public void setIs_visible(String is_visible) {
    this.is_visible = is_visible;
  }
  public String getIs_visible() {
    return this.is_visible;
  }
  public JSONObject getJSONObject() {
    JSONObject jobj = new JSONObject();
    jobj.put("type_id", this.type_id);
    jobj.put("type_name", this.type_name);
    jobj.put("type_desc", this.type_desc);
    jobj.put("is_lock", this.is_lock);
    jobj.put("is_visible", this.is_visible);
    return jobj;
  }
}

persistence 클래스(자동으로 생성된 코드)

package itg.retis.db.persistence;

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

import itg.retis.db.domain.CodeType;

public interface CodeTypeMapper {

  public CodeType selectCodeType(Map<STRING, Object> params);

  public void insertCodeType(CodeType codeType);

  public void updateCodeType(CodeType codeType);

  public void deleteCodeType(Map<STRING, Object> params);

  public int getCount();

  public List<CODETYPE> listCodeType(Map<STRING, Integer> map);

}

service 클래스(자동으로 생성된 코드)

package itg.retis.db.service;

import itg.retis.db.domain.CodeType;
import itg.retis.db.persistence.CodeTypeMapper;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CodeTypeService {

  public final static int pagerowcnt = 25;

  @Autowired
  private CodeTypeMapper codeTypeMapper;

  public CodeType selectCodeType(String typeId) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("type_id",typeId);
    return codeTypeMapper.selectCodeType(params);
  }

  public void insertCodeType(CodeType codeType) {
    codeTypeMapper.insertCodeType(codeType);
  }

  public void updateCodeType(CodeType codeType) {
    codeTypeMapper.updateCodeType(codeType);
  }

  public void deleteCodeType(String typeId) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("type_id",typeId);
    codeTypeMapper.deleteCodeType(params);
  }

  public int getCount() {
  	return codeTypeMapper.getCount();
  }

  public List<CodeType> listCodeType(int page) throws Exception {
  	Map<String, Integer> params = new HashMap<String, Integer>();
    params.put("page", page);
    params.put("pagerowcnt", pagerowcnt);
    return codeTypeMapper.listCodeType(params);
  }

}

MyBatis 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="itg.retis.db.persistence.CodeTypeMapper">

  <!-- selectCodeType -->
  <select id="selectCodeType" parameterType="map" resultType="itg.retis.db.domain.CodeType">
    select type_id
           ,type_name
           ,type_desc
           ,is_lock
           ,is_visible
      from code_type
     where type_id = #{type_id}
  </select>

  <!-- updateCodeType -->
  <update id="updateCodeType" parameterType="itg.retis.db.domain.CodeType" statementType="PREPARED">
      update code_type
        <trim prefix="SET" suffixOverrides=",">
          <if test="type_name != null">type_name = #{type_name, jdbcType=VARCHAR} ,</if>
          <if test="type_desc != null">type_desc = #{type_desc, jdbcType=VARCHAR} ,</if>
          <if test="is_lock != null">is_lock = #{is_lock, jdbcType=VARCHAR} ,</if>
          <if test="is_visible != null">is_visible = #{is_visible, jdbcType=VARCHAR} ,</if>
        </trim>
     where type_id = #{type_id}
  </update>

  <!-- insertCodeType -->
  <insert id="insertCodeType" parameterType="itg.retis.db.domain.CodeType" statementType="PREPARED">
      insert into code_type(
        <trim suffixOverrides=",">
          <if test="type_id != null">type_id ,</if>
          <if test="type_name != null">type_name ,</if>
          <if test="type_desc != null">type_desc ,</if>
          <if test="is_lock != null">is_lock ,</if>
          <if test="is_visible != null">is_visible ,</if>
        </trim>
        ) values	(
        <trim suffixOverrides=",">
          <if test="type_id != null">#{type_id, jdbcType=VARCHAR} ,</if>
          <if test="type_name != null">#{type_name, jdbcType=VARCHAR} ,</if>
          <if test="type_desc != null">#{type_desc, jdbcType=VARCHAR} ,</if>
          <if test="is_lock != null">#{is_lock, jdbcType=VARCHAR} ,</if>
          <if test="is_visible != null">#{is_visible, jdbcType=VARCHAR} ,</if>
        </trim>
        )
  </insert>

  <!-- deleteCodeType -->
  <delete id="deleteCodeType" parameterType="map" statementType="PREPARED">
      delete from code_type
     where type_id = #{type_id}
  </delete>

  <!-- getCount -->
  <select id="getCount" resultType="int">
    select count(*)
      from code_type
  </select>

  <!-- listCodeType -->
  <select id="listCodeType" parameterType="map" resultType="itg.retis.db.domain.CodeType">
    select * 
      from ( select t1.*, ceil( rownum / #{pagerowcnt}) as page 
               from (select * 
                       from code_type
                      order by type_id
                    ) t1 
           ) 
     where page = #{page} 
  </select>

</mapper>

JSONData 클래스(자동으로 생성된 코드)

package itg.retis.db.json;

import java.util.List;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import itg.retis.db.domain.CodeType;
import itg.retis.db.service.CodeTypeService;
import itg.retis.util.BeanUtils;
import bluexmas.util.DateUtils;
import bluexmas.util.DataUtils;

public class JSONCodeType implements JSONData {

  private CodeTypeService service;

  @Override
  public JSONObject getJSON(HttpServletRequest request, HttpServletResponse response) {

    service = (CodeTypeService)BeanUtils.getBean("codeTypeService");

    String subcmd = request.getParameter("subcmd");
    JSONObject jobj_data = null;
    if (subcmd.equals("add")) {
      jobj_data = getAddData(request, response);
    } else if (subcmd.equals("edit")) {
      jobj_data = getEditData(request, response);
    } else if (subcmd.equals("list")) {
      jobj_data = getListData(request, response);
    } else if (subcmd.equals("info")) {
      jobj_data = getInfoData(request, response);
    }
    return jobj_data;
  }

  public JSONObject getAddData(HttpServletRequest request, HttpServletResponse response) {

    CodeType codeType = new CodeType();
    try {
      codeType.setType_id(request.getParameter("type_id"));
      codeType.setType_name(request.getParameter("type_name"));
      codeType.setType_desc(request.getParameter("type_desc"));
      codeType.setIs_lock(request.getParameter("is_lock"));
      codeType.setIs_visible(request.getParameter("is_visible"));
    } catch (Exception e) {
      System.out.println(e.toString());
    }

    String errStr = null;
    try {
      service.insertCodeType(codeType);
    } catch (Exception e) {
      e.printStackTrace();
      errStr = "error !!! " + e.toString(); // e.toString();
    }

    JSONObject jobj_list = new JSONObject();
    jobj_list.put("err", (errStr==null ? "" : errStr));

    JSONObject jobj_data = new JSONObject();
    jobj_data.put("success", (errStr==null ? true : false));
    jobj_data.put("data", jobj_list);

    return jobj_data;
  }

  public JSONObject getEditData(HttpServletRequest request, HttpServletResponse response) {

    CodeType codeType = new CodeType();
    try {
      codeType.setType_id(request.getParameter("type_id"));
      codeType.setType_name(request.getParameter("type_name"));
      codeType.setType_desc(request.getParameter("type_desc"));
      codeType.setIs_lock(request.getParameter("is_lock"));
      codeType.setIs_visible(request.getParameter("is_visible"));
    } catch (Exception e) {
      System.out.println(e.toString());
    }

    String errStr = null;
    try {
      service.updateCodeType(codeType);
    } catch (Exception e) {
      e.printStackTrace();
      errStr = "error !!! " + e.toString(); // e.toString();
    }

    JSONObject jobj_list = new JSONObject();
    jobj_list.put("err", (errStr==null ? "" : errStr));

    JSONObject jobj_data = new JSONObject();
    jobj_data.put("success", (errStr==null ? true : false));
    jobj_data.put("data", jobj_list);

    return jobj_data;
  }

  public JSONObject getListData(HttpServletRequest request, HttpServletResponse response) {

    int pagerowcnt = 20;
    int pageIndex = 1;
    try {
      pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
    } catch (Exception e) {
      System.out.println(e.toString());
    }

    int rowCount = service.getCount();

    if (pageIndex<1) {
      pageIndex = 1;
    }

    JSONArray arrayObj = new JSONArray();

    List<CodeType> dataList = null;
    String errStr = null;
    try {
      dataList = service.listCodeType(pageIndex);
    } catch (Exception e) {
      e.printStackTrace();
      errStr = "조회오류 !!! 데이터베이스 접속정보를 확인해 보세요."; // e.toString();
    }

    if (dataList!=null) {
      for (int i=0; i<dataList.size(); i++) {
        CodeType codetype = dataList.get(i);
        arrayObj.add(codetype.getJSONObject());
      }
    }

    JSONObject jobj_list = new JSONObject();
    jobj_list.put("list", arrayObj);
    jobj_list.put("err", (errStr==null ? "" : errStr));

    JSONObject jobj_data = new JSONObject();
    jobj_data.put("success", (errStr==null ? true : false));
    if (dataList!=null) {
      jobj_data.put("currentPage", pageIndex);
      jobj_data.put("total", rowCount);
      jobj_data.put("pageSize", pagerowcnt);
    }
    jobj_data.put("data", jobj_list);

    return jobj_data;
  }

  // Info
  public JSONObject getInfoData(HttpServletRequest request, HttpServletResponse response) {

    // pk
    String type_id = null;
    try {
        type_id = request.getParameter("type_id");
    } catch (Exception e) {
      System.out.println(e.toString());
    }

    String errStr = null;
    CodeType infoObj = null;
    try {
      infoObj = service.selectCodeType(type_id);
    } catch (Exception e) {
      e.printStackTrace();
      errStr = "조회오류 !!! 데이터베이스 접속정보를 확인해 보세요."; // e.toString();
    }

    JSONObject jobj_list = new JSONObject();
    jobj_list.put("info", infoObj.getJSONObject());
    jobj_list.put("err", (errStr==null ? "" : errStr));

    JSONObject jobj_data = new JSONObject();
    jobj_data.put("success", (errStr==null ? true : false));
    jobj_data.put("data", jobj_list);

    return jobj_data;
  }
}

JSONFactory 클래스에 JSONData 클래스가 반환 되도록 코드 추가
(사용자가 코드 추가)

package itg.retis.db.json;

public class JSONFactory {
	
	public static JSONData getJSONData(String cmd) {
		
		System.out.println("JSONFactory = " + cmd);

		if (cmd.equals("CodeType")) {   // 1 <-- 여기 두줄 추가
			return new JSONCodeType();  // 2
		} else {
			return new JSONSample();	
		}
	}
}

json 서블릿 호출하여 json data가 올바르게 전달되는지 확인

Sencha 텝에서 게시판 JavaScript 확인

code_type_list.js 소스 (자동으로 생성된 코드)

Ext.ns("ns_code_type_list");

ns_code_type_list.init = function(){

    var dataList;
    var dataStore;
    var pagingToolbar;
    var writeToolbar;

    Ext.regModel('dataModel', {
        fields: ['type_id','type_name','type_desc','is_lock','is_visible']
    });

    dataStore = new Ext.data.Store({
        model: 'dataModel',
        jsonData: [ currentPage = 1 ],
        data: [ ]
    });

    dataList = new Ext.List({
        title: 'CodeType목록',
        store: dataStore,
        scroll: false, // <-- 여기 중요
        layout:'fit', // <-- 여기 중요
        blockRefresh:true,
        onItemDisclosure: {
            handler: function(record, btn, index) {
                //alert(record.get('no'));
                ns_code_type_write.init();
                ns_code_type_write.panel.getInfoData(record.get('type_id'));
                main.MainPanel.setActiveItem(ns_code_type_write.panel, "slide");
            }
        },
        itemTpl:'{type_id} / {type_name} / {type_desc} / {is_lock} / {is_visible}'
    });

    function setList(aJsonData) {
        dataStore = new Ext.data.Store({
            model : 'dataModel',
            data : aJsonData.data.list,
            clearOnPageLoad : true,
            jsonData : aJsonData,
            previousPage: function() {
            	this.jsonData.currentPage = this.jsonData.currentPage - 1;
            	ns_code_type_list.panel_list.getList();
            },
            nextPage: function() {
            	this.jsonData.currentPage = this.jsonData.currentPage + 1;
            	ns_code_type_list.panel_list.getList();
            },
            loadPage: function(page) {
            	this.jsonData.currentPage =  page;
            	ns_code_type_list.panel_list.getList();
        	}
        });
        pagingToolbar.store = dataStore;
        pagingToolbar.handleStoreLoadSH(dataStore, true);

        dataList.bindStore(dataStore);

        ns_code_type_list.panel_list.scroller.scrollTo({
            x: 0,
            y: 0
        });
    };

    pagingToolbar = new Ext.ux.touch.PagingToolbar({
        ui: "charcoal",
        store : dataStore
    });

    writeToolbar = new Ext.Toolbar({
    		ui: "charcoal",
        items: [
        	{ xtype: 'spacer' },
          { text: '등록',
            handler:function() {
              ns_code_type_write.init();
           	 main.MainPanel.setActiveItem(ns_code_type_write.panel, "slide");
          	 }
          }
        ]
    });

    //
    dataStore.on('load', pagingToolbar.handleStoreLoad, pagingToolbar);

    ns_code_type_list.panel_list = new Ext.Panel({
        useCurrentLocation: true,
        scroll:'vertical',
        cardSwitchAnimation:"cube",
        getList:function()
        {
            Ext.Ajax.request({
                url: 'json',
                params : {
                    cmd : 'CodeType',
                    subcmd : 'list',

                    pageIndex : dataStore.jsonData.currentPage
                },
                success: function(response, opts) {
                    //console.log(response.responseText);
                    var JsonData = JSON.parse(response.responseText);
                    //console.log(JsonData);
                    if(JsonData.data.err == "") {
                        setList(JsonData);
                    } else {
                        alert(JsonData.data.err);
                    }
                }
            });
        },
        items:
        [{
            xtype: 'fieldset',
            instructions: 'CodeType목록 입니다. ',
            defaults: {
                labelAlign: 'left'
            },
            items: [
            	dataList,
            	pagingToolbar,
            	writeToolbar
            ]
        }]
    });
}

code_type_write.js 소스 (자동으로 생성된 코드)

Ext.ns("ns_code_type_write");

ns_code_type_write.init = function() {

  var m_subcmd = 'add';
  var m_type_id = "";

  ns_code_type_write.panel = new Ext.form.FormPanel({
    scroll : 'vertical',
    standardSubmit : false,
    title : 'Guestbook',
    items : [{
      xtype : 'fieldset',
      id : 'code_type_form',
      title : '코드타입 등록',
      // instructions: 'Please complete the information.',
      defaults : {
        labelAlign : 'left',
        labelWidth : '120'
      },
      items : [
      {
        xtype : 'textfield',
        id : 'type_id',
        label : '타입아이디',
        useClearIcon : true
      }
      , {
        xtype : 'textfield',
        id : 'type_name',
        label : '타입명',
        useClearIcon : true
      }
      , {
        xtype : 'textfield',
        id : 'type_desc',
        label : '설명',
        useClearIcon : true
      }
      , {
        xtype : 'textfield',
        id : 'is_lock',
        label : '잠금여부',
        useClearIcon : true
      }
      , {
        xtype : 'textfield',
        id : 'is_visible',
        label : '보여짐여부',
        useClearIcon : true
      }
            ]
    },
    {
      layout : {
        type : 'hbox',
        pack : 'center'
      },
      flex : 2,
      style : 'margin: .5em;',
      items : [ {
        xtype : 'button',
        ui : 'decline-round',
        id : 'btnAdd',
        name : 'btnAdd',
        handler : function() {
          Ext.Ajax.request({
            url: 'json',
            params : {
              cmd : 'CodeType',
              subcmd : m_subcmd,

              type_id : Ext.getCmp("type_id").getValue(),
              type_name : Ext.getCmp("type_name").getValue(),
              type_desc : Ext.getCmp("type_desc").getValue(),
              is_lock : Ext.getCmp("is_lock").getValue(),
              is_visible : Ext.getCmp("is_visible").getValue(),
            },
            success : function(response, opts) {
              //console.log(Ext.getCmp("login.user_id"));
              //console.log(response.responseText + Ext.getCmp("login.user_id").value);
              var JsonData = JSON.parse(response.responseText);
              console.log(JsonData);
              if (JsonData.data.err == "") {
                if (JsonData.data.result == "N") {
                  alert(JsonData.data.err);
                } else {
                  alert('등록이 완료 되었습니다.');
                  ns_code_type_list.panel_list.getList();
                  main.MainPanel.setActiveItem(ns_code_type_list.panel_list, "slide");
                }
              } else {
                alert(JsonData.data.err);
              }
            }
          });
        },
        text : '작성완료'
      } ]
    }],

    getInfoData : function(aTYPE_ID) {
      Ext.getCmp("code_type_form").setTitle('코드타입 수정');
      Ext.getCmp("btnAdd").setText('정보수정');
      m_subcmd = "edit";
      // alert('no = ' + ano);
      m_TYPE_ID = aTYPE_ID;
      Ext.Ajax.request({
        url: 'json',
        params : {
          cmd : 'CodeType'
          ,subcmd : 'info'
          ,type_id : aTYPE_ID
        },
        success : function(response, opts) {
          //console.log(response.responseText);
          var JsonData = JSON.parse(response.responseText);
          //console.log(JsonData);
          if (JsonData.data.err == "") {
            Ext.getCmp("type_id").setValue(JsonData.data.info.type_id);
            Ext.getCmp("type_name").setValue(JsonData.data.info.type_name);
            Ext.getCmp("type_desc").setValue(JsonData.data.info.type_desc);
            Ext.getCmp("is_lock").setValue(JsonData.data.info.is_lock);
            Ext.getCmp("is_visible").setValue(JsonData.data.info.is_visible);
          } else {
            alert(JsonData.data.err);
          }
        }
      });
    }
  });
}

확인 - 리스트

 

확인 - 저장

확인 - 조회 및 수정

마무리  

이 툴을 만들 당시 Sencha 2가 나왔기 때문에 현재 버전은 Sencha 1 버전으로만 생성이 되네요.
시간이 된다면 Sencha2 지원과 json 데이터 호출 ajax 부분도 php로 구현하고 하고 싶네요.

php json 호출 템플릿을 제공 하실분이 있으면 언제든지 연락주세요.

728x90

+ Recent posts