728x90

프로젝트 생성

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>


728x90
728x90

출처 : 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>

-

-

-

-

-

-

-->
728x90
728x90

출처 : 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>
728x90
728x90

출처 : 자바에서 메일 보내는 방법 - 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>
728x90
728x90

출처 : 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>

-

-

-

-

-

-

728x90
728x90

출처 : 개발하는 씽매려기 :: 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>
728x90
728x90
출처 : 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");
728x90
728x90

출처 : 

환경설정

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>
728x90

+ Recent posts