node.js

Programming/JavaScript, Sencha 2016.05.15 16:49 Posted by 파란크리스마스

출처 : [Node.JS] 강좌 05편: NPM | VELOPERT.LOG
[Node.JS] 강좌 09편: Express 프레임워크 사용해보기 | VELOPERT.LOG
[Node.JS] 강좌 목록 | VELOPERT.LOG

C:\Users\nodejs>npm --version
2.15.1

express 설치

C:\Users\nodejs>npm install express
express@4.13.4 node_modules\express
├── escape-html@1.0.3
├── array-flatten@1.1.1
├── utils-merge@1.0.0
├── vary@1.0.1
├── cookie-signature@1.0.6
├── etag@1.7.0
├── parseurl@1.3.1
├── cookie@0.1.5
├── content-type@1.0.2
├── range-parser@1.0.3
├── fresh@0.3.0
├── merge-descriptors@1.0.1
├── content-disposition@0.5.1
├── methods@1.1.2
├── path-to-regexp@0.1.7
├── serve-static@1.10.2
├── depd@1.1.0
├── qs@4.0.0
├── on-finished@2.3.0 (ee-first@1.1.1)
├── finalhandler@0.4.1 (unpipe@1.0.0)
├── debug@2.2.0 (ms@0.7.1)
├── proxy-addr@1.0.10 (forwarded@0.1.0, ipaddr.js@1.0.5)
├── accepts@1.2.13 (negotiator@0.5.3, mime-types@2.1.11)
├── type-is@1.6.12 (media-typer@0.3.0, mime-types@2.1.11)
└── send@0.13.1 (destroy@1.0.4, ms@0.7.1, statuses@1.2.1, mime@1.3.4, http-errors@1.3.1)

-

-

-

-

-

-



저작자 표시
신고

JQuery 기초

Programming/JavaScript, Sencha 2016.04.24 09:51 Posted by 파란크리스마스

Dialog close전에 Dialog 활성화 여부 확인 후 닫기

	if ($('#popupHoList').is(':visible'))
		$("#popupHoList").dialog('close');

jQuery 사용

출처 : 제이쿼리(jQuery) 기본 :: 갱짱.study

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>

.ready() 메소드

출처 : jQuery ready와 load의 차이 - 오중호랑이의 비밀로그

.ready() 메소드 - 문서의 DOM이 모두 로드 되었을때 실행

$(document).ready(function(){
    alert('Hello World !!!');
});

셀렉터(Selector)

출처 : 박종명의 아름다운 개발 since 2010.06 - 자주 쓰는 JQUERY 기능 - 셀렉터(SELECTOR) 편
Category: Selectors

All Selector (“*”)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
</head>

<body>

<div id="AngularJS">AngularJS</div>
<div class="BackboneJS">Backbone.js</div>
<div name="Emberjs">Emberjs</div>
<span name="ExtJS">ExtJS</span>

<script>
$(function(){
	$('*').css('font-weight', 'bold'); // 모두 선택
});
</script>

</body>
</html>

ID Selector (“#id”)

<script>
$(function(){
	$('#AngularJS').css('font-weight', 'bold'); // AngularJS
});
</script>

Class Selector (“.class”)

<script>
$(function(){
	$('.BackboneJS').css('font-weight', 'bold'); // BackboneJS
});
</script>

Attribute Equals Selector [name=”value”]

<script>
$(function(){
	$('div[name="Emberjs"]').css('font-weight', 'bold'); // Emberjs
});
</script>

Attribute Not Equal Selector [name!=”value”]

<script>
$(function(){
	$('div[name!="Emberjs"]').css('font-weight', 'bold'); // AngularJS, Backbone.js
});
</script>

:first Selector

<script>
$(function(){
	$('div:first').css('font-weight', 'bold'); // AngularJS
});
</script>

:last Selector

<script>
$(function(){
	$('div:last').css('font-weight', 'bold'); // Emberjs
});
</script>

:eq() Selector

<script>
$(function(){
    $('div:eq(2)').css('font-weight', 'bold'); // Emberjs
});
</script>

.text() .html() - 내용 가져오기, 내용 변경하기

출처 : jQuery 3강 - html() vs text() 함수 차이점 알아보기 + val() 함수

.text() .html() - 내용 가져오기

text 메소드는 html 테그를 제외한 텍스트 내용만 가져오고, html 메소드는 html 테그까지 포함된 내용을 가져옮

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
<script>
$(document).ready(function(){
	alert($('#AngularJS').text()); // AngularJS
	alert($('#AngularJS').html()); // <a href="http://angularjs.org/">AngularJS</a>
});
</script>
</head>

<body>

<div id="AngularJS"><a href="http://angularjs.org/">AngularJS</a></div>
<div class="BackboneJS">Backbone.js</div>
<div name="Emberjs">Emberjs</div>
<span name="ExtJS">ExtJS</span>

</body>
</html>

.text() .html() - 내용 변경하기

<script>
$(document).ready(function(){
	$('#AngularJS').html('<a href="https://blog.outsider.ne.kr/975">Angular.js는 왜 좋은가? :: Outsider\'s Dev Story</a>');
	$('.BackboneJS').text('백본js');
});
</script>

.show() .hide() - 보이기, 숨기기

출처 : 48.jQuery - show()와 hide로 숨기기 및 보이기

jQuery객체.is(":visible") 호출로 현재 보여지고 있는지 숨겨져 있는지 확인 가능

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
<script>
function doShow() {
    if ($('#AngularJS').is(":visible")) {
        $('#AngularJS').hide(); // 숨기기
        $('#button1').text('보이기'); 
    } else {
        $('#AngularJS').show(); // 보이기
        $('#button1').text('숨기기');
    }
}
</script>
</head>
 
<body>
 
<div id="AngularJS">AngularJS</div>
<div class="BackboneJS">Backbone.js</div>
<div name="Emberjs">Emberjs</div>
<span name="ExtJS">ExtJS</span>
 
<p><button id="button1" onclick="javascript:doShow()">숨기기</button></p>
 
</body>
</html>

.addClass() .removeClass() .hasClass() - 클래스 추가, 삭제, 포함 여부 확인하기

출처 : 클래스 추가 및 삭제하기 - EVERDEVEL

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
<style type="text/css">
.div_hide {
	display: none;
}
</style>
<script>
function doShow() {
	if ($('#AngularJS').hasClass("div_hide")) {
		$('#AngularJS').removeClass('div_hide');
		$('#button1').text('보이기');
	} else {
		$('#AngularJS').addClass('div_hide');
		$('#button1').text('숨기기');
	}
}
</script>
</head>

<body>

<div id="AngularJS">AngularJS</div>
<div class="BackboneJS">Backbone.js</div>
<div name="Emberjs">Emberjs</div>
<span name="ExtJS">ExtJS</span>

<p><button id="button1" onclick="javascript:doShow()">보이기</button></p>

</body>
</html>

.css() - CSS 변경

출처 : jQuery CSS 속성 변경 - 제타위키

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(function(){
	$('body').css('background-color', 'red');
});
</script>

.attr() - 속성을 제어

출처 : 즐거움을 찾자 Find Fun!! :: jQuery API 정복 - attr(), 속성을 제어하기

인자에 개수에 따라 2가지로 용도로 사용 - 하나의 인자만 있으면 속성값을 가져오는 것이고, 2개의 인자를 사용 하면 속성값을 설정함
속성값 설정시 속성이름이 존재하지 않는 경우 속성이 추가됨

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
<style type="text/css">
.div_hide {
	display: none;
}
</style>
<script>
function doGetAttr() {
	alert($('#AngularJS').attr('name')); // js_framework_1
}

function doSetAttr() {
	$('#AngularJS').attr('hangul', '알골라JS'); // 속성 추가
}
</script>
</head>

<body>

<div id="AngularJS" name="js_framework_1">AngularJS</div>
<div class="BackboneJS">Backbone.js</div>
<div name="Emberjs">Emberjs</div>
<span name="ExtJS">ExtJS</span>

<p><button onclick="javascript:doGetAttr();">속성값 조회</button></p>
<p><button onclick="javascript:doSetAttr();">속성값 설정</button></p>

</body>
</html>

.find() 자식 노드 선택자

출처 : find(expr) - jQuery 日本語リファレンス

지정 요소의 모든 하위 요소에서 조건식에 맞는 요소를 선택

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
<script>
function doFind() {
    $('#js_framework').find('.BackboneJS').css('color','red');
}
</script>
</head>
 
<body>
 
<div id="js_framework"> 
    <div id="AngularJS">AngularJS</div>
    <div class="BackboneJS">Backbone.js</div>
    <div name="Emberjs">Emberjs</div>
</div>
 
<p><button onclick="javascript:doFind();">Find 메소드 호출</button></p>
 
</body>
</html>

.append() - 마지막 자식 요소 추가

출처 : jQuery API 정복 - 마지막 자식 요소 추가, append() - jyhyun

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
<script>
function doAppend() {
	$('#js_framework').append('<span name="ExtJS">ExtJS</span>'); // 마지막 요소 추가
}
</script>
</head>

<body>

<div id="js_framework"> 
	<div id="AngularJS">AngularJS</div>
	<div class="BackboneJS">Backbone.js</div>
	<div name="Emberjs">Emberjs</div>
</div>

<p><button onclick="javascript:doAppend();">마지막 요소 추가</button></p>

</body>
</html>

.clone() - 요소 복사하기

출처 : jQuery API 정복 - 요소 복사하기, clone() - jyhyun

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
<script>
function doClone() {
	
	//
	var row = $('#tr_dumy').clone();
	row.attr('id', 'tr_fw');
	
	//
	row.find('#js_name').text('Emberjs');
	
	//
	$('#js_framework').append(row); // 마지막 요소 추가
}
</script>
</head>

<body>

<table id="js_framework" border="1">
	<tr id='tr_fw'>
		<td>AngularJS</td>
		<td>Angular.js는 구글이 만든 MV*(Model - View - Whatever) 자바스크립트 프레임워크</td>
	</tr>
	<tr id='tr_fw'>
		<td>Backbone.js</td>
		<td>Model-Collection-View 기반으로 구현하는 Javascript 웹 애플리케이션 프레임웍</td>
	</tr> 
</table>


<table style="display:none;">
	<tr id="tr_dumy">
		<td id="js_name"></td>
		<td id="js_contents"></td>
	</tr>
</table>

<p><button onclick="javascript:doClone();">clone 테스트</button></p>

</body>
</html>

-

저작자 표시
신고

Lazarus로 Raspberry PI의 GPIO제어 (LED 컨트롤)

Programming/Delphi 2016.03.13 22:18 Posted by 파란크리스마스

출처 : Lazarus on Raspberry Pi
RaspberyPi rpi_hal Hardware Abstraction Library

라이브러리 다운로드

rudiratlos/rpi-hal 다운로드

rpi_hal 버그가 있어서 제가 수정했습니다. 압축된 소스 파일에 수정된 rpi_hal.pas 파일을 첨부했습니다.

빌드옵션

빌드 옵션으로 UseCThreads 추가가 필요합니다.

소스

RaspberryPI LED.7z

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  rpi_hal;

type

  { TForm1 }

  TForm1 = class(TForm)
    ToggleBox1: TToggleBox;
    ToggleBox2: TToggleBox;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure ToggleBox1Change(Sender: TObject);
    procedure ToggleBox2Change(Sender: TObject);
  private
    { private declarations }
    isr_1 : isr_t;
    isr_2 : isr_t;
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

const
  GPIO20 = 20;
  GPIO21 = 21;

function my_isr(gpio_nr:integer):integer;
// for gpio_int testing. will be called on interrupt
const waittim_ms=1;
begin
  writeln ('my_isr fired for GPIO',gpio_nr,' servicetime: ',waittim_ms:0,'ms');
  sleep(waittim_ms);
  my_isr:=999;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  writeln('Show CPU-Info, RPI-HW-Info and Registers:');
  rpi_show_all_info;

  isr_1.gpio := GPIO20;
  isr_1.rising_edge := true;
  gpio_set_int(isr_1, GPIO20, @my_isr, true, OUTPUT);
  gpio_int_enable(isr_1);

  isr_2.gpio := GPIO21;
  isr_2.rising_edge := true;
  gpio_set_int(isr_2, GPIO21, @my_isr, true, OUTPUT);
  gpio_int_enable(isr_2);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  gpio_int_disable(isr_1);
  gpio_int_release(isr_1);

  gpio_int_disable(isr_2);
  gpio_int_release(isr_2);
end;

procedure TForm1.ToggleBox1Change(Sender: TObject);
begin
  gpio_set_pin(isr_1.gpio, ToggleBox1.Checked);
end;

procedure TForm1.ToggleBox2Change(Sender: TObject);
begin
  gpio_set_pin(isr_2.gpio, ToggleBox2.Checked);
end;

end.

실행

$ chmod 755 raspi_led
$ sudo ./raspi_led


저작자 표시
신고

Java - Mail 보내기

Programming/Java 2016.03.12 16:22 Posted by 파란크리스마스

출처 : 자바에서 메일 보내는 방법 - Nothing New Under the Sun

JavaMail 다운로드

다운로드

Servlet 소스

class mvc.servlet.MailServlet

package mvc.servlet;

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

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
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 net.sf.json.JSONObject;

@WebServlet(urlPatterns = "/mail")
public class MailServlet extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String from_email = request.getParameter("from_email");
		String to_email = request.getParameter("to_email");
		String mail_subtitle = request.getParameter("subtitle");
		String mail_content = request.getParameter("content");
		
		System.out.println("from_email = " + from_email);
		System.out.println("to_email = " + to_email);
		
		
		// 먼저 환경 정보를 설정해야 한다.
		// 메일 서버 주소를 IP 또는 도메인 명으로 지정한다.
		Properties props = System.getProperties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "smtp.gmail.com");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.quitwait", "false");
		
		Authenticator auth = new MyAuthenticator();

		// 위 환경 정보로 "메일 세션"을 만들고 빈 메시지를 만든다
		Session session = Session.getDefaultInstance(props, auth);
		session.setDebug(true);
		
		MimeMessage msg = new MimeMessage(session);
		
		try {
			// 발신자, 수신자, 참조자, 제목, 본문 내용 등을 설정한다
			msg.setFrom(new InternetAddress(from_email, "*보내는사람*"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to_email, "*받는사람*"));
			/*
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress("eee@fff.co.kr", "선덕여왕"));
			msg.addRecipient(Message.RecipientType.CC, new InternetAddress("ggg@hhh.co.kr", "의자왕"));
			*/
			msg.setSubject(mail_subtitle);
			msg.setContent(mail_content, "text/html; charset=utf-8");

			// 메일을 발신한다
			Transport.send(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		response.setContentType("text/x-json;charset=UTF-8");            
		response.setHeader("Cache-Control", "no-cache"); 
		
		PrintWriter out = response.getWriter();
		
		JSONObject json = new JSONObject();
		json.put("result", "true");
		out.println(json);
	}
	
	static class MyAuthenticator extends Authenticator {
		public PasswordAuthentication getPasswordAuthentication() {
			//String username = "******@gmail.com";
			//String password = "*****";
			return new PasswordAuthentication(username, password);
		}
	}
}

mail.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../resources/js/jquery-1.12.0.js"></script>
<title>Java Mail</title>
<style type="text/css">
body {
	font-family: 'Apple SD Gothic Neo',arial,sans-serif;
	font-size: 14px;
}
</style>
</head>
<body>
	
<form action="mail">
	<table>
		<tr><td>보내는사람</td><td><input type="text" name="from_email"></td></tr>
		<tr><td>받는사람</td><td><input type="text" name="to_email"></td></tr>
		<tr><td>제목</td><td><input type="text" name="subtitle"></td></tr>
		<tr><td>내용</td><td><input type="text" name="content"></td></tr>
	</table>
	<input type="submit" value="보내기">
</form>

</body>
</html>

인증오류 해결방법

출처 : email - how to fix "send-mail: Authorization failed 534 5.7.14

534 5.7.14  https://support.google.com/mail/answer/78754 g23sm18237842pfg.35 - gsmtp

	at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:823)
	at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:756)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:673)
	at javax.mail.Service.connect(Service.java:317)
	at javax.mail.Service.connect(Service.java:176)
	at javax.mail.Service.connect(Service.java:125)
	at javax.mail.Transport.send0(Transport.java:194)
	at javax.mail.Transport.send(Transport.java:124)
	at mvc.servlet.MailServlet.service(MailServlet.java:54)

https://www.google.com/settings/security/lesssecureapps

보안 수준이 낮은 앱의 액세스 을 사용으로 설정

AJAX로 보내기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="resources/js/jquery-1.12.0.js"></script>
<title>Java Mail</title>
<style type="text/css">
body {
	font-family: 'Apple SD Gothic Neo',arial,sans-serif;
	font-size: 14px;
}
</style>
<script type="text/javascript">
function sendEMail() {
	
	var form = document.formEMail;

	//
	try {
		$.ajax({
			type: 'GET',
			url: 'mail',
			dataType: 'json',
			data: {
				from_email : form.from_email.value,
				to_email : form.to_email.value,
				subtitle : form.subtitle.value,
				content : form.content.value
			},
			success: function(data)
			{
				//alert(data);
				$('.clsResult').html(data.result);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert('There was an error.');
			}
		});
		
	} catch(e) {
		alert(e);
	}
	
	return false;
}

</script>
</head>
<body>
	
<form action="mail" name="formEMail">
	<table>
		<tr><td>보내는사람</td><td><input type="text" name="from_email"></td></tr>
		<tr><td>받는사람</td><td><input type="text" name="to_email"></td></tr>
		<tr><td>제목</td><td><input type="text" name="subtitle"></td></tr>
		<tr><td>내용</td><td><input type="text" name="content"></td></tr>
	</table>
	<input type="submit" value="보내기">
</form>

<hr>

<button onclick="javascript:sendEMail();">AJAX로 보내기</button><br/>
<p>결과</p>
<div class="clsResult">
</div>

</body>
</html>
저작자 표시
신고

jstl(java standard tag library)

Programming/Java 2016.02.28 19:13 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

c:set, c:out, c:remove - 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 - 게시판 작성

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>

-

-

-

-

-

-

저작자 표시
신고

javascript 기본

Programming/JavaScript, Sencha 2016.02.14 02:08 Posted by 파란크리스마스

1. alert

브라우져의 팝업으로 값을 확인하는 명령어

alert('Hello World !!!!');

2. console.log - 로그값 확인 

브라우져의 개발자모드를 이용해서 콘솔창에서 로그값 확인 가능

console.log('나 로그');

3. 변수

변수 선언

var value1;

변수 대입

value1 = 2;

4. 상수

상수 const 키워드 사용

const const1 = 1'

5. 데이터 타입

  • 숫자형 - 정수형 / 1, 2, 3
  • 숫자형 - 실수형 / 1.23
  • 문자형 - '변수'
  • 블리언 - true / false

6. 배열

출처 : [자바스크립트 완벽 가이드 정리] 배열

배열의 속성

length 속성 : 배열의 개수 반환

배열의 요소 추가

push

unshift

배열의 요소 삭제

pop() 마지막 요소 삭제, 반환값으로 삭제된 값 반환

shift() 첫번째 

배열의 요소 접근

배열의 index는 0 부터 시작

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

<script type="text/javascript">
var colors = ["white", "black", "yellow"];

document.write("배열의 개수 = " + colors.length + "<br>");
document.write("배열의 두번째 요수 = " + colors[1] + "<br>");
</script>

</body>
</html>

7. 산술연산자

  • + : 덧셈
  • - : 뺄셈
  • / : 나눗셈
  • * : 곱셈
  • ++ : 1증가
  • -- : 1감소
  • % : 나머지

8. 문자열 연산자

  • + : 문자열 합치기
9. 조건문

출처 : [JavaScript] 조건문과 반복문

if문

var date = new Date();
var hour = date.getHours();
 
if(hour < 11) {
    alert("아침");
}
else if(hour < 15) {
    alert("점심");
}
else {
    alert("저녁");
}

switch문

var input = Number(prompt('숫자를 입력하세요.', '숫자'));
 
switch(input % 2) {
    case 0:
        alert("짝수입니다.");
        break;
    case 1:
        alert("홀수입니다.");
        break;
    default:
        alert("숫자가 아닙니다.");
        break;
}

삼항 연산자

var input = prompt('숫자 입력', '');
var number = Number(input);
 
(number > 0) ? alert('자연수') : alert('자연수아님');

10. 반복문

출처 : [JavaScript] 조건문과 반복문

while 반복문

value = 0;
while(value < 5) {
    alert(value + '번째 반복');
    value++;
}

do while 반복문

var value = 0;
do {
    alert(value + '번째 반복문');
    value++;
} while(value < 5);

for 반복문

var array = ['포도', '사과', '바나나', '망고'];
 
for(var i=0; i<array.length; i++) {
    alert(array[i]);
}

for in 반복문

배열의 요소 만큼 반복

var array = ['포도', '사과', '바나나', '망고'];
 
for(var i in array) {
    alert(array[i]);
}
11. 예외 처리
try {
  addalert("bad call");
} catch(e) {
  alert(e.message);
}

12. 함수

출처 : Javascript : 함수(function) 다시 보기

함수선언식 function declaration

function sum(src1, src2) {
	return src1 + src2;
}

alert( sum(1, 2) ); // 결과 3

익명 함수표현식 anonymous function

var sum = function (src1, src2) {
	return src1 + src2;
}

alert( sum(1, 2) ); // 결과 3

즉시실행함수 IIFF, Immediately Invoked Function Expression

(function() {
    /* 실행코드 */
})();

함수 변수로 전달

// 전달될 함수
var sum = function (src1, src2) {
	return src1 + src2;
}

// 첫번째 인자로 함수가 전달됨
function sum2(function_name, src1, src2, src3 ) {
	var result = 0;
	result = function_name(src1, src2);
	result = function_name(result, src3);
	return result;
}

alert( sum2( sum, 1, 2, 3) ); // 결과 6

13. 구조체

// 구조체 
var user = {
  name : '이순신',
  user_id : 'lee',
  age : 10
}

// (.)점으로 구조체 멤버에 접근
alert(user.name); // 이순신

구조체 내 함수

var user = {
  name : '이순신',
  user_id : 'lee',
  age : 10,
  getName : function() {
  	return this.name;
  },
  setName : function(name) {
  	this.name = name;
  }
}

alert(user.getName());
user.setName('김유신');

alert(user.getName());

구조체 외부에서 함수 추가

var user = {
  name : '이순신',
  user_id : 'lee',
  age : 10
}

user.getAge = function() {
	return this.age;
}

alert(user.getAge());



7. 객체

- 1

- 2

- 3

8. this 키워드

-

9. 내장 객체

출처 : JavaScript - 내장 객체의 종류 - 늑대의 기억 저장소

window : 브라우저 창이 열릴 때 마다 하나씩 만들어지는 객체, 브라우저 창 안에 존재하는 모든 요소의 최상위 객체.

document : 웹 문서마다 하나씩 만들어지는 객체로 <body> 태그에 의해 만들어진다. HTML 문서에 대한 정보를 가지고 있다.

history : 현재 창에서 사용자의 방문 기록을 저장하고 있는 객체

location : 현재 문서에 대한 URL 정보를 가지고 있는 객체

navigator : 현재 사용하는 브라우저에 대한 정보를 가지고 있는 객체.

screen : 현재 사용하는 화면에 대한 정보를 다루는 객체

10. Number 객체

-

11. Math 객체

출처 : Math 개체(JavaScript) - MSDN - Microsoft
JavaScript Math Reference - W3Schools
즐거움을 찾자 Find Fun!! :: JavaScript 수학 객체 Math

Math 주요 메소드

  • abs(x)       x의 절대값
  • ceil(x)       올림
  • max(x,y,z,...,n) 인자 중 max값
  • min(x,y,z,...,n)  인자 중 min값
  • random()       0 과 1 사이의 난수
  • round(x)       반올림

12. Date 객체

출처 : Date - JavaScript | MDN - Mozilla Developer Network
JavaScript Date Reference - W3Schools
Date 개체(JavaScript) - MSDN - Microsoft
JavaScript Date Object - The Computer Technology

Data 객체 생성

var d = new Date(); // 인자가 없는 경우 객체가 생성된 시간
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

현재 월 확인

var curdate = new Date()
var month = curdate.getMonth()
document.write(month + "
")


저작자 표시
신고

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>


저작자 표시
신고


 

티스토리 툴바