Spring - 게시판 작성

Programming/Java 2016.02.27 03:13 Posted by 파란크리스마스

출처 : 개발하는 씽매려기 :: MyBatis] 쿼리에서 특정 문자 제거 (if 사용시)
MyBatis – MyBatis 3 | 동적 SQL

Domain 객체

com.iot.domain.DepartmentsDomain 클래스

package com.iot.domain;

import net.sf.json.JSONObject;

public class DepartmentsDomain {

	// pk
	private int department_id;

	private String department_name;
	private int manager_id;
	private int location_id;

	private String delete_flag = "N";

	public void setDepartment_id(int department_id) {
		this.department_id = department_id;
	}

	public int getDepartment_id() {
		return this.department_id;
	}

	public void setDepartment_name(String department_name) {
		this.department_name = department_name;
	}

	public String getDepartment_name() {
		return this.department_name;
	}

	public void setManager_id(int manager_id) {
		this.manager_id = manager_id;
	}

	public int getManager_id() {
		return this.manager_id;
	}

	public void setLocation_id(int location_id) {
		this.location_id = location_id;
	}

	public int getLocation_id() {
		return this.location_id;
	}

	public String getDelete_flag() {
		return delete_flag;
	}

	public void setDelete_flag(String delete_flag) {
		this.delete_flag = delete_flag;
	}

	public JSONObject getJSONObject() {
		JSONObject jobj = new JSONObject();
		jobj.put("department_id", this.department_id);
		jobj.put("department_name", this.department_name);
		jobj.put("manager_id", this.manager_id);
		jobj.put("location_id", this.location_id);
		return jobj;
	}

}

Domain 목록 객체

com.iot.domain.DepartmentsList 클래스

package com.iot.domain;

import java.util.List;

import com.iot.util.FormBase;

public class DepartmentsList extends FormBase {

	public final static String CMD_SELECT = "select";

	public final static String CMD_DELETE = "delete";

	private String command = CMD_SELECT;

	private List<DepartmentsDomain> datas;

	public String getCommand() {
		return command;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	public List<DepartmentsDomain> getDatas() {
		return datas;
	}

	public void setDatas(List<DepartmentsDomain> datas) {
		this.datas = datas;
	}
}

Mapper 인터페이스

package com.iot.persistence;

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

import com.iot.domain.DepartmentsDomain;

public interface DepartmentsMapper {

	public DepartmentsDomain selectDepartments(Map<String, Object> params);

	public void insertDepartments(DepartmentsDomain departments);

	public void updateDepartments(DepartmentsDomain departments);

	public void deleteDepartments(Map<String, Object> params);

	public int getCount();

	public int getCountFormData(Map<String, Object> params);

	public List<DepartmentsDomain> listDepartments(Map<String, Object> map);

}

Mapper SQL Map 파일

<?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.persistence.DepartmentsMapper">
	
	<!-- selectDepartments -->
	<select id="selectDepartments" parameterType="map" resultType="com.iot.domain.DepartmentsDomain">
		select department_id
		       ,department_name
		       ,manager_id
		       ,location_id
		  from departments
		 where department_id = #{department_id}
	</select>
	
	<!-- updateDepartments -->
	<update id="updateDepartments" parameterType="com.iot.domain.DepartmentsDomain" statementType="PREPARED">
		update departments
		  <trim prefix="SET" suffixOverrides=",">
		    <if test="department_name != null">department_name = #{department_name, jdbcType=VARCHAR} ,</if>
		    <if test="manager_id != null">manager_id = #{manager_id, jdbcType=INTEGER} ,</if>
		    <if test="location_id != null">location_id = #{location_id, jdbcType=INTEGER} ,</if>
		  </trim>
		where department_id = #{department_id}
	</update>
	
	<!-- insertDepartments -->
	<insert id="insertDepartments" parameterType="com.iot.domain.DepartmentsDomain" statementType="PREPARED">
		insert into departments(
		<trim suffixOverrides=",">
		  <if test="department_name != null">department_name ,</if>
		  <if test="manager_id != null">manager_id ,</if>
		  <if test="location_id != null">location_id ,</if>
		</trim>
		) values	(
		<trim suffixOverrides=",">
		  <if test="department_name != null">#{department_name, jdbcType=VARCHAR} ,</if>
		  <if test="manager_id != null">#{manager_id, jdbcType=INTEGER} ,</if>
		  <if test="location_id != null">#{location_id, jdbcType=INTEGER} ,</if>
		</trim>
		)
	</insert>
	
	<!-- deleteDepartments -->
	<delete id="deleteDepartments" parameterType="map" statementType="PREPARED">
		delete from departments
		 where department_id = #{department_id}
	</delete>
	
	<!-- getCount -->
	<select id="getCount" resultType="int">
		select count(*)
		  from departments
	</select>

	<!-- getCountFormData -->
	<select id="getCountFormData" parameterType="map" resultType="int">
		select count(*)
		  from departments
		  <trim prefix="WHERE" prefixOverrides="AND |OR ">
		    <if test="searchstr != null">and department_name like '%${searchstr}%'</if>
		  </trim>
	</select>
	
	<!-- listDepartments -->
	<select id="listDepartments" parameterType="map" resultType="com.iot.domain.DepartmentsDomain">
		select * 
		  from departments
		  <trim prefix="WHERE" prefixOverrides="AND |OR ">
		    <if test="searchstr != null">and department_name like '%${searchstr}%'</if>
		  </trim>
		  <if test="defaultSize != null">
		  	limit #{defaultSize} offset #{offset}
		  </if>
	</select>

</mapper>

MyBatis 동적SQL

맨 끝에 있는 콤마(,)를 제거하는 경우

문장의 마지막 단어가 suffixOverrides단어( 콤마(,) )인 경우 제거하고, 문장의 시작은 prefix단어(SET)를 붙입니다.

		  <trim prefix="SET" suffixOverrides=",">
		    <if test="department_name != null">department_name = #{department_name, jdbcType=VARCHAR} ,</if>
		    <if test="manager_id != null">manager_id = #{manager_id, jdbcType=INTEGER} ,</if>
		    <if test="location_id != null">location_id = #{location_id, jdbcType=INTEGER} ,</if>
		  </trim>

맨 앞에 있는 연산자를(AND 또는 OR) 제거하는 경우

문장의 시작 단어가 prefixOverrides 단어(AND 또는 OR)인 경우 prefixOverrides 단어를 제거하고 prefix단어(WHERE)를 붙입니다.

		  <trim prefix="WHERE" prefixOverrides="AND |OR ">
		    <if test="searchstr != null">and department_name like '%${searchstr}%'</if>
		  </trim>

Service 객체

package com.iot.service;

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

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

import com.iot.domain.DepartmentsDomain;
import com.iot.domain.DepartmentsList;
import com.iot.persistence.DepartmentsMapper;

@Service
public class DepartmentsService {

	public final static int pagerowcnt = 10;

	@Autowired
	private DepartmentsMapper departmentsMapper;

	public DepartmentsDomain selectDepartments(int departmentId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("department_id", departmentId);
		return departmentsMapper.selectDepartments(params);
	}

	public void insertDepartments(DepartmentsDomain departments) {
		departmentsMapper.insertDepartments(departments);
	}

	public void updateDepartments(DepartmentsDomain departments) {
		departmentsMapper.updateDepartments(departments);
	}

	public void deleteDepartments(int departmentId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("department_id", departmentId);
		departmentsMapper.deleteDepartments(params);
	}

	public void deleteDepartments(Map<String, Object> params) {
		departmentsMapper.deleteDepartments(params);
	}

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

	public int getCountFormData(DepartmentsList formData) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("searchstr", formData.getSearchString());
		return departmentsMapper.getCountFormData(params);
	}

	public List<DepartmentsDomain> listDepartments(int page) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		if (page>0) {
			params.put("defaultSize", pagerowcnt);
			params.put("offset", pagerowcnt * (page - 1));
		}
		return departmentsMapper.listDepartments(params);
	}

	public List<DepartmentsDomain> listDepartmentsFormData(DepartmentsList formData) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("defaultSize", pagerowcnt);
		params.put("offset", pagerowcnt * (formData.getPage() - 1));
		params.put("searchstr", formData.getSearchString());
		return departmentsMapper.listDepartments(params);
	}

}

Controller 클래스

package com.iot.ui.controller;

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

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.domain.DepartmentsDomain;
import com.iot.domain.DepartmentsList;
import com.iot.service.DepartmentsService;

@Controller
public class DepartmentsController {

	@Autowired
	private DepartmentsService service;

	private void list(DepartmentsList formData, ModelMap modelMap) throws Exception {
		int record_count = 0;

		if (formData.getSearchString()!=null && formData.getSearchString().length()>0) {
			record_count = service.getCountFormData(formData);
		}

		//
		if (record_count==0) {
			record_count = service.getCount();
		}

		formData.setPageSize(DepartmentsService.pagerowcnt);
		formData.setTotalCount(record_count);

		System.out.println("record_count = " + record_count);

		List<DepartmentsDomain> list = service.listDepartmentsFormData(formData);

		formData.setDatas(list);
		modelMap.addObject("formData", formData);
		modelMap.addObject("page", formData.getPage());
	}

	@RequestMapping(value="/departments_list.iot", method=RequestMethod.GET)
	public String departments_list(ModelMap modelMap) throws Exception {
		DepartmentsList formData = new DepartmentsList();
		formData.setPage(1);
		formData.setSearchString("");

		list(formData, modelMap);

		return "/departments_list";
	}

	@RequestMapping(value="/departments_list.iot", method=RequestMethod.POST)
	public String departments_list(
			@RequestParam("command") String command, 
			DepartmentsList formData, 
			ModelMap modelMap) throws Exception 
	{

		if (command.equals("delete")) {
			List<DepartmentsDomain> list = formData.getDatas();
			for (int i=0; i<list.size(); i++) {
				DepartmentsDomain departments = list.get(i);
				if (departments.getDelete_flag()!=null && departments.getDelete_flag().equals("Y")) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("department_id",departments.getDepartment_id());
					service.deleteDepartments(params);
				}
			}
		}

		list(formData, modelMap);

		return "/departments_list";
	}
	@RequestMapping(value="/departments_view.iot", method=RequestMethod.POST)
	public String departments_view(
			@RequestParam("department_id") int department_id, 
			ModelMap modelMap) throws Exception 
	{
		DepartmentsDomain data = service.selectDepartments(department_id);
		modelMap.addObject("data", data);
		modelMap.addObject("command", "view");
		return "/departments_add";
	}

	@RequestMapping(value="/departments_add.iot", method=RequestMethod.GET)
	public String departments_add(ModelMap modelMap) throws Exception {
		DepartmentsDomain data = new DepartmentsDomain();
		modelMap.addObject("data", data);
		modelMap.addObject("command", "add");
		return "/departments_add";
	}

	@RequestMapping(value="/departments_add.iot", method=RequestMethod.POST)
	public String departments_add_process(
			@RequestParam("command") String command, 
			DepartmentsDomain data, 
			ModelMap modelMap) throws Exception 
	{
		if (command.equals("add")) {
			service.insertDepartments(data);
		} else {
			service.updateDepartments(data);
		}
		return "redirect:/departments_list.iot";
	}

}

부서 목록 조회 JSP

departments_list.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<HTML>
<HEAD>
<TITLE>부서목록</TITLE>
<META http-equiv="Content-Type"  content="text/html; charset=UTF-8">
<LINK rel="stylesheet" href="<c:url value="/resources/css/iot.css"/>" type="text/css">
<SCRIPT type="text/javascript">
function listPage(goto_page) {
	var obj = document.selectForm;
	obj.page.value = goto_page;
	obj.action = '<c:url value="/departments_list.iot"/>';
	obj.method = 'post';
	obj.submit();
}

function dataAdd() {
	var obj = document.selectForm;
	obj.action = '<c:url value="/departments_add.iot"/>';
	obj.method = 'get';
	obj.submit();
}

function viewResultDetail(department_id) {
	var obj = document.detailForm;
	obj.department_id.value = department_id;
	obj.submit();
}

function deleteContract() {
	ret = confirm("정말로 삭제 하시겠습니까?");
	if (ret) {
	  var obj = document.selectForm;
	  obj.command.value = 'delete';
	  obj.submit();
	}
}

function switchCheckbox(checked, objCheckbox) {
	if (objCheckbox != null) {
		if (objCheckbox.length == null) {
			if (!objCheckbox.disabled) {
				objCheckbox.checked = checked;
			}
		} else {
			for (var i = 0; i < objCheckbox.length; i++) {
				if (!objCheckbox[i].disabled) {
					objCheckbox[i].checked = checked;
				}
			}
		}
	}
}
</SCRIPT>
</HEAD>

<body>
<!-- body style="margin:0"  -->

<form name="detailForm" action="<c:url value="/departments_view.iot"/>" method="post">
  <INPUT type="hidden" name="department_id">
</form>

<!-- div id="mailListDiv" class="division">
<div class="divList" id="divList" -->

<form:form modelAttribute="formData" name="selectForm" method="POST">
  <form:hidden path="command" value="select"/>
	<form:hidden path="pageSize"/>
	<form:hidden path="page"/>
					
  <table width="100%">
    <tr>
      <td><DIV style="font: bold 16pt">부서 목록</DIV></td>
      <td style="text-align: 'right';" align="right" valign="bottom">
        <input type="button" value="등록" onclick="javascript:dataAdd();"/> 
        <input type="button" onClick="javascript:deleteContract();" value="삭제"/>
      </td>
    </tr>
  </table>
  <br>

  <TABLE width="100%" cellspacing="1" cellpadding="3" class="table" style="table-layout: fixed;">
    <COLGROUP>
      <COL width="30px">
      <COL width="100px">
      <COL width="100px">
      <COL width="100px">
      <COL width="100px">
    </COLGROUP>
    <TR class="header_tr">
      <TD><INPUT type="checkbox" onclick="JavaScript:switchCheckbox(this.checked, document.selectForm.chk_id)"/></TD>
      <TD>부서ID</TD>
      <TD>부서명</TD>
      <TD>관리자ID</TD>
      <TD>위치ID</TD>
    </TR>
    <c:forEach items="${formData.datas}" var="data" varStatus="loop">
      <form:hidden path="datas[${loop.index}].department_id"/>
      <tr class="link_cell">
        <td align="center"><form:checkbox path="datas[${loop.index}].delete_flag" value="Y" id="chk_id"/></td>
        <td onclick="javascript:viewResultDetail(${data.department_id});">${data.getDepartment_id()}</td>
        <td onclick="javascript:viewResultDetail(${data.department_id});">${data.getDepartment_name()}</td>
        <td onclick="javascript:viewResultDetail(${data.department_id});">${data.getManager_id()}</td>
        <td onclick="javascript:viewResultDetail(${data.department_id});">${data.getLocation_id()}</td>
      </tr>
    </c:forEach>
  </TABLE>

	<div id="normalPagingNav" class="paginate">
		<div style="display:inline-block;width:100%;">
			<div class="pagination">
				${formData.pageLink}
			</div><!-- //paging01 -->
		</div>
		<table>
		  <tr>
		    <td><form:input path="searchString" size="35"/></td>
		    <td><input type="submit" value="조희" /></td>
		  </tr>
		</table>
	 </div>
</form:form>

</body>
</html>

부서 등록 및 조회, 수정 JSP

departments_add.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<c:url value="/departments_add.iot" var="form_url"/>

<HTML>
<HEAD>
<TITLE>부서</TITLE>
<META http-equiv="Content-Type"  content="text/html; charset=UTF-8">
<LINK rel="stylesheet" href="<c:url value="/resources/css/iot.css"/>"   type="text/css">
</HEAD>

<body>

<form:form id="dataForm" name="dataForm" modelAttribute="data" action="${form_url}" method="post">
<form:hidden path="department_id" />
<INPUT type="hidden" name="command" value="${command}">

<table width="710" border="0" cellspacing="0" cellpadding="0">
	<tr>
		<td align="center" style="padding-top:25px;">
			<table width="680" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td><DIV style="font: bold 16pt">부서등록</DIV></td>
					<td></td>
				</tr>
				<tr>
					<td height="10" colspan="2"></td>
				</tr>
				<tr>
					<td colspan="2" bgcolor="f5f5f5" style="padding:10px;">
						<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
							<tr>
								<td style="padding:25px;">
									<table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="eaeaea">
										<tr>
											<td width="25%" height="28" align="right" bgcolor="f8f8f8" class="dotum11px" style="padding:3px 5px 0 10px;">부서명</td>
											<td bgcolor="#FFFFFF" style="padding:0 0 0 10px;">
												<form:input path="department_name" class="border" size="50" maxlength="50" />
											</td>
										</tr>
										<tr>
											<td width="25%" height="28" align="right" bgcolor="f8f8f8" class="dotum11px" style="padding:3px 5px 0 10px;">관리자ID</td>
											<td bgcolor="#FFFFFF" style="padding:0 0 0 10px;">
												<form:input path="manager_id" class="border" size="50" maxlength="50" />
											</td>
										</tr>
										<tr>
											<td width="25%" height="28" align="right" bgcolor="f8f8f8" class="dotum11px" style="padding:3px 5px 0 10px;">위치ID</td>
											<td bgcolor="#FFFFFF" style="padding:0 0 0 10px;">
												<form:input path="location_id" class="border" size="50" maxlength="50" />
											</td>
										</tr>
									</table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td colspan="2"> </td>
				</tr>
				<tr>
					<td colspan="2" align="center">
						<input type="submit" value="등록" />
					</td>
				</tr>
			</table>
		</td>
	</tr>
</table>
</form:form>
</body>

</html>
출처 : Get to Spring ApplicationContext from everywhere (The clean way)

Spring 컨터이너안의 Bean 객체를 어디에서든 얻어오는 Tip

ApplicationContextProvider 클래스

ApplicationContextProvider 클래스를 만들고, 이 클래스는 ApplicationContextAware 인터페이스를 구현합니다.

package com.iot.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware {
	
	private static ApplicationContext ctx = null;

	public static ApplicationContext getApplicationContext() {
		return ctx;
	}

	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		this.ctx = ctx;
	}

}

ApplicationContext 환경파일 추가

이 Bean을 ApplicationContext 구성 파일에 설정합니다.

	<bean id="applicationContextProvider" class="com.iot.util.ApplicationContextProvider"></bean>

BeanUtils 클래스

사용하기 쉽게 유틸클래스를 만듭니다.

package com.iot.util;

import org.springframework.context.ApplicationContext;

public class BeanUtils {
	
	public static Object getBean(String beanId) {
		
		ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();

		if( applicationContext == null ) {
			throw new NullPointerException("Spring의 ApplicationContext초기화 안됨");
		}
		
		/*
		String[] names = applicationContext.getBeanDefinitionNames();
		for (int i=0; i<names.length; i++) {
			System.out.println(names[i]);
		}
		*/
		
		return applicationContext.getBean(beanId);
	}
}

	DepartmentsService service = (DepartmentsService) BeanUtils.getBean("departmentsService");


MyBatis

Programming/Java 2016.02.20 02:01 Posted by 파란크리스마스

출처 : 

환경설정

MyBatis 관련 환경파일 import

iot-servlet.xml 파일에 아래 내용 추가

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

JDBC 설정

iot-datasource.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">

	<!-- ========================= 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:5614/iot_db?user=HR&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull"/>
		<property name="username" value="HR"/>
		<property name="password" value="111111"/>
		<property name="maxActive" value="20"/>
		<property name="maxIdle" value="5"/>
		<property name="maxWait" value="2000"/>
		<!-- validationQuery:유효 검사용 쿼리( 1개 이상의 row를 반환하는 쿼리를 넣어주면 된다. ) -->
		<property name="validationQuery" value="select 1"/>
		<!-- testWhileIdle:컨넥션이 놀고 있을때 -_-; validationQuery 를 이용해서 유효성 검사를 할지 여부. -->
		<property name="testWhileIdle" value="true"/>
		<!-- timeBetweenEvictionRunsMillis:해당 밀리초마다 validationQuery 를 이용하여 유효성 검사 진행 -->
		<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>

MyBatis 설정

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.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.domain" />
    </bean>

    <!-- scan for mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.iot.persistence" />
    </bean>
</beans>

Domain 객체

출처 : 혹시 DTO(VO) 작성하시나요? - SLiPP

프레임워크마다 VO, Command, Domain, DTO, TO 여러가지 이름으로 부르지만, MyBatis에서는 Domain이라고 부르고, Domain객체는 데이터베이스에서 조회된 데이터를 객체에 담아서 jsp에 실어 사용자에게 전달합니다.

package com.iot.domain;

import java.sql.Timestamp;

public class TbluserDomain {

	// pk
	private int seq;

	private String user_id;
	private String pass;
	private String nick;
	private Timestamp joindate;
	private String email;
	private String sex;

	private String delete_flag = "N";

	public void setSeq(int seq) {
		this.seq = seq;
	}

	public int getSeq() {
		return this.seq;
	}

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

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

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getPass() {
		return this.pass;
	}

	public void setNick(String nick) {
		this.nick = nick;
	}

	public String getNick() {
		return this.nick;
	}

	public void setJoindate(Timestamp joindate) {
		this.joindate = joindate;
	}

	public Timestamp getJoindate() {
		return this.joindate;
	}

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

	public String getEmail() {
		return this.email;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getSex() {
		return this.sex;
	}

	public String getDelete_flag() {
		return delete_flag;
	}

	public void setDelete_flag(String delete_flag) {
		this.delete_flag = delete_flag;
	}
}

Mapper 객체

출처 : mybatis-spring ? 마이바티스 스프링 연동모듈 | 매퍼 주입
MyBatis - MyBatis 3 | Mapper XML 파일

  • cache - 해당 명명공간을 위한 캐시 설정
  • cache-ref - 다른 명명공간의 캐시 설정에 대한 참조
  • resultMap - 데이터베이스 결과데이터를 객체에 로드하는 방법을 정의하는 요소
  • sql - 다른 구문에서 재사용하기 위한 SQL 조각
  • insert - 매핑된 INSERT 구문.
  • update - 매핑된 UPDATE 구문.
  • delete - 매핑된 DELEETE 구문.
  • select - 매핑된 SELECT 구문.

Mapper 인터페이스

package com.iot.persistence;

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

import com.iot.domain.TbluserDomain;

public interface TbluserMapper {

	public TbluserDomain selectTbluser(Map<String, Object> params);

	public void insertTbluser(TbluserDomain tbluser);

	public void updateTbluser(TbluserDomain tbluser);

	public void deleteTbluser(Map<String, Object> params);

	public int getCount();

	public int getCountFormData(Map<String, Object> params);

	public List<TbluserDomain> listTbluser(Map<String, Object> map);

}

Mapper SQL Map 파일

  • cache - 해당 명명공간을 위한 캐시 설정
  • cache-ref - 다른 명명공간의 캐시 설정에 대한 참조
  • resultMap - 데이터베이스 결과데이터를 객체에 로드하는 방법을 정의하는 요소
  • sql - 다른 구문에서 재사용하기 위한 SQL 조각
  • insert - 매핑된 INSERT 구문.
  • update - 매핑된 UPDATE 구문.
  • delete - 매핑된 DELEETE 구문.
  • select - 매핑된 SELECT 구문.
<?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.persistence.TbluserMapper">

  <!-- selectTbluser -->
  <select id="selectTbluser" parameterType="map" resultType="com.iot.domain.TbluserDomain">
    select seq
           ,user_id
           ,pass
           ,nick
           ,joindate
           ,email
           ,sex
      from tbluser
     where seq = #{seq}
  </select>

  <!-- updateTbluser -->
  <update id="updateTbluser" parameterType="com.iot.domain.TbluserDomain" statementType="PREPARED">
      update tbluser
        <trim prefix="SET" suffixOverrides=",">
          <if test="user_id != null">user_id = #{user_id, jdbcType=VARCHAR} ,</if>
          <if test="pass != null">pass = #{pass, jdbcType=VARCHAR} ,</if>
          <if test="nick != null">nick = #{nick, jdbcType=VARCHAR} ,</if>
          <if test="joindate != null">joindate = #{joindate, jdbcType=TIMESTAMP} ,</if>
          <if test="email != null">email = #{email, jdbcType=VARCHAR} ,</if>
          <if test="sex != null">sex = #{sex, jdbcType=VARCHAR} ,</if>
        </trim>
     where seq = #{seq}
  </update>

  <!-- insertTbluser -->
  <insert id="insertTbluser" parameterType="com.iot.domain.TbluserDomain" statementType="PREPARED">
      insert into tbluser(
        <trim suffixOverrides=",">
          <if test="seq != null">seq ,</if>
          <if test="user_id != null">user_id ,</if>
          <if test="pass != null">pass ,</if>
          <if test="nick != null">nick ,</if>
          <if test="joindate != null">joindate ,</if>
          <if test="email != null">email ,</if>
          <if test="sex != null">sex ,</if>
        </trim>
        ) values	(
        <trim suffixOverrides=",">
          <if test="seq != null">#{seq, jdbcType=decimal} ,</if>
          <if test="user_id != null">#{user_id, jdbcType=VARCHAR} ,</if>
          <if test="pass != null">#{pass, jdbcType=VARCHAR} ,</if>
          <if test="nick != null">#{nick, jdbcType=VARCHAR} ,</if>
          <if test="joindate != null">#{joindate, jdbcType=TIMESTAMP} ,</if>
          <if test="email != null">#{email, jdbcType=VARCHAR} ,</if>
          <if test="sex != null">#{sex, jdbcType=VARCHAR} ,</if>
        </trim>
        )
  </insert>

  <!-- deleteTbluser -->
  <delete id="deleteTbluser" parameterType="map" statementType="PREPARED">
      delete from tbluser
     where seq = #{seq}
  </delete>

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

  <!-- getCountFormData -->
  <select id="getCountFormData" parameterType="map" resultType="int">
    select count(*)
      from tbluser
      <trim prefix="WHERE" prefixOverrides="AND |OR ">
        <if test="searchstr != null">and user_id like '%${searchstr}%'</if>
      </trim>
  </select>

  <!-- listTbluser -->
  <select id="listTbluser" parameterType="map" resultType="com.iot.domain.TbluserDomain">
    select * 
      from tbluser
      <trim prefix="WHERE" prefixOverrides="AND |OR ">
        <if test="searchstr != null">and user_id like '%${searchstr}%'</if>
      </trim>
     limit #{defaultSize} offset #{offset}
  </select>

</mapper>

Service 객체

package com.iot.service;

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

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

import com.iot.domain.TbluserDomain;
import com.iot.persistence.TbluserMapper;

@Service
public class TbluserService {

  public final static int pagerowcnt = 25;

  @Autowired
  private TbluserMapper tbluserMapper;

  public TbluserDomain selectTbluser(double seq) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("seq",seq);
    return tbluserMapper.selectTbluser(params);
  }

  public void insertTbluser(TbluserDomain tbluser) {
    tbluserMapper.insertTbluser(tbluser);
  }

  public void updateTbluser(TbluserDomain tbluser) {
    tbluserMapper.updateTbluser(tbluser);
  }

  public void deleteTbluser(double seq) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("seq",seq);
    tbluserMapper.deleteTbluser(params);
  }

  public void deleteTbluser(Map<String, Object> params) {
    tbluserMapper.deleteTbluser(params);
  }

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

  public List<TbluserDomain> listTbluser(int page) throws Exception {
  	Map<String, Object> params = new HashMap<String, Object>();
    params.put("defaultSize", pagerowcnt);
    params.put("offset", pagerowcnt * (page-1));
    return tbluserMapper.listTbluser(params);
  }

}

UserController 클래스

package com.iot.ui.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.domain.TbluserDomain;
import com.iot.service.TbluserService;

@Controller
public class UserController {
	
	@Autowired
	private TbluserService tbluserService;
	
	@RequestMapping(value="/userlist.iot", method = RequestMethod.GET)
	public String userlist(ModelMap modelMap) throws Exception 
	{
		List<TbluserDomain> ausers = tbluserService.listTbluser(1);
		modelMap.addAttribute("ausers", ausers);
		return "/UserList";
	}

	@RequestMapping(value="/userinfo.iot", method = RequestMethod.GET)
	public String userinfo(
			@RequestParam("seq") int seq,
			ModelMap modelMap) throws Exception 
	{
		TbluserDomain cu = tbluserService.selectTbluser(seq);
		modelMap.addAttribute("cu", cu);
		return "/UserInfo";
	}
	
}

사용자 목록 조회 JSP

UserList.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ 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>
<h3>현재 접속자 목록</h3>
<c:forEach items="${ausers}" var="u">
 <li><a href="<c:url value="/userinfo.iot"/>?seq=${u.seq}">${u.nick}</a></li>

</c:forEach>

</body>
</html>

사용자 조회 JSP

UserInfo.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>

	<table border="1" cellspacing="0" cellpadding="0" align="center" >
    <tr>
    <td>닉네임</td><td>이메일</td>
     </tr>
 

		<tr>
			<td>${cu.nick}</td>
			<td>${cu.email}</td>
			<td></td>
		</tr>

	</table>

</body>
</html>

jstl(java standard tag library)

Programming/Java 2016.02.19 20:57 Posted by 파란크리스마스

출처 : JSTL의 이해 및 실습 - 12.구루비 Dev 스터디

JSTL 라이브러리

 접두어

 URI 식별자

 기능

 

 c

 http://java.sun.com/jsp/jstl/core

 변수선언

 

 fmt

 http://java.sun.com/jsp/jstl/fmt

 숫자,날짜,시간을 포맷팅 하는 기능과 국제화, 다국어 지원 기능을 제공

 

 fn

 http://java.sun.com/jsp/jstl/functions

 문자열을 처리하는 함수를 제공

 

 sql

 http://java.sun.com/jsp/jstl/sql

 데이터베이스의 데이터를 입력/수정/삭제/조회하는 기능을 제공

 

 x

 http://java.sun.com/jsp/jstl/xml

 XML 문서를 처리할 때 필요한 기능을 제공

 

 form

 http://www.springframework.org/tags/form

 Spring MVC에서 form 관련 기능 제공

 

 sec

 http://www.springframework.org/security/tags

 Spring Security에서 권한 관련 기능 제공

 

관련 라이브러리

jstl-api-1.2.jar, jstl-impl-1.2.jar

JSTL 변수 선언, 삭제, 출력

출처 : 과일가게 개발자 :: JSTL 변수 선언, 삭제, 출력

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="jsp" 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">
</head>
<body>

<!-- 변수 선언 -->
<c:set var="name" value="홍길동" />

<!-- 변수 출력 -->
이름 : <c:out value="${name}" /><br/>

<!-- 변수 삭제 -->
<c:remove var="name" />
삭제된 이름 출력 : <c:out value="${name}" default="이름없음" />

</body>
</html>

C:URL

출처 : [Java] Tag라이브러리(JSTL) 사용하기 | 아이군의 블로그

C:URL 태그라이브러는현재의 서블릿 컨텍스트 이름을 자동으로 앞에 붙여주고 세션관리와 파라미터의 이름과 값의 인코딩을 자동으로 지원합니다. 

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">
<script src='<c:url value="/js/jquery-1.10.2.js"/>' type="text/javascript"></script>
</head>
<body>

<!-- 변수 출력 -->
<c:url value="images/pi_zero.jpg" var="imageURL"/>

<img alt="파이제로 이미지" src="<c:out value="${imageURL}"/>" width="150">

</body>
</html>

브라우져로 본 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">
<script src='/IotWebServer/js/jquery-1.10.2.js' type="text/javascript"></script>
</head>
<body>

<!-- 변수 출력 -->


<img alt="파이제로 이미지" src="/IotWebServer/images/pi_zero.jpg" width="150">

</body>
</html>

-

-

-

-

-

-

Spring MVC - 값 전달

Programming/Java 2016.02.11 12:25 Posted by 파란크리스마스

출처 : 스프링3(Spring3)MVC 연동 (3) - 서버값 웹페이지로 전송하기 :: 야근싫어하는 개발자

파라미터 전달 (클라이언트 -> 서버)

java 소스

	@RequestMapping(value = "/sum_result1.iot", method = RequestMethod.GET)
	public String sum_result1(
			@RequestParam("param1") int param1,
			@RequestParam("param2") int param2,
			ModelMap modelMap
			)

Get 파라미터 전달

http://localhost:7070/IotWebServer/sum_result1.iot?param1=2&param2=3

서버값 클라이언트에 전달 (서버 -> 클라이언트)

java 소스 - TestController.java

package com.iot.ui.controller;

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;

@Controller
public class TestController {

	@RequestMapping(value = "/sum_result1.iot", method = RequestMethod.GET)
	public String sum_result1(
			@RequestParam("param1") int param1,
			@RequestParam("param2") int param2,
			ModelMap modelMap
			)
	{
		// 결과값
		int sum_value = param1 + param2;
		
		// Model에 값 설정
		modelMap.addAttribute("param1", param1);
		modelMap.addAttribute("param2", param2);
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}
}

jsp 소스 - sum_result1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
 
스프링 테스트<br/><br/>
 
${param1} 더하기 ${param2} (은/는) ${sum_value} 입니다.
 
</body>
</html>

결과

@ResponseBody 어노테이션

출처 : @ResponseBody 이해하기

@ResponseBody 로 어노테이션이 되어 있다면 메소드에서 리턴되는 값은 View 를 통해서 출력되지 않고 HTTP Response Body 에 직접 쓰여지게 됩니다.

java 소스

	@ResponseBody
	@RequestMapping(value="/sum_result_body.iot", method = RequestMethod.GET)
	public String sum_result_body(
			@RequestParam("param1") int param1, 
			@RequestParam("param2") int param2
			) throws Exception 
	{
		return param1 + " + " + param2 + " = " + (param1 + param2);
	}

결과

@RequestParam 어노테이션

출처 : [Spring 3 - @MVC] @Controller #2 - 파라미터와 리턴 타입의 종류

옵션

  • value : 파라미터명
  • required : 필수 여부
  • defaultValue : required가 false인 경우 값이 없는 경우 기본값

java 소스

	@RequestMapping(value = "/sum_result2.iot", method = RequestMethod.GET)
	public String sum_result2(
			@RequestParam("param1") int param1,
			@RequestParam(value="param2", required=false, defaultValue="0") int param2,
			ModelMap modelMap
			)
	{
		// 결과값
		int sum_value = param1 + param2;
		
		// Model에 값 설정
		modelMap.addAttribute("param1", param1);
		modelMap.addAttribute("param2", param2);
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}

결과

domain 객체 클라이언트에 전달 (서버 -> 클라이언트)

출처 : 뜬금없는 도메인 오브젝트의 발전사

java 소스 도메인 객체 - SumValueDomain.java

package com.iot.domain;

public class SumValueDomain {
	
	private int value1;
	private int value2;
}

get, set 메소드 생성

메소드 추가

	public int getSumValue() {
		return this.value1 + this.value2;
	}

java 소스 도메인 객체 최종소스 - SumValueDomain.java

package com.iot.domain;

public class SumValueDomain {
	
	private int value1;
	private int value2;
	
	public int getValue1() {
		return value1;
	}
	
	public void setValue1(int value1) {
		this.value1 = value1;
	}
	
	public int getValue2() {
		return value2;
	}
	
	public void setValue2(int value2) {
		this.value2 = value2;
	}
	
	public int getSumValue() {
		return this.value1 + this.value2;
	}
}

java 소스

	@RequestMapping(value = "/sum_result3.iot", method = RequestMethod.GET)
	public String sum_result3(
			@RequestParam("param1") int param1,
			@RequestParam(value="param2", required=false, defaultValue="0") int param2,
			ModelMap modelMap
			) 
	{
		// 도메일 객체 생성
		SumValueDomain sum_value = new SumValueDomain();
		
		// 값 설정
		sum_value.setValue1(param1);
		sum_value.setValue2(param2);
		
		// Model에 도메일 객체 전달
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result3";
	}

jsp 소스 - sum_result3.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>

스프링 테스트<br/><br/>

${sum_value.value1} 더하기 ${sum_value.value2} (은/는) ${sum_value.getSumValue()} 입니다.

</body>
</html>

결과

domain 객체 서버에 전달 (클라이언트 -> 서버)

domain 객체를 spring 프레임워크에서 제공되는 form 테그 라이브러리를 사용해서 jsp에 전달했다가 다시 form 테그를 이용해서 서버의 controller에 전달하는 과정

java 소스 - Form jsp 호출

	@RequestMapping(value = "/sum_form.iot", method = RequestMethod.GET)
	public String sum_form(ModelMap modelMap) {
		// 도메일 객체 생성
		SumValueDomain sum_value = new SumValueDomain();
		
		// Model에 도메일 객체 전달
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_form";
	}

jsp 소스 - sum_form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
</head>
<body>

<form:form modelAttribute="sum_value" action="sum_result4.iot" method="POST">
	<p>
		값1<br/>
		<form:input path="value1"/>
	</p>
	<p>
		값2<br/>
		<form:input path="value2"/>
	</p>
	<p>
		<input type="submit" value="Submit">
	</p>
</form:form>

</body>
</html>

결과 - Form jsp

java 소스 - Form 에서 submit 호출 받는 메소드

	@RequestMapping(value = "/sum_result4.iot", method = RequestMethod.POST)
	public String sum_result4(SumValueDomain domain, ModelMap modelMap) 
	{
		int sum_value = domain.getValue1() + domain.getValue2();
		
		modelMap.addAttribute("param1", domain.getValue1());
		modelMap.addAttribute("param2", domain.getValue2());
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}

결과

Spring - 환경 설정

Programming/Java 2016.02.06 02:54 Posted by 파란크리스마스

출처 : Web.xml의 개요, 기능, 활용
web.xml Listener, Filter의 활용
톰캣 web.xml 설명
[Spring] web.xml 기본 설정

파일 위치

%PROJECT_HOME%\WEB-INF\web.xml

기본 web.xml 파일

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="bluexmas" version="3.0">

	<display-name>IotWebServer</display-name>
	
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>com.bluexmas.ui</param-value>
	</context-param>	
	
	<session-config>
		<session-timeout>720</session-timeout>
	</session-config>

	<jsp-config>
		<jsp-property-group>
			<url-pattern>*.jsp</url-pattern>
			<page-encoding>UTF-8</page-encoding>
		</jsp-property-group>
		<jsp-property-group>
			<url-pattern>/servlet/*</url-pattern>
			<page-encoding>UTF-8</page-encoding>
		</jsp-property-group>
	</jsp-config>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

서블릿 추가

서블릿 파일

package com.iot.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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

// 출처 : http://dkatlf900.tistory.com/68
// tomcat 7.0부터 지원되는 xml 매핑을 자동 매핑
//@WebServlet("/test")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException 
	{
		// request 안의 모든 parameter 확인하기
		// 출처 : http://tmdjcollabo.tistory.com/entry/java-request-%EC%95%88%EC%9D%98-%EB%AA%A8%EB%93%A0-parameter-%ED%99%95%EC%9D%B8%ED%95%98%EA%B8%B0
		Enumeration<String> params = request.getParameterNames();
		System.out.println("----------------------------");
		while (params.hasMoreElements()){
			String name = (String) params.nextElement();
			System.out.println(name + " : " + request.getParameter(name));
		}
		System.out.println("----------------------------");
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("Iot 서버 입니다.");
	}
}

web-xml 추가

	<servlet>
		<servlet-name>test</servlet-name>
		<servlet-class>com.iot.servlet.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>test</servlet-name>
		<url-pattern>/test</url-pattern>
	</servlet-mapping>

Spring MVC DispatherServlet 설정

출처 : @MVC와 DispatcherServlet에 대해서

디렉토리 구조

web-xml 추가

	<servlet>
		<servlet-name>iot</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>iot</servlet-name>
		<url-pattern>*.iot</url-pattern>
	</servlet-mapping>

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

	<bean id="testController" class="com.iot.ui.controller.TestController"/>
	
	<!-- ========================= 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>		
</beans>

TestController.java

package com.iot.ui.controller;

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

@Controller
public class TestController {

	@RequestMapping(value = "/test.iot", method = RequestMethod.GET)
	public String test(ModelMap modelMap) {
		return "testjsp";
	}
}

testjsp.jsp

<%@ 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>
</head>
<body>

스프링 테스트

</body>
</html>


Java objects to XML using JAXB (Servlet)

Programming/Java 2014.12.04 10:41 Posted by 파란크리스마스

출처 : JAXB(위키백과)
@XMLAccessorType, @XMLRootElement
JAXB 2.0 Annotation 정리
How to customise an XML export using JAXB
Creating a Generic List Wrapper in JAXB

JAXB(Java Architecture for XML Binding)는 자바 클래스를 XML로 표현하는 자바 API이다. JAXB는 주로 2가지 기능이 있다. 자바 객체를 XML로 직렬화하는 것이고 반대로 XML에서 자바 객체로 역직렬화하는 것이다. 즉, JAXB는 메모리의 데이터를 XML 형식으로 변환하여 저장할 수 있고, 이 과정을 위해 프로그램의 각 클래스에서 XML을 읽고 저장하는 일을 구현해야 한다.

JAXB 2.0 Annotation 정리

@XmlRootElement 속성

  • name : xml root element 명 지정
  • namespace: namespace 지정

@XmlAccessorType의 설정

@XmlAccessorType(XmlAccessType.PROPERTY)

  • 모든 getter/setter 쌍을 JAXB 직렬화/역직렬화 대상으로 함
  • JAXB 직력화/역직력화에서 제외하고자 할 경우 getter 혹은 setter에 @XmlTransient를 사용
  • @XmlTransient는 getter/setter 상단에 설정
    • 멤버변수 상단에 설정시 적용 않됨
  • getter/setter가 존재하지 않는 public 멤버 변수를 JAXB 직력화/역직력화에서 추가하고자 할 경우 JAXB 어노테이션 사용
    • @XmlElement
    • @XmlAttribute

Employee

package com.test;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "Emp")
@XmlType(propOrder = {"name", "age", "role", "gender"})
public class Employee {

	private int id;

	private String gender;

	private int age;
	private String name;
	private String role;

	private String password;

	@XmlTransient
	public String getPassword() {
		return password;
	}

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

	@XmlAttribute
	public int getId() {
		return id;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	@XmlElement(name = "gen")
	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	@Override
	public String toString() {
		return "ID = " + id + " NAME=" + name + " AGE=" + age + " GENDER="
				+ gender + " ROLE=" + role + " PASSWORD=" + password;
	}

}

JAXBExample

package com.test;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JAXBExample {

	private static final String FILE_NAME = "jaxb-emp.xml";

	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.setId(1);
		emp.setAge(25);
		emp.setName("Pankaj");
		emp.setGender("Male");
		emp.setRole("Developer");
		emp.setPassword("sensitive");

		jaxbObjectToXML(emp);

		Employee empFromFile = jaxbXMLToObject();
		System.out.println(empFromFile.toString());
	}

	private static Employee jaxbXMLToObject() {
		try {
			JAXBContext context = JAXBContext.newInstance(Employee.class);
			Unmarshaller un = context.createUnmarshaller();
			Employee emp = (Employee) un.unmarshal(new File(FILE_NAME));
			return emp;
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static void jaxbObjectToXML(Employee emp) {

		try {
			JAXBContext context = JAXBContext.newInstance(Employee.class);
			Marshaller m = context.createMarshaller();
			// for pretty-print XML in JAXB
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			// Write to System.out for debugging
			// m.marshal(emp, System.out);

			// Write to File
			m.marshal(emp, new File(FILE_NAME));
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

결과 파일 : jaxb-emp.xml

JAXBExample에서 Employee 클래스에 데이터를 담고, 그것을 xml로 출력한 결과입니다.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp id="1">
    <name>Pankaj</name>
    <age>25</age>
    <role>Developer</role>
    <gen>Male</gen>
</Emp>

Wrapper

package com.test;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAnyElement;

public class Wrapper<T> {
	private List<T> items;

	public Wrapper() {
		items = new ArrayList<T>();
	}

	public Wrapper(List<T> items) {
		this.items = items;
	}

	@XmlAnyElement(lax = true)
	public List<T> getItems() {
		return items;
	}
}

XMLServlet

package com.test;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

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 javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

@WebServlet(urlPatterns = "/xml")
public class XMLServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/xml;charset=UTF-8");
		OutputStream out = resp.getOutputStream();

		try {
			JAXBContext jc = JAXBContext.newInstance(Wrapper.class, Employee.class);
			
			// Marshal
			Marshaller marshaller;
			
			marshaller = jc.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshal(marshaller, getEmpDatas(), "emps", out);

		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		out.close();
	}

	/** * Unmarshal XML to Wrapper and return List value. */
	private static <T> List<T> unmarshal(Unmarshaller unmarshaller, Class<T> clazz, String xmlLocation) throws JAXBException {
		StreamSource xml = new StreamSource(xmlLocation);
		Wrapper<T> wrapper = (Wrapper<T>) unmarshaller.unmarshal(xml, Wrapper.class).getValue();
		return wrapper.getItems();
	}

	/**
	 * * Wrap List in Wrapper, then leverage JAXBElement to supply root element *
	 * information.
	 */
	private static void marshal(Marshaller marshaller, List<?> list, String name, OutputStream os) throws JAXBException {
		QName qName = new QName(name);
		Wrapper wrapper = new Wrapper(list);
		JAXBElement<Wrapper> jaxbElement = new JAXBElement<Wrapper>(qName, Wrapper.class, wrapper);
		marshaller.marshal(jaxbElement, os);
	}

	private List<Employee> getEmpDatas() {

		List<Employee> datas = new ArrayList<Employee>();

		Employee emp = new Employee();
		emp.setId(1);
		emp.setAge(25);
		emp.setName("Pankaj");
		emp.setGender("Male");
		emp.setRole("Developer");
		emp.setPassword("sensitive");

		datas.add(emp);

		emp = new Employee();
		emp.setId(11);
		emp.setAge(125);
		emp.setName("1Pankaj");
		emp.setGender("1Male");
		emp.setRole("1Developer");
		emp.setPassword("1sensitive");

		datas.add(emp);

		return datas;
	}
}

실행결과

소스파일

ObjToXML.zip

Spring Security

Programming/Java 2014.10.03 08:03 Posted by 파란크리스마스

출처 : Spring Security login/logout 관련 글
Spring Security Logout Example
Spring Security 3 - 맛보기와 기본 설정의 이해


web.xml

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/baroCOST-datasource.xml
			/WEB-INF/baroCOST-security.xml
		</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>	

baroCOST-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<security:http auto-config="true">
		<security:intercept-url pattern="/favicon.ico" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/**" access="ROLE_USER" />
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>
			<security:user-service>
				<security:user name="guest" password="guest" authorities="ROLE_USER" />
			</security:user-service>
		</security:authentication-provider>
	</security:authentication-manager>
</beans>

Spring Security 에서 기본 제공해주는 로그인 페이지(spring_security_login)

<html><head><title>Login Page</title></head><body onload='document.f.j_username.focus();'>
<h3>Login with Username and Password</h3>
<form name='f' action='/baroCOST/j_spring_security_check' method='POST'>
 <table>
    <tr><td>User:</td><td><input type='text' name='j_username' value=''></td></tr>
    <tr><td>Password:</td><td><input type='password' name='j_password'/></td></tr>
    <tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
  </table>
</form></body></html>

DB 사용

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<security:http auto-config="true">
		<security:intercept-url pattern="/favicon.ico" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/**" access="ROLE_USER" />
		<security:intercept-url pattern="/" access="ROLE_USER" />
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>
			<!-- 
            <security:user-service>
                <security:user name="guest" password="guest" authorities="ROLE_USER" />
            </security:user-service>
            -->		
			<security:jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="select user_id username, password, 1 as enabled from user_info where user_id = ?"
				authorities-by-username-query="select user_id username, 'ROLE_USER' authority from user_info where user_id = ?"
			/>
		</security:authentication-provider>
	</security:authentication-manager>
</beans>

로그인 페이지 변경

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">
           
	<security:http pattern="/common/css/**" security="none" />
	<security:http pattern="/common/image/**" security="none" />
	<security:http pattern="/common/js/**" security="none" />           

	<security:http auto-config="true">
		<security:intercept-url pattern="/favicon.ico" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/login.cmx" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/**" access="ROLE_USER" />
		<security:intercept-url pattern="/" access="ROLE_USER" />
		
		<security:form-login login-page="/login.cmx" default-target-url="/index.html"
			authentication-failure-url="/loginfailed" />
		<security:logout logout-success-url="/logout" />		
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>
			<!-- 
            <security:user-service>
                <security:user name="guest" password="guest" authorities="ROLE_USER" />
            </security:user-service>
            -->		
			<security:jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="select user_id username, password, 1 as enabled from user_info where user_id = ?"
				authorities-by-username-query="select user_id username, 'ROLE_USER' authority from user_info where user_id = ?"
			/>
		</security:authentication-provider>
	</security:authentication-manager>
</beans>


Camel Header 설정

Programming/Java 2014.09.25 10:19 Posted by 파란크리스마스

참고 : http://camel.apache.org/jms.html

RouteBuilder

	from("jms:queue:test1?maxConcurrentConsumers=1&maxMessagesPerTask=1&autoStartup=true&preserveMessageQos=true")
	.bean(com.bluexmas.Test1Queue.class, "doTest")
	.to("jms:queue:test2");
	
	from("jms:queue:test2?maxConcurrentConsumers=1&maxMessagesPerTask=1&autoStartup=true&preserveMessageQos=true")
	.bean(com.bluexmas.Test2Queue.class, "doTest")
	.to("stream:out");

Header1Object

package com.bluexmas;

import java.io.Serializable;

public class Header1Object implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	int age;
	String name;
	
	public Header1Object(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

	@Override
	public String toString() {
		return "Header1Object [age=" + age + ", name=" + name + "]";
	}
}

Test1Queue

package com.bluexmas;

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

import org.apache.camel.Exchange;
import org.apache.camel.Message;

import com.uni.fep.bean.service.MQSenderService;
import com.uni.fep.bean.util.BeanUtils;
import com.uni.fep.bean.util.EnvironmentInit;

public class Test1Queue {
	
	public void doTest(Exchange exchange) {
		System.out.println("-- Test1Queue.doTest ----------------------------");
		
		Message in = exchange.getIn();
		
		System.out.println("body = " + in.getBody());
		System.out.println("header1 = " + in.getHeader("header1"));
		System.out.println("header2 = " + in.getHeader("header2"));
		
		in.setHeader("header1", "value1-1");
		in.setHeader("header2", "value2");
		
		List<String> listValue = new ArrayList<String>();
		listValue.add("list1");
		listValue.add("list2");
		in.setHeader("header3", listValue);
		System.out.println("header3 = " + in.getHeader("header3"));
		
		in.setHeader("header4", new Header1Object(10, "bluexmas"));
		System.out.println("header4 = " + in.getHeader("header4"));
	}
	
	public static void main(String[] args) throws Exception {
		EnvironmentInit.init();
		
		MQSenderService service = (MQSenderService)BeanUtils.getBean("MQSenderService");
		
		String message = "Hello Camel";
		
		Map<String, Object>map=new HashMap<String,Object>();
		map.put("header1", "value1");
		
		service.doSend("test1", map, message);
		
		Thread.sleep(5000);
		
		System.exit(0);
	}

}

Test2Queue

package com.bluexmas;

import org.apache.camel.Exchange;
import org.apache.camel.Message;

public class Test2Queue {

	public void doTest(Exchange exchange) {
		System.out.println("-- Test2Queue.doTest ----------------------------");
		
		Message in = exchange.getIn();
		
		System.out.println("body = " + in.getBody());
		System.out.println("header1 = " + in.getHeader("header1"));
		System.out.println("header2 = " + in.getHeader("header2"));
		System.out.println("header3 = " + in.getHeader("header3"));
		System.out.println("header4 = " + in.getHeader("header4"));
	}
	
}

출력결과

-- Test1Queue.doTest ----------------------------
body = Hello Camel
header1 = value1
header2 = null
header3 = [list1, list2]
header4 = Header1Object [age=10, name=bluexmas]
-- Test2Queue.doTest ----------------------------
body = Hello Camel
header1 = value1-1
header2 = value2
header3 = null
header4 = null
Hello Camel

설명

Camel에서 기본적으로 Header의 내용은 Queue 넘어 갈때 초기화 되는데, 
초기화 하지 않고, 그대로 데이터를 가지고 다니려면 preserveMessageQos=true 해주면 된다.

출력결과를 보시면 알 수 있듯이 기본 자료형외에 객체는 전달 할 수가 없는 것으로 판단된다.

header1 : 초기에 전달된 Header의 값으로 그 값을 변경했을때 변경된 값이 전달되는 것을 확인
header2 : 초기에 전달되지 않았으나 추가로 Header에 추가된 값으로 Queue 이동 후 값이 존재하는 것을 확인
Header3 : ArreyList에 기본형 데이터(String) 추가해서 Header에 추가해서 전달했으나 List 전달되지 않는 것으로 확인
Header4 : 사용자가 임으로 만들 객체를 Header에 추가 했으나 Queue 이동 후 값이 전달되지 않는 것으로 확인

Spring Security 적용하기

Programming/Java 2014.01.28 15:33 Posted by 파란크리스마스

출처 : Spring Security 3 - 맛보기와 기본 설정의 이해
스프링 시큐리티 적용하기 (properties 인증 방법)
Spring Security를 이용한 인증 처리
AJAX Login with Spring Security

WEB-INF\web.xml

	<!-- 스프링 시큐리티 적용하기 -->
	<context-param&g
		<param-name>contextConfigLocation</param-name>
		<param-value>WEB-INF/spring-security.xml</param-value>
 	</context-param>	
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<listener>
  		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 	</listener>

WEB-INF\spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<security:http pattern="/common/css/**" security="none" />
	<security:http pattern="/common/img/**" security="none" />
	<security:http pattern="/common/js/**" security="none" />

	<security:http auto-config="true">
		<security:intercept-url pattern="/admin/**"	access="ROLE_ADMIN" />
		<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />		

		<!-- 
		<security:form-login login-page="/login.do"
			login-processing-url="/j_spring_security_check.do"
			default-target-url="/loginSuccess.do" authentication-failure-url="/loginFailed.do" />

		<security:logout logout-url="/j_spring_security_logout.do"
			logout-success-url="/logout.do" invalidate-session="true" />
 		-->			
	</security:http>


	<security:authentication-manager>
		<security:authentication-provider>
            <security:user-service>
                <security:user name="admin" password="admin!@" authorities="ROLE_ADMIN" />
            </security:user-service>		
			<!-- 
			<security:user-service properties="/WEB-INF/users-config.xml" />
			 -->
		</security:authentication-provider>
	</security:authentication-manager>

</beans>

WEB-INF\users-config.xml (옵션)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
        <comment>users</comment>
        <entry key="admin">1111,ROLE_ADMIN,ROLE_USER</entry>
        <entry key="user">2222,ROLE_USER</entry>
</properties>

 

Quartz - 배치 실행

Programming/Java 2014.01.28 14:45 Posted by 파란크리스마스

출처 : Chapter 19. Quartz 혹은 Timer 를 사용한 스케쥴링     

DongHoReportBatch.java

package com.blueX.batch;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class DongHoReportBatch extends QuartzJobBean {

	@Override
	protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss a"); 
		System.out.println(sdf.format(dt).toString()); 
	}
	
	public static void main(String[] args) throws Exception {
		String[] configLocation = new String[] { "file:WebContent/WEB-INF/blueX-servlet.xml" };
		ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
	}

}

blueX-servlet.xml

	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" autowire="no">
		<property name="triggers">
       		<list>
	         	<ref bean="dongHoReportTrigger" />
			</list>
     	</property>
     	<property name="quartzProperties">
		    <props>
		    	<prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
		        <prop key="org.quartz.threadPool.threadCount">5</prop>
		        <prop key="org.quartz.threadPool.threadPriority">4</prop>
		        <prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>
		        <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>
			</props>
		</property>
	</bean>
	
	<bean id="dongHoReportTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
		<property name="jobDetail" ref="dongHoReportJob" />
		<property name="startDelay" value="60000"/> <!-- 서버 시작후 1분후 첫 실행 -->
		<property name="repeatInterval" value="300000"/> <!-- 첫 실행 후 5분 마다 실행 -->
	</bean> 
	
	<bean id="dongHoReportJob" class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.blueX.batch.DongHoReportBatch" />
	</bean>

Java - File Hash 값 추출

Programming/Java 2013.12.11 09:56 Posted by 파란크리스마스

DigestUtils

package bluexmas.utils;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestUtils {

	public static String extractStringHashSHA256(String str){
		String SHA = ""; 
		try{
			MessageDigest sh = MessageDigest.getInstance("SHA-256"); 
			sh.update(str.getBytes()); 
			byte byteData[] = sh.digest();
			StringBuffer sb = new StringBuffer(); 
			for(int i = 0 ; i < byteData.length ; i++){
				sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
			}
			SHA = sb.toString();
			
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace(); 
			SHA = null; 
		}
		return SHA;
	}
	
	public static String extractFileHashSHA256(String filename) throws Exception {
		
		String SHA = ""; 
		int buff = 16384;
		try {
			RandomAccessFile file = new RandomAccessFile(filename, "r");

			MessageDigest hashSum = MessageDigest.getInstance("SHA-256");

			byte[] buffer = new byte[buff];
			byte[] partialHash = null;

			long read = 0;

			// calculate the hash of the hole file for the test
			long offset = file.length();
			int unitsize;
			while (read < offset) {
				unitsize = (int) (((offset - read) >= buff) ? buff : (offset - read));
				file.read(buffer, 0, unitsize);

				hashSum.update(buffer, 0, unitsize);

				read += unitsize;
			}

			file.close();
			partialHash = new byte[hashSum.getDigestLength()];
			partialHash = hashSum.digest();
			
			StringBuffer sb = new StringBuffer(); 
			for(int i = 0 ; i < partialHash.length ; i++){
				sb.append(Integer.toString((partialHash[i]&0xff) + 0x100, 16).substring(1));
			}
			SHA = sb.toString();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		return SHA;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(extractStringHashSHA256("1"));
		System.out.println(extractFileHashSHA256("a.pdf"));
	}	
}