Spring MVC - JSON 통신

Programming/Java 2016.12.10 17:29 Posted by 파란크리스마스

JSONData 추상 클래스 생성

Factory 패턴에서 반환 가능한 형태로 만들기 위해서 추상 클래스를 사용하기때문에 아래와 같이 추상 클래스를 생성

package com.iot.json;

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

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

import net.sf.json.JSONObject;

public abstract class JSONData {
	
	private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
	
	public abstract JSONObject getJSON(HttpServletRequest request, HttpServletResponse response);
	
	public JSONObject getJSONObject(Map<String, Object> map) {
		JSONObject jobj = new JSONObject();
		//loop a Map
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (entry.getValue() instanceof java.sql.Date) {
				//
				jobj.put(entry.getKey(), fromCalendar((Date) entry.getValue()));
			} else {
				jobj.put(entry.getKey(), entry.getValue());
			}
		}
		return jobj;
	}
	
	public static String fromCalendar(final Date date) {
		String formatted = formatter.format(date);
		return formatted.substring(0, 22) + ":" + formatted.substring(22);
	}
}

JSONSample 클래스 생성

간단하게 테스트나 이해를 돕기 위해서 JSONData 추상 클래스를 상속받아서 Sample 클래스를 생성

package com.iot.json;

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

import org.springframework.stereotype.Controller;

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

@Controller
public class JSONSample extends JSONData {

	@Override
	public JSONObject getJSON(HttpServletRequest request, HttpServletResponse response) {
		JSONArray arrayObj = new JSONArray();
		
		JSONArray data = new JSONArray();
		data.add("Tiger Nixon");
		data.add("System Architect");
		data.add("Edinburgh");
		data.add("5421");
		data.add("2011/04/25");
		data.add("$320,800");
		arrayObj.add(data);
		
		data = new JSONArray();
		data.add("Garrett Winters");
		data.add("Accountant");
		data.add("Tokyo");
		data.add("8422");
		data.add("2011/07/25");
		data.add("$170,750");
		arrayObj.add(data);
		
		JSONObject jobj_data = new JSONObject();
		jobj_data.put("data", arrayObj);
		
		return jobj_data;
	}
}

JSONFactory 클래스 생성

Factory 패턴으로 cmd 값에 따라 해당 JSONData를 구현한 객체를 반환

package com.iot.json;

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

@Controller
public class JSONFactory {
	
	@Autowired
	private JSONSample jSONSample;
	
	public JSONData getJSONData(String cmd) {
		
		System.out.println("cmd = " + cmd);
		
		if (true) {
			return jSONSample;
		}
		
		return jSONSample;
	}
}

JSONController 클래스 생성

json 형태로 데이터 반환

package com.iot.json;

import java.io.IOException;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
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.ResponseBody;

@Controller
public class JSONController {
	
	@Autowired
	private JSONFactory jSONFactory;

	@ResponseBody
	@RequestMapping(value="/json.iot", method=RequestMethod.GET, produces="application/json; charset=utf-8")
	public String service(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
		
		/*
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String reg_id = auth.getName();
		*/
		
		/*
		Enumeration<String> keys = request.getParameterNames();
		while(keys.hasMoreElements()) {
			String key = keys.nextElement();
			System.out.println("param = " + key + "/" + request.getParameter(key));
		}
		*/
		
		String cmd = request.getParameter("cmd");
		if (cmd==null) {
			cmd = "";
		}
		
		JSONData json = jSONFactory.getJSONData(cmd);
		
		return json.getJSON(request, response).toString();
	}

}

iot-servlet.xml 내용 추가

json 관련 패키지가 자동으로 스프링컨테이너에 로딩 되도록 WEB-INF/iot-servlet.xml 파일에에 아래 내용을 추가

<context:component-scan base-package="com.iot.json"/>

	<!-- 컨트롤더 package 자동으로 스프링 컨테이너 등록 -->
	<context:component-scan base-package="com.iot.controller"/>
	<context:component-scan base-package="com.iot.json"/>

Sample 데이터 확인

JSONUser 클래스 추가

AJAX로 사용자 추가하는 클래스를 만들기 위해서  JSONData 추상 클래스를 상속받아서 JSONUser 클래스를 생성

package com.iot.json;

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

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

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

import net.sf.json.JSONObject;

@Controller
public class JSONUser extends JSONData {
	
	public static String COMMAND = "user";
	
	@Autowired
	private UserInfoService service;

	@Override
	public JSONObject getJSON(HttpServletRequest request, HttpServletResponse response) {
		String subcmd = request.getParameter("subcmd");
		System.out.println("subcmd = " + subcmd);	
		
		JSONObject jobj_data = null;
		if (subcmd.equals("add")) {
			jobj_data = getAddData(request, response);
		}
			
		return jobj_data;
	}

	private JSONObject getAddData(HttpServletRequest request, HttpServletResponse response) {
		
		String errStr = null;
		
		try {
			UserInfo userinfo = new UserInfo();
			userinfo.setUser_id(request.getParameter("user_id"));
			userinfo.setPassword(request.getParameter("password"));
			userinfo.setName(request.getParameter("name"));
			userinfo.setNickname(request.getParameter("nickname"));
			
			service.insertUserInfo(userinfo);
		} catch (Exception e) {
			errStr = e.toString();
			e.printStackTrace();
		}
		
		JSONObject jobj_data = new JSONObject();
		jobj_data.put("success", (errStr == null ? true : false));
		
		return jobj_data;
	}

}

JSONFactory 수정

파라미터 cmd의 값이 user인 경우 JSONUser의 객체가 반환 되도록 코드 추가

package com.iot.json;

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

@Controller
public class JSONFactory {
	
	@Autowired
	private JSONUser jSONUser;
	
	@Autowired
	private JSONSample jSONSample;
	
	public JSONData getJSONData(String cmd) {
		
		System.out.println("cmd = " + cmd);
		
		if (JSONUser.COMMAND.equals(cmd)) { // JSONUser.COMMAND = user
			return jSONUser;
		} else {
			return jSONSample;
		}
		
		// return jSONSample;
	}
}

UserController 클래스 생성

사용자 관련 Controller 클래스 생성

package com.iot.controller;

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

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 UserController {
	
	@RequestMapping(value = "/user_add_ajax.iot", method = RequestMethod.GET)
	public String user_add_ajax(ModelMap modelMap) throws Exception {
		return "/user_add_ajax";
	}

}

user_add_ajax.jsp 생성

사용자 추가 JSP 작성 - JQuery AJAX 통신

<%@ 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="http://code.jquery.com/jquery-latest.min.js"></script>
<title>사용자추가</title>
<script type="text/javascript">
function user_add() {
	var form = document.uploadForm;
    //var form = new FormData(document.getElementById('uploadForm'));
	$.ajax({
	  url: "<c:url value="/json.iot"/>",
	  data: {
		cmd : "user",
		subcmd : "add",
		user_id : form.user_id.value,
		password : form.password.value,
		name : form.name.value,
		nickname : form.nickname.value
	  },
	  // data: form,
	  dataType: 'json',
	  contentType: false,
	  type: 'GET',
	  success: function (response) {
	    console.log('success');
	    console.log(response);
	  },
	  error: function (jqXHR) {
	    console.log('error');
	  }
	});
}
</script>
</head>
<body>

<h1>사용자 추가</h1>
<form id="uploadForm" name="uploadForm" method="get">
	<input type="hidden" name="cmd" value="user">
	<input type="hidden" name="subcmd" value="add">
	<table border="1">
		<tr>
			<td>사용자ID</td>
			<td>
				<input type="text" name="user_id"/>
			</td>
		</tr>
		<tr>
			<td>암호</td>
			<td>
				<input type="text" name="password"/>
			</td>
		</tr>
		<tr>
			<td>사용자이름</td>
			<td>
				<input type="text" name="name"/>
			</td>
		</tr>
		<tr>
			<td>별명</td>
			<td>
				<input type="text" name="nickname"/>
			</td>
		</tr>
		<!-- 
		<tr>
			<td>사진</td>
			<td>
				<input type="file" name="photo"/>
			</td>
		</tr>
		-->
	</table>
	<br/>
	<input type="button" value="사용자추가" onclick="javascript:user_add();"/>
</form>

</body>
</html>


저작자 표시
신고

Spring MVC - 파일 업로드

Programming/Java 2016.12.04 16:52 Posted by 파란크리스마스

Spring MVC Multipart Configuration (iot-servlet.xml 내용추가)

출처 : Spring MVC File Upload Example Tutorial - Spring MVC File Upload Example Tutorial – Single and Multiple Files
스프링(Spring) 파일 업로드(File Upload) :: 갱짱.study - 이갱짱 - Tistory

	<!-- ========================= Multipart Form-Data Resolver ========================= -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--
		<property name="maxUploadSize">
			<value>10000000</value>
		</property>
		-->
	</bean>

FileUploadController.java

package com.iot.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

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 org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

	@RequestMapping(value = "/file_upload_form.iot", method = RequestMethod.GET)
	public String file_upload_form(ModelMap modelMap) {
		return "/file_upload_form";
	}
	
	@RequestMapping(value = "/file_upload_save.iot", method = RequestMethod.POST)
	public String file_upload_save(@RequestParam("uploadfile") MultipartFile uploadfile, ModelMap modelMap) {

		OutputStream out = null;
		PrintWriter printWriter = null;

		try {
			// 파일명 얻기
			String fileName = uploadfile.getOriginalFilename();
			// 파일의 바이트 정보 얻기
			byte[] bytes = uploadfile.getBytes();
			// 파일의 저장 경로 얻기
			String uploadPath = getDestinationLocation() + fileName;
			
			// 파일 객체 생성
			File file = new File(uploadPath);
			// 상위 폴더 존재 여부 확인
			if (!file.getParentFile().exists()) {
				// 상위 폴더가 존재 하지 않는 경우 상위 폴더 생성
				file.getParentFile().mkdirs();
			}
			
			// 파일 아웃풋 스트림 생성
			out = new FileOutputStream(file);
			// 파일 아웃풋 스트림에 파일의 바이트 쓰기
			out.write(bytes);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (printWriter != null) {
					printWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return "/file_upload_form";
	}
	
	private String getDestinationLocation() {
		return "/업로드폴더/";
	}
}

file_upload_form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="file_upload_save.iot" method="post" enctype="multipart/form-data">
		<fieldset>
			<table>
				<tr>
					<th>파일</th>
					<td><input type="file" name="uploadfile" required="required"></td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="작성">
						<input type="reset" value="취소">
					</td>
				</tr>
			</table>
		</fieldset>
	</form>
</body>
</html>

업로드 폴더 웹에 노출시키기

{tomcat_home}/conf/server.xml 내용 추가

<Context docBase="C:/업로드폴더" path="uploaddir" reloadable="true"/>

JQuery Ajax로 파일 업로드

출처 - Programming is Fun :: Spring MVC를 이용한 Ajax File upload

FileUploadController 내용 추가

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

	@ResponseBody
	@RequestMapping(value = "/file_upload_save_ajax.iot", headers="Accept=*/*", method = RequestMethod.POST)
	public String file_upload_save_ajax(@RequestParam("uploadfile") MultipartFile uploadfile, ModelMap modelMap) {

		OutputStream out = null;

		try {
			String fileName = uploadfile.getOriginalFilename();
			byte[] bytes = uploadfile.getBytes();
			String uploadPath = getDestinationLocation() + fileName;// 저장경로
			
			File file = new File(uploadPath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			
			out = new FileOutputStream(file);
			out.write(bytes);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return "true";
	}

file_upload_form_ajax.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
$( document ).ready(function() {
  $('#btn-upload').on('click', function () {
    console.log('btn-upload');
    var form = new FormData(document.getElementById('uploadForm'));
    $.ajax({
      url: "file_upload_save_ajax.iot",
      data: form,
      dataType: 'text',
      processData: false,
      contentType: false,
      type: 'POST',
      success: function (response) {
        console.log('success');
        console.log(response);
      },
      error: function (jqXHR) {
        console.log('error');
      }
    });
  });
});
</script>
</head>
<body>
	<form action="file_upload_save.iot" method="POST" id="uploadForm" enctype="multipart/form-data">
		<fieldset>
			<table>
				<tr>
					<th>파일</th>
					<td><input type="file" name="uploadfile" required="required"></td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="작성">
						<input type="reset" value="취소">
					</td>
				</tr>
			</table>
		</fieldset>
	</form>
	<span id="btn-upload">파일업로드AJAX</span>
</body>
</html>


저작자 표시
신고

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

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

package com.iot.controller;

import java.util.List;

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

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

@Controller
public class IotController {

	@Autowired
	private UserInfoService service;

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

}

JSP에 Form 테그 추가

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

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

Hello World

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

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

</body>
</html>

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

UserInfo 객체를 인자로 받음

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

		service.insertUserInfo(userinfo);

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

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

		return "/hello_world";
	}

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

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

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

public void insertUserInfo(UserInfo userInfo);

Mapper XML에 Insert질의문 추가

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

최종 IotController.java

package com.iot.controller;

import java.util.List;

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

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

@Controller
public class IotController {

	@Autowired
	private UserInfoService service;

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

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

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

		return "/hello_world";
	}

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

		service.insertUserInfo(userinfo);

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

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

		return "/hello_world";
	}

}

최종 UserInfoMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.iot.db.mapper.UserInfoMapper">

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

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

</mapper>
저작자 표시
신고

Spring - Mybatis이용 DB 연동

Programming/Java 2016.11.19 19:40 Posted by 파란크리스마스

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

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

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

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

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

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

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

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

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

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

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

MyBatis Domain 패키지 생성

MyBatis Mapper 패키지 생성

MyBatis Service 패키지 생성

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

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

user_info 예제 테이블 생성

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

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

MyBatis Domain 클래스 생성

package com.iot.db.domain;

public class UserInfo {

	// pk
	private String user_id;

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

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

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

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

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

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

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

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

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

MyBatis Mapper 인터페이스 생성

package com.iot.db.mapper;

import java.util.List;

import com.iot.db.domain.UserInfo;

public interface UserInfoMapper {

	public List<UserInfo> listUserInfo();

}

MyBatis Mapper XML파일 생성

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.iot.db.mapper.UserInfoMapper">

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

</mapper>

MyBatis Service 클래스 생성

package com.iot.db.service;

import java.util.List;

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

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

@Service
public class UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

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

}

컨트롤러 클래스 수정

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

package com.iot.controller;

import java.util.List;

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

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

@Controller
public class IotController {

	@Autowired
	private UserInfoService service;

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

}

hello_world.jsp에 데이터 전달

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

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

Hello World

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

</body>
</html>

실행결과

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

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

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

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


저작자 표시
신고

Spring MVC 프로젝트생성

Programming/Java 2016.11.19 18:08 Posted by 파란크리스마스

프로젝트 생성

test.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%

int sum = 1 + 2;

%>

결과 = <%=sum%>

</body>
</html>

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="archim" version="3.0">

	<display-name>iot</display-name>

	<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.html</welcome-file>
	</welcome-file-list>
</web-app>

스프링에서의 POST/GET 한글처리(web.xml)

출처 : Spring MVC : 스프링에서의 POST/GET 한글처리

	<filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

스프링에서의 MVC 설정(web.xml)

출처 : Spring MVC : @MVC와 DispatcherServlet에 대해서

주소 *.iot는 DispatcherServlet이 실행

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

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

MVC 컨트롤러 package 생성

MVC 컨트롤러 class 생성

package com.iot.controller;

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

@Controller
public class IotController {
	
	@RequestMapping(value = "/hello_world.iot", method = RequestMethod.GET)
	public String hello_world() {
		return "/hello_world";
	}

}

MVC 컨트롤러 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

Hello World

</body>
</html>

컨트롤더 package 자동으로 스프링 컨테이너 등록(iot-servlet.xml 추가)

<context:component-scan base-package="com.iot.controller"/>

확인

최종 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="archim" version="3.0">

	<display-name>iot</display-name>

	<!-- 스프링에서의 POST/GET 한글처리(web.xml) -->
	<filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 스프링에서의 MVC 설정(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>

	<!-- Session time 설정 -->
	<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.html</welcome-file>
	</welcome-file-list>
</web-app>

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

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


저작자 표시
신고

String 시큐리티

Programming/Java 2016.07.10 01:28 Posted by 파란크리스마스

출처 : Rednics Blog - 보안이 적용되지 않은 간단한 웹 어플리케이션 생성

WEB-INF\web.xml

	<!-- 스프링 스큐리티 관련 설정 / 시작 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/iot-datasource.xml <!-- DB 접속 정보 -->
			/WEB-INF/iot-mybatis.xml    <!-- 사용자조회에서 사용 -->
			/WEB-INF/iot-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>
	<!-- 스프링 스큐리티 관련 설정 / 종료 -->

WEB-INF\iot-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">

	<!-- 참고 사이트 http://springsource.tistory.com/77 -->

	<security:http pattern="/*.html" security="none" />
	<security:http pattern="/resources/**/*" security="none" />
	<security:http pattern="/login.do" security="none" />
	<security:http pattern="/loginfailed.do" security="none" />
	<security:http pattern="/logout.do" security="none" />
	
	<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="/admin/**" access="ROLE_ADMIN" />

		<security:form-login login-page="/login.do" default-target-url="/ShoppingMall2.do" authentication-failure-url="/loginfailed.do" />
		<security:logout logout-success-url="/logout.do" />
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>

			<security:jdbc-user-service
				data-source-ref="dataSource"
				users-by-username-query="select user_id username, pass password, 1 as enabled from tbluser where user_id = ?"
				authorities-by-username-query="select user_id username, 'ROLE_USER' authority from tbluser where user_id = ?" />

		</security:authentication-provider>
	</security:authentication-manager>
</beans>

Controller

package com.iot.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;

@Controller
public class LoginController {

	@RequestMapping(value = "/login.do", method = RequestMethod.GET)
	public String login(ModelMap modelMap) throws Exception {
		return "/login";
	}

	@RequestMapping(value = "/loginfailed.do", method = RequestMethod.GET)
	public String loginfailed(ModelMap modelMap) throws Exception {
		return "/loginfailed";
	}
	
	@RequestMapping(value = "/logout.do", method = RequestMethod.GET)
	public String logout(ModelMap modelMap) throws Exception {
		return "/logout";
	}
}

WEB-INF\jsp\login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
<style>
.errorblock {
	color: #ff0000;
	background-color: #ffEEEE;
	border: 3px solid #ff0000;
	padding: 8px;
	margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>
	<h3>Login with Username and Password (Custom Page)</h3>
 
	<c:if test="${not empty error}">
		<div class="errorblock">
			Your login attempt was not successful, try again.<br /> Caused :
			${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
		</div>
	</c:if>
 
	<form name='f' action="<c:url value='j_spring_security_check' />"
		method='POST'>
 
		<table>
			<tr>
				<td>사용자ID:</td>
				<td><input type='text' name='j_username' value=''>
				</td>
			</tr>
			<tr>
				<td>암호:</td>
				<td><input type='password' name='j_password' />
				</td>
			</tr>
			<tr>
				<td colspan='2'><input name="submit" type="submit"
					value="submit" />
				</td>
			</tr>
			<tr>
				<td colspan='2'><input name="reset" type="reset" />
				</td>
			</tr>
		</table>
 
	</form>
</body>
</html>

AuthenticationToken 확장

출처 : Syaku (샤쿠) | 스프링 시큐리티 커스텀 로그인 : Spring Security

IotAuthenticationToken.java

package com.iot.handler;

import java.util.Collection;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import com.iot.domain.UserInfo;

public class IotAuthenticationToken extends UsernamePasswordAuthenticationToken {

	// ----------------------------------- PRIVATE ATTRIBUTES
	private UserInfo userInfo = null;
	private String login_type;
	
	// ----------------------------------- CONSTRUCTOR
	public IotAuthenticationToken(
	    Object principal, 
	    Object credentials, 
	    Collection<? extends GrantedAuthority> authorities, 
	    UserInfo userInfo, 
	    String login_type
	) {
		super(principal, credentials, authorities);
		this.userInfo = userInfo;
		this.login_type = login_type;
	}

	// ----------------------------------- GET/SET TERS
	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public String getLogin_type() {
		return login_type;
	}

	public void setLogin_type(String login_type) {
		this.login_type = login_type;
	}
}

IotAuthenticationProvider.java

package com.iot.handler;

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

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

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

@Component
public class IotAuthenticationProvider implements AuthenticationProvider {
	
	@Autowired
	private UserInfoService service;

	@Autowired
	private HttpSession session;

	// ---------------------------------- PUBLIC METHODS
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		
		String username = authentication.getName();
		String password = (String) authentication.getCredentials();
		UserInfo userInfo = null;
		Collection<? extends GrantedAuthority> authorities;
		
		try {
			IotAuthDets authDetails = (IotAuthDets) authentication.getDetails();
			userInfo = service.selectUserInfo(username);

			if(userInfo!=null && userInfo.getDelete_yn().equals("Y")){
				throw new UsernameNotFoundException("User details not found with this username: " + username);
			}
			if (userInfo == null) {
				throw new UsernameNotFoundException("User details not found with this username: " + username);
			}

			if (!password.equals(userInfo.getPassword())) {
				throw new BadCredentialsException("비밀번호가 일치하지 않습니다.");
			}
			
			authorities = getAuthorities(userInfo.getAuthority());
			userInfo.setAuthorities(authorities);

			return new CMXAuthenticationToken(
					(authDetails.isSublogin() ? "sub," + userInfo.getUser_id() + "@" + userInfo.getKira_user() : userInfo.getUser_id()), 
					authentication.getCredentials(), 
					authorities, 
					userInfo,
					authDetails.getLoginType()
			);
			
		} catch (UsernameNotFoundException e) {
			throw new UsernameNotFoundException(e.getMessage());
		} catch (BadCredentialsException e) {
			throw new BadCredentialsException(e.getMessage());
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	private List<GrantedAuthority> getAuthorities(String role) {
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		authList.add(new SimpleGrantedAuthority("ROLE_USER"));
		
		if (role != null && role.trim().length() > 0) {
			if (role.equals("A")) {
				authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
			} else if (role.equals("S")) {
				authList.add(new SimpleGrantedAuthority("ROLE_MBER_MANAGER"));
			}
		}
		
		return authList;
	}

	@Override
	public boolean supports(Class<? extends Object> authentication) {
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication) && authentication.equals(UsernamePasswordAuthenticationToken.class);
	}
}

iot-security.xml

	<bean id="iotAuthenticationProvider" class="com.iot.handler.IotAuthenticationProvider"/>
	<security:authentication-manager alias="authenticationManager">
		<security:authentication-provider ref="iotAuthenticationProvider" />
	</security:authentication-manager>

JSP에서 로그인 정보 조회

출처 : Spring Security에서 화면에 사용자 정보, 권한에 따른 동적 메뉴 화면 구성 및 로그아웃 구성하기

<%@ page import="org.springframework.security.core.context.SecurityContextHolder"%> 
<%@ page import="org.springframework.security.core.Authentication"%>
<%@ page import="com.iot.handler.IotAuthenticationToken"%>
<%@ page import="com.iot.domain.UserInfo"%>

<%
Authentication auth = (Authentication)request.getUserPrincipal();
IotAuthenticationToken iotAuth = null;
if (auth!=null && auth instanceof IotAuthenticationToken) {
	iotAuth = (IotAuthenticationToken)auth;
}

// <sec:authentication property="userInfo" />
// <sec:authentication property="userInfo.email" />
System.out.println("user_info = " + iotAuth.getUserInfo());

// <sec:authentication property="login_type"/>
System.out.println("login_type = " + iotAuth.getLogin_type());
%>

<c:set> security값 설정

출처 : How to set value from<security:authentication/> to the parameter with <c:set>

<c:set var="login_type"><sec:authentication property="login_type"/></c:set>

로그인 타입 : ${login_type}

<c:if test="${login_type == 'LOGIN_TYPE_DAUM' || login_type == 'LOGIN_TYPE_DAUM'}">
	다음로그인
</c:if>

-

-

-

-

-

-

-->
저작자 표시
신고

Spring tiles

Programming/Java 2016.07.09 19:22 Posted by 파란크리스마스

출처 : Spring 3 MVC: Tiles Plugin Tutorial with Example in Eclipse

WEB-INF\web.xml

	<context-param>
		<param-name>spring.profiles.active</param-name>
		<param-value>tiles3</param-value>
	</context-param>

WEB-INF\intel4-tiles.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	

	<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".html" />
		<property name="templateMode" value="HTML5" />
		<property name="cacheable" value="true" />
	</bean>
	
	<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
		<property name="templateResolver" ref="templateResolver" />
	</bean>
	<bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
		<property name="templateEngine" ref="templateEngine" />
		<property name="order" value="1" />
		<property name="viewNames" value="thymeleaf/*" />
	</bean>

	<!-- Resolves view names to Tiles definitions -->
	<beans profile="tiles3">
		<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
			<property name="order" value="0"/>
		</bean>
	
		<!-- Configures Tiles 3-->
		<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
			<property name="definitions">
				<list>
					<value>/WEB-INF/jsp/tiles/tiles.xml</value>
					<!-- 
					<value>/WEB-INF/jsp/service/tiles.xml</value>
					<value>/WEB-INF/jsp/spiderview/tiles.xml</value>
					<value>/WEB-INF/jsp/spiderlive/tiles.xml</value>
					<value>/WEB-INF/jsp/customer/tiles.xml</value>
					<value>/WEB-INF/jsp/news/tiles.xml</value>
					<value>/WEB-INF/jsp/recruit/tiles.xml</value>
					<value>/WEB-INF/jsp/company/tiles.xml</value>
					<value>/WEB-INF/jsp/admin/tiles.xml</value>
					 -->
				</list>
			</property>
		</bean>
	</beans>

</beans>

WEB-INF\jsp\tiles\tiles.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC 
	"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">	

<tiles-definitions>
	
	<definition name="/*.blank" template="/WEB-INF/jsp/common/layout/blankLayout.jsp">
		<put-attribute name="content"	value="/WEB-INF/jsp/admin/{1}.jsp"/>
	</definition> 
	
	<definition name="/*" template="/WEB-INF/jsp/tiles/web_layout.jsp">
		<put-attribute name="header" value="/WEB-INF/jsp/tiles/web_header.jsp" />
		<put-attribute name="main" value="/WEB-INF/jsp/{1}.jsp" />
		<put-attribute name="footer" value="/WEB-INF/jsp/tiles/web_footer.jsp" />	
	</definition>
	
</tiles-definitions>

WEB-INF\jsp\tiles\web_layout.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<%@taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>

<!DOCTYPE HTML>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0 minimal-ui"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="black">
</head>

<body>

	<!-- head -->
	<tiles:insertAttribute name="header" />
	
	<!-- content -->
	<tiles:insertAttribute name="main" />

	<!-- footer -->
	<tiles:insertAttribute name="footer" />
	
</body>
</html>
저작자 표시
신고

JQuery - 페이지 정보 자동 생성

Programming/JavaScript, Sencha 2016.05.28 20:24 Posted by 파란크리스마스

pagination.js 파일

// 페이지 생성 함수
// 인자1 : JQuery 객체 - 페이지 정보를 출력될 객체
// 인자2 : 전체 페이지수
// 인자3 : 현재 페이지수
// 인자4 : 페이지 호출시 호출할 함수
function genPageNum(id_pagenum, totalPage, curPage, event) {
	
	// 블럭에 표시 페이지수
	var block_size = 10;
	
	// 초기화
	id_pagenum.empty();
	
	// 현재 블럭
	var block = Math.floor((curPage-1) / block_size);
	
	// 현재 블럭의 시작 페이지
	var block_start_pagenum = 10 * block;
	
	// 현재 블럭에서 마지막 페이지 
	var loop_count = block_size;

	// 현재 블럭에서 마지막 페이지 구하기
	if (block == Math.floor(totalPage / block_size) && (totalPage % block_size) > 0)  {
		loop_count = totalPage % block_size;
	}
	
	// 이전블럭 표시 (curPage > 10 이상이면 표시)
	if (curPage > block_size) {
		id_pagenum.append(
				"[<b><a href='javascript:listDevice("+
				(block * block_size) +
				", last_device_type);'>Prev</a></b>]");
	}
	
	// 페이지 수 만큼 반복
	for (pagenum = 1; pagenum <= loop_count; pagenum++) {
		// 현재 페이지 처리
		if ((pagenum + (block * block_size)) == curPage) {
			id_pagenum.append(
					"<b><font color=\"red\">"+(pagenum + (block * block_size))+"</font></b>");
		}
		// 현재 페이지 외 처리
		else {
			id_pagenum.append(
					"[<b><a href='javascript:pagination__page_move("+
					(pagenum + (block * block_size)) +
					"," + event+ ");'>"+
					(pagenum + (block * block_size)) +
					"</a></b>]");
		}
	}
	
	// 다음블럭 처리
	if (block < Math.floor(totalPage / block_size)) {
		id_pagenum.append(
				"[<b><a href='javascript:pagination__page_move("+
				(1 + ((block+1) * block_size)) +
				"," + event+ ");'>Next</a></b>]");
	}
}

// 페이지 선택시 호출 되는 함수
function pagination__page_move(pagenum, event) {
	if (event!=undefined) {
		event(pagenum);
	}
}

인자4에 전달될 함수 예제

function stock_page_move(pagenum) {
	listDevice(pagenum, last_device_type);
}

페이지 자동 생성 함수 호출

genPageNum($('#pagenum', currentDoc), result.totalPage, result.CurPage, stock_page_move);
저작자 표시
신고

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>
저작자 표시
신고


 

티스토리 툴바