1. Open Tomcat’s conf/web.xml file back up and find the JspServlet again.

  2. Add the following init parameter, which tells the Servlet to use Apache Ant with the JDK

    compiler to compile JSPs instead of the Eclipse compiler.

    1
    2
    3
    4
    <init-param>
        <param-name>compiler</param-name>
        <param-value>modern</param-value>
    </init-param>
    cs
  1. Tomcat doesn’t have a way to use the JDK compiler directly, so you must have the latest version of Ant installed on your system. You also need to add the JDK’s tools.jar file and Ant’s ant.jar and ant-launcher.jar files to your classpath. The easiest way to do this is to create a bin\setenv.bat file and add the following line of code to it (ignore new lines here), replacing the file paths as necessary for your system.

    set "CLASSPATH=C:\path\to\jdk8\lib\tools.jar;C:\path\to\ant\lib\ant.jar; C:\path\to\ant\lib\ant-launcher.jar"

    Of course, this applies only to Windows machines. For non-Windows environments, you should instead create a bin/setenv.sh file with the following contents, replacing the file paths as necessary for your system:

    export CLASSPATH=/path/to/jdk8/lib/tools.jar:/path/to/ant/lib/ant.jar: /path/to/ant/lib/ant-launcher.jar 


선 확인 해야할것: 
mysql 인코딩 처리 (여기 참조)

스프링에서 한글을 인식시키위해서 XML 설정에 아래와 같은 값을 집어 넣어준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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>       
    <init-param>          
        <param-name>forceEncoding</param-name>        
           <param-value>true</param-value>      
    </init-param>
</filter>
<filter-mapping>       
<filter-name>CharacterEncodingFilter</filter-name>    
   <url-pattern>/*</url-pattern>
</filter-mapping>
cs

참고자료: 
http://ultteky.egloos.com/10488541


Spring AOP

소프트웨어를 개발할때마다 공통적으로 부딪히는 문제들이 아래와 같이 있다. 

  • 로깅
  • 보안/인증
  • 트랜잭션
  • 리소스 풀링
  • 에러 검사
  • 정책 적용
  • 멀티 쓰레드 안전 관리 
  • 데이터 퍼시스턴스 

클래스 또는 컴포넌트로 모듈화하지만 문제들을 어떻게 해결하는것은 또 다른 문제 
일반적으로 문제영역(Problem Domain)은 핵심 관심과 횡단 관심으로 구성된다.

핵심 관심

 관심

패러다임 

모듈 

핵심관심 

OOP 

클래스/컴포넌트/서비스 

횡단관심 

AOP 

 관점

관점지향 프로그램은 관심의 분리를 통해 문제 영역을 핵심 관심과 횡단관심의 독립적인 모듈로 분해하는 프로그래밍 패러다임으로 다음과 같은 이점을 제공한다

  • 관심의 분리 도출
  • 비즈니스 로직 이해도 향상
  • 생산성 향상
  • 비즈니스 코드와 횡단 관심사들 간의 결합성 제거
  • 비즈니스 코드 재사용성 향상
  • 확장 용이
업무 기능과 시스템 기능을 분리하여 코드를 작성함으로써 서로 다른 관심사를 분리할 수 있으며, 업무 로직을 쉽게 이해할 수 있게 됨으로써 생산성의 향상을 가져올 수 있다.  또한 이처럼 업무 기능을 구현하는 코드와 시스템 기능을 구현하는 횡단 관심사들 간의 결합성이 제거되어 업무코드를 재사용하고 확장하기 쉽다

* 관점지향 용어 

 용어

설명 

어드바이스 

관점이 언제, 무엇을 하는지를 정의함. 

조인포인트 

관점이 플러그인되는 애플리케이션의 실행 위치 

포인트컷 

관점이 어드바이스하는 위치(어디서). 조인포인트의 범위를 축소함 

관점 

어드바이스와 포인트컷 결합. 무엇을 언제, 어디서 하는지를 정의함  

엮기 

관점을 대상 객체에 적용시키는 것 프록시 객체 생성 

도입 

기존 클래스에 새로운 메서드가 애트리뷰트를 추가하는것 


튜토리얼스 포인트 부연설명

AOP Terminologies:

Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These terms are not specific to Spring, rather they are related to AOP.

TermsDescription
AspectA module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement.
Join pointThis represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.
AdviceThis is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.
PointcutThis is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.
IntroductionAn introduction allows you to add new methods or attributes to existing classes.
Target objectThe object being advised by one or more aspects, this object will always be a proxied object. Also referred to as the advised object.
WeavingWeaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime.

아래 그림 설명


프로그램이 실행 과정 속에 여러 개의 조인포인트를 정의할수 있으며, 이둘중 어느위치에 포인트 컷을 지정하여 그 위치에서 어드바이스가 실행되도록 설정한다.


어드바이스란 관점의 실제 구현체로 포인터컷에 삽입되어 동작할 수 있는 코드로서, 관점이 무엇을 언제하는지 정의  


어드바이스 

설명 

before 

메서드가 호출되기 전에 어드바이스 기능이 발생함 

after 

메서드의 실행이 완료된 후 결과와 관계없이 어드바이스 기능이 발생함 

after-returning 

메서드의 실행이 성공적으로 완료된 후 어드바이스 기능이 발생함

after-throwing 

 메서드가 예외를 던진 후에 어드바이스 기능이 발생함 

around 

 메서드가 호출되기 전과 후에 어드바이스 기능이 발생함


조인포인트는 관점이 플러그인 되는 애플리케이션의 실행위치 즉, 관점의 코드가 애플리케이션의 정상적인 흐름 속에 삽입되어 새로운 행위를 추가하는 시점이다. 

  • 호출되는 메서드
  • 예외가 던져지는 위치
  • 필드 값이 수정될때 
관점이 모든 조인 포인트를 어드바이스 할 필요가 없기 때문에 포인트 컷으로 관점이 어드바이스하는 조인포인트의 범위를 축소시킨다. 
* 어드바이스가 관점의 언제 무엇을 하는지를 정의한다면, 포인트컷은 어디서를 정의한다. 포인트컷은 명확한 클래스와 메서드 이름 

Spring AOP 구현 

Spring AOP 설정 

설정을 위해서는 두 개의 모듈을 필요로 한다

  • spring-aop.jar
  • spring-aspects.jar
Maven을 사용하므로 pom.xml 파일에 종속성을 추가하면 된다. 

예제로 로깅 기능을 제공하는 관점을 구현해보다. 각 메서드가 호출될 때 해당 메서드가 호출되었다는 것을 로깅하는 코드를 작성하는 것은 전혀 어렵지는 않지만, 번거로우 일이다.
Spring AOP를 사용하면 쉽게 구현할 수 있고, 또한, 메서드가 추가될 때마다 로기 기능을 구현하지 않아도 새로운 메서드에 대한 로깅 기능을 사용할 수 있다.

- 관점 클래스 정의
Spring AOP는 관점을 자바 클래스로 정의하고, 어드바이스를 관점 클래스의 메서드로 구현한다.





의존성을 주입할 수 있는 대상은 다른 Spring 빈뿐만이 아니다

의존성을 주입할 수 있는 대상은 아래와 같다

  • 다른 Spring 빈 참조
  • 단순 값
  • 컬렉션
  • 널(null)
  • SpEL 표현식
다른 의존성 주입 대상들에 대해 사용하는 방법


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class CustomerRepositoryImpl implements CustomerRepository {
    
    private String driverClassName;
    private String url;
    private String username;
    private String password;
 
    public String getDriverClassName() {
        return driverClassName;
    }
 
    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }
 
    public String getUrl() {
        return url;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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.xsd">
 
    <bean id="hello" class="springHello.Hello"/>
    <bean id="customerService" class="service.CustomerServiceImpl">
        <constructor-arg ref="customerRepository"/>
    </bean>
    
    <bean id="customerRepository" class="repository.CustomerRepositoryImpl">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/order_system"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
</beans>
 
cs

아래 xml 코드의 customerRepository 부분의 property 값들과 같이 스프링 빈이 아니어도 의존성 주입을 할수 있다

* 예제용으로 보여주었을 뿐 데이터 베이스를 구현하기 위한 더좋은 방법이 있으므로 이방법으로 할필요없는 없다

단일 필드 값만이 아니라 컬렉션 타입의 필드에도 값을 주입할 수 있다. 


 필드 타입

요소 

설명 

Collection/List 

<list> 

중복 허용 값 목록 

Collection/Set 

<set> 

중복되지 않는 값 목록 

Map  

<map> 

어떤 타입이든 허용되는 이름 값 컬렉션 

Properties 

<props> 

Sring 타입의 이름-값 컬렉션 

앞의 데이터베이스 연결 정보를 컬렉션 타입으로 정의할 때 가장 적당한 타입은 Properties 타입니다. 우리는 다음과 같이 Properties 타입의 컬렉션 필드를 정의할 수 있다. 

1
2
3
4
5
6
public class CustomerRepositoryImpl implements CustomerRepository {
    private Properties properties;
    
    public void setProperties(Properties properties){
        this.properties = properties;
    }
cs

1
2
3
4
5
6
7
8
9
10
    <bean id="customerRepository" class="repository.CustomerRepositoryImpl">
        <property name="properties">
            <props>
                <prop key="driverClassName">com.mysql.jdbc.Driver</prop>
                <prop key="url">jdbc:mysql://localhost:3306/order_system</prop>
                <prop key="username">root</prop>
                <prop key="password"></prop>
            </props>
        </property>
    </bean>
cs

Properties 값을 이용할 경우 위와 같이의존성 주입을 할수 있다. 

키값을 불러오는 형식으로 아래와 같이 사용가능하다. 

1
2
3
4
private String driverClassName = properties.getProperty("driverClassName");
private String url = properties.getProperty("url");
private String username = properties.getProperty("username");
private String password = properties.getProperty("password");
cs

이외에도 

Map, List 를 이용하는 방법들이 있으니 교재를 참조 (p119 - p 121)

필드에 null값을 주입해야 하는 경우에는 다음과 같이 <null/> 요소를 사용한다.

1
<property name="nullableProparty"><null/></property>
cs

또한 Spring 표현식 언어인 SpEL(Sproing Expression Language)의 #{} 표현식을 사용하여 필드값을 주입할 수 있다. 

1
2
3
<bean>
    <property name="property" value="#{5}" />
</bean>
cs

Spring 표현식을 이용할수 있는 값들에 대해서는 교제 p122 에 있는 표를 참조하면 된다. 


3.5 어노테이션 

XML 설정 최소화

XML 설정 파일을 사용할 때 순수하가 POJO로 Spring 빈을 수현할 수 있으며, 앞에서 살펴본 바와 같이 소스 코드를 변경시키지 않고도 설정을 변경시키는 것만으로도 유지 보수를 쉽게 할수 있게 한다는 이점을 갖게된다 

그러나 Java 코드와 설정이 분리되어 프로그램의 이해를 어렵게 하고 Spring 빈 클래스가 많아지면 XML 설정도 많아져서 개발자들이 어플리케이션을 개발하는데 어려움을 겪게되는것도 사실이다. 

이런 문제를 해결하기 위해 아래와 같은 두가지 해결책이 있다. 

  • 자동 와이어링
  • 어노테이션 와이어링
자동와이어링은 XML설정 파일은 그대로 사용하면 Spring  빈 설정을 최소한으로 할 수 있ㄷ도록 하는 기능 

어노테이션 와이어링은 XML 설정 파일을 아예 사용하거지 않거나또는, 가능한 사용을 억제하고 어노테이션을 사용하여 Spring 빈을 설정할 수 있도록 하는 기능을 제공 

여기서 와이어링이란 의존성 주입을 통해 Spring 빈을 연결하는 것을 말한다. 

Spring 프레임워크는 다음과 같은 4가지 자동 와이어링 방식을 제공

 방식

autowire 애트리뷰트 

설명 

 이름

 byName

필드와 같은 이름 (또는ID)를 가지는 빈과 자동 와이어링

 타입

 byType

필드와 같은 타입의 빈과 자동 와이어링 

 생성자

contructor 

생성자 매개 변수의 타입과 일치하는 빈을 자동 와이어링1 

자동탐색 

 autodetect

먼저 생성자 자동 와이어링이 수행되고 실패하면 타입 와이어링이 수행됨  

다음과 같이 Bean 클래스가 정의되어 있다고 하자 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Bean1 {}
public class Bean2  {
    private Bean1 bean1;
    public void setBean1(Bean1 bean){
        this.bean1 = bean1
    }
}
public class Bean3 {
    private Bean1 bean1;
    public Bean3(Bean1 bean1){
        this.bean1 = bean1;
    }
}
 
<bean id="bean1" class="Bean1"/>
cs

byName 이 지정되면 필드명과 같은 이름을 가지는 빈을 찾아 자동으로 와이어링 시킨다

-> 이름 와이어링

아래는 Bean2 크래스의 필드명이 bean1이므로 빈 이름이 bean1인 빈을 찾아서 필드에 의존성을 주입한다. 

1
<bean id="bean2" class="Bean2" autowire="byName"/>
cs


byType 이 지정되면 필드와 타입의을 가지는 빈을 찾아 자동으로 와이어링 시킨다

-> 타입 와이어링

아래는 Bean2 클래스의 bean1필드의 타입이 Bean1 클래스이므로 class 애트리뷰트가 Bean1인 bean1 빈을 찾아서 필드에 의존성을 주입시킨다. 

1
<bean id="bean2" class="Bean2" autowire="byType"/>
cs



1
<bean id="bean3" class="Bean3" autowire="constructor"/>
cs



어노태이션 와이어링
XML 설정을 최소하 하기 위해 Spring 프레임 워크는 빈 와이어링 즉, 의존성 주입을 지원하는 어노테이션을 제공한다. 이러한 기능을 어노테이션 와이어링이라고 한다. 어노테이션 와이어링을 사용하기 위해서즌 먼저 XML 설정 파일에 context 네임스페이스를 추가해야 한다. 다음과 같이 <beans> 태그 안에 context 네임스페이스를 추가한다. 
1
2
3
4
5
6
7
8
9
10
<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="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-4.1.xsd">
    
<context:annotation-config/>
</beans>
cs

추가로 <context:annotation-config/>도 설정해 어노테이션 와이어링 사용할수 있게 한다. 

어노테이션을 사용한 의존성 주입에 사용할 수 있는 어노테이션은 다음과 같다. 


 어노테이션

제공자 

@Autowired 

Spring 

@Inject 

JSR-330 

@Resource 

JSR-250 

@Autowired 어노테이션은 Spring 프레임워크에서 제공하는 기본적인 어노테이션이다. 이 어노테이션은 필드 또는 생성자, setter 메서드에 적용할 수 있으며, 먼저 타입 와이어링을 시도한 후에 실패하면 이름 와이어링으로 후보 빈을 찾는다.

보통 아래와 같이 오토와이

1
2
3
4
public class CustomerServiceImpl implements CustomerService {    
    @Autowired
    private CustomerRepository repository;
}
cs

필드외에도 생성자와 setter 메서드에 @Autowired 애트리뷰트를 지정할 수도 있다. 

이제 XML 설정 파일에 의존성 주입을 하기 위한 설정을 생략해도 된다. 
만약 와이어링할 빈이 없는 경우 NoSuchBeanDefinitionException이 발생 
이떄 우리는 다음과 같은 두가지 방법을 사용할 수 있다. 

 방안

설정 

선택적 자동 와이어링 지정(null값 허용) 

@Autowired(required=false) 

 와이어링할 빈 지정(범위 한정)

@Qualifier("beanID") 


첫번째 방법은 와이어링을 반드시 해야 하는것은 아니라고 선택적 자동 와이어링을 지정하는것이다. 만약 자동 와이어링할 빈을 찾지 못한다면, 해당 필드에 저장되는 값은 null이 된다. 

1
2
3
import org.springframework.beans.factory.annotation.Autowired;
@Autowired(required=false)
private CustomerRepository repository;
cs

또 다른 방법은 와이어링할 빈을 지정하는 것. 달리말하면, 찾을 수 있도록 범위를 한정하는 것.ㅣ @Qualifier 어노테이션의 괄호 안에 와이어링할 빈 이름을 지정한다.

1
2
3
import org.springframework.beans.factory.annotation.Qualifier;
@Qualifier("customerRepository")
private CustomerRepository repository;
cs


Spring 프레임워크가 제공하는 @Autowired 어노테이션 외에도 Java의 JSR-330사양에 있는 @Inject 어노테이션을 사용할 수 있다. JSR-330 사양은 Java 언어가 제공하는 의존성 주입을 표준 어노테이션이 정의되어 있다. 이들 어노테이션을 사용하려면 클래스 경로에 표준 어노테이션을 구현한 jar 파일이 있어야 한다 . 우리는 Maven을 사용하므로 pom.xml 파일에 종종석을 추가하면 된다 .

1
2
3
4
5
<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>
cs


자동 빈 발견 

XML 설정을 사용하지 않용하지 않고도 오노테이션을 사용하여 Spring 빈을 설정 할수 있다. 


 어노테이션

설명 

@Component 

클래스가 Spring 빈임을 표시하는 범용 어노테이션 

@Service 

클래스가 서비스를 정의하고 있으ㅁ을 표시하는 @Componenet 

@Repository 

클래스가 데이터 레파지토리를 정의하고 있음을 표시하는 @Component 

@Controller 

 클래스가 Spring MVC 컨트롤러를 정의하고 있음을 표시하는 @Component

@Component 어노테이션은 가장 범용적인 Spring 빈 설정 어노테이션이다. 다음과 같이 Spring 빈 클래스에 지정하면 된다. 이때 디폴트 Spring 빈의 이름은 클래스명의 첫 문자를 소문자로 바꾼 이름이 된다. 아래 예의 Spring 빈은 customerRepositoryImpl 이된다 

1
2
3
@Component
public class CustomerRepositoryImpl implements CustomerRepository {
}
cs

Spring 빈의 이름을 변경하고 싶다면 괄호안에 이름을 지정하면 된다

1
2
3
@Component("customerService")
public class CustomerRepositoryImpl implements CustomerRepository {
}
cs

@Component 어노테이션 대신에 Spring 빈의 성격에 따라 @Service, @Repository, @Controller 어노테이션을 사용할 수 있다. @Service 어노테이션은 Spring 빈이 업무 로직을 구현한 서비스임을 나타낸다. 

1
2
3
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {
}
cs

@Repository  어노테이션은 Spring 빈이 데이터 액세서 기능을 제공하는 레파지토리임을 나타낸다. 

1
2
3
@Repository("customerRepository")
public class CustomerRepositoryImpl implements CustomerRepository {
}
cs

@Controller 어노테이션은 Spring MVC에서 컨트롤러임을 나타낸다. 

이렇게 어노테이션으로 정의한 Spring 빈을 자동으로 발견할 수 있도록 XML 설정 파일에 설정해야만 한다. 이때 XML 설정 파일에는 <context:annotation-config/> 대신에 자동으로 Spring 빈을 발견하기 위한 설정만 추가하면 된다 

1
<context:component-scan base-package="com.ensoa.order"/>
cs

base-package애트리뷰트에 지정된 패키지오 서브 패키지를 스캐닝 하여 Spring 빈을 찾아 인스턴스를 생성하고 IoC컨테이ㅅ너 즉, 어플리케이션 컨텍스트에 자동으로 등록된다. 편리하지만 POJO코드보다는 조금 복잡해진다. 그래도 직관적으로 이해할 수 있으므로 아주 유용한 기능이다.

** 중대형 프로젝트는 수십명의 작업자가 같이 작업을 하므로 자동 어노테이션보다는 기존 XML방식으로 의존성을 서술한 방식을 주로 이용한다. XML 방식이 전체적인 의존성 주입방식 파악에 훨씬 유용하기 때문이다

'Java > Spring Framework' 카테고리의 다른 글

스프링 프레임워크 마이그레이션 3.2.9 to 4.3.5  (0) 2016.12.22
Spring 한글설정  (0) 2015.03.19
Spring AOP  (0) 2015.01.19
스프링 학습 개발 도구 설치  (0) 2015.01.13
프레임 워크 배우기 좋은 웹사이트  (0) 2014.11.04

Java SDK 다운로드 

http://www.oracle.com/technetwork/java/javase/downloads/index.html



개발툴: Spring Tool Suite

https://spring.io/tools/sts

(나중에 jetbrains Intellij 사용)



한글을 이용하기 위한 이클립스 설정 설정 

Window - Preferences - General - Content Types



Java Properties File 항목을 클릭하고 마찬가지로 Default encoding을 UTF-8로 바꾸고 Update 버튼 클릭



Web-> JSP Files 에서도 Encoding을 UTF-8로 바꾼다

Maven 설치 및 설정 

http://maven.apache.org/download.cgi


자기 OS 버전에 맞는 파일을 다운로드 하여 압축을 풀고 패스 경로를 지정해준다




Apache 톰캣서버 - 기존방법대로 설치

톰캣 압축 파일 OS버전에 맞춰 톰캣 7.0 다운로드 

Eclipse Preferences 에서 runtime environment 에서 tomcat 7.0 설정

File -> New -> Other -> Server 로 가서 Tomcat 서버 추가


Tomcat 서버 클릭후 Tomcat 서버 압축 푼곳에 경로 설정


서버추가후 Servers 폴더가 나타나는데 

server.xml 안에 두부분 아래와 같이 수정 (한글처리를 위해)

1
<Connector connectionTimeout="20000" port="9999" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
cs
1
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"  URIEncoding="UTF-8"/>
cs


메이븐을 활용한 프로젝트 생성

메이븐 기본개념 정리 블로그 - 

http://dimdim.tistory.com/entry/Maven-%EC%A0%95%EB%A6%AC

메이븐 설치후 프로젝트가 들어갈 워크스페이스 폴더에 위치 시킨다

폴도 윈도우 안에 마우스를 두고 오른쪽을 클릭하면 여기에 명령창 열기가 컨텍스트 메뉴에 추가되는데 클릭한후 위에 명령어를 실행한다. 


첫번째 프로픔트가 깜빡거릴때 엔터키를 누르고

Choose a number :: 6 :: 다음에 깜빡거릴때 엔터기를 누른다 이때 받아들인 버전은 archetype 1.1 버전을 말한다. 

세번째 프롬프트가 'groupId' :: 다음에 깜빡거릴때 com.ensoa



Eclipse 로 Maven 프로젝트 만들기


요소

 설명

<groupId>

프로젝트 그룹ID 

<artifactId> 

프로젝트 아티팩트 ID 

<version>

버전 

<packaging> 

패키징 .방식 : jar, war, ear 

<dependencies> 

이 프로젝트가 의존하는 다른 프로젝트 정보 

메이븐 프로젝트 의존성 설정

프로젝트가 의존하는 다른 프로젝트에 대한 정보는 <dependancy> 요소로 설장한다 . <dependency> 요소 안에는 다음 서브 요소를 포함한다. 


 요소

설명 

<groupId> 

의존 프로젝트 그룹 ID 

<artifactId> 

의존 프로젝트 아티팩트 ID 

<version> 

버전 

Ex) 프로젝트에서 스프링 프레임 워크를 사용하고자 한다면, Spring 프레임 워크 의존성을 추가해야 한다. 

1
2
3
4
5
6
7
<dependencies>
    <dependency>
     <groupdId>org.springframework</groupdId>
     <artifactId>spring-context</artifactId>
     <version>4.1.1.RELEASE</version>
    </dependency>
</dependencies>
cs

스프링 프레임 워크를 사용하기 위해서는 spring-context 모듈만 필요한것은 아님

스프링 프레임워크는 19개의 독립적인 모듈 즉, jar 파일로 구성되어 있다. 

실제 Maven으로 다운로드한 pom.xml을 보면 많은 프로젝트가 의존하고 있는것을 볼수 있다


의존성을 설정할 때 <scope> 요소를 사용하여 의존성 범위를 지정 가능 


 설정 값

설명 

compile 

컴파일 시에 필요함. 실행과 테스트 시에도 포함됨. 디폴트 값

runtime 

실행시 필요함. 컴파일에는 필요하지 않지만, 실행 할 때 필요하며 배포 할때 포함됨 

provided 

컴파일할 때는 필요하지만, 실행 시에는 컨테이너 등에서 기본으로 제공하기 때문에 배포할 필요가 없음.  

test 

테스트 코드를 컴파일 할때 필요함. 테스트 시에는 포함되지만, 배포 시에는 제외됨 


레파지토리 



Session



세션 타임 설정을 위한 두가지 방법 

1. web.xml에 직접 설정하는 방법 

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" ... version="2.5">
  ...
  ...
  ...
  <session-config>
    <session-timeout>100</session-timeout<!-- 분단위  -->
  </session-config>
</web-app>
cs

2. jsp 페이지에 임의로 설정

1
2
3
<%
  session.setMaxInactiveInterval(100 * 60); //  단위
%>
cs

 

아직 db에 대한 학습을 하지 않앟기때문에 web.xml에 임의로 저장하여 활용

 web.xml에 파라미터로써 로그인 ID와 Password를 저장하고 활용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
               http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5"
 <!-- 기존 내용  -->
 <!-- 아래의 내용만 삽입  -->
 <context-param>
   <param-name>MasterID</param-name>
   <param-value>jspbook</param-value>
 </context-param>
 <context-param>
   <param-name>MasterPassword</param-name>
   <param-value>112233</param-value>
 </context-param>
 <!-- 삽입 끝  -->
 
</web-app>
cs


login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
 <html>
 <head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <title>로그인</title></head>
 </head>
 <body>
관리자  (Master)로 로그인하세요.<br/>
 <form action="loginProcess.jsp" method="post">
 ID : <input type="text" name="id"><br/>
 Password : <input type="password" name="pw"><br/>
 <input type="submit" value="전송">
 </body>
 </html>
cs

loginProcess.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<%@ page contentType="text/html;charset=utf-8" %>
<%
 String storedID = application.getInitParameter("M
asterID");  
 String storedPW = application.getInitParameter("M
asterPassword");  
 String id = request.getParameter("id");
 String pw = request.getParameter("pw");
 if (id.equals(storedID) && pw.equals(storedPW)) { 
   session.setAttribute("MasterLoginID", id); 
%>
<html>
<head><title>로그인 처리</title></head>
<body>
로그인에 성공했습니다. <br/><br/>
<a href="loginCheck.jsp">로그인 체크</a>
</body>
</html>
<%
 } else if (id.equals(storedID)) { 
%>
<script>
alert("패스워드가 다릅니다.");  
history.go(-1);
</script>
<%
 } else {  
%>
<script>
alert("로그인  ID가 다릅니다.");
history.go(-1);
</script>
<%
 }
%>
cs

※ 대부분의 JSP 페이지 및 Servlet은 session 기본 객체를 사용하게 된다. 따라서 로그인과관련된 코딩이 없어도 session 기본 객체는 이미 생성되며 session 기본 객체의 생성 시점

로그인 성공 시점은 일치하지 않는다는 점에 유의해야 한다. 이는 곧 사용자가 로그아웃

하더라도 기존의 session 기본 객체는 계속 유지될 수 있다는 것을 의미한다.


로그인 지속 여부 판단

로그인이 되어 있다는 것을 판단하는 방법은 session 기본 객체에 로그인 표식을 위한 속성

이 존재하는지의 여부를 판단하는 것으로 이루어진다.

loginCheck.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ page contentType="text/html;charset=utf-8" %>
<%
 String masterID = (String)session.getAttribute("M
asterLoginID");
 boolean isLogin = false;
 if (masterID !null) {
   isLogin = true; 
 }
%>
<html>
<head><title>로그인여부 검사</title></head>
<body>
<%
   if (isLogin) {
%>
ID "<%masterID %>"로 로그인 한 상태  <br/><br/>
<a href="logout.jsp">로그아웃</a>
<%
   } else {
%>
로그인하지 않은 상태
<%
   }
%>
</body>
</html>
cs

로그아웃 처리 logout.jsp

session.invalidate() 메소드를 통해 세션을 종료하면 된다 

1
2
3
4
5
6
7
8
9
10
11
<%@ page contentType="text/html;charset=utf-8" %>
<%
 session.invalidate();
%>
<html>
<head><title>로그아웃</title></head>
<body>
로그아웃하였습니다. <br/><br/>
<a href="login.html">처음부터</a>
</body>
</html>
cs

아래와 같이 세션에서 객체 속성을 삭제하는 방법으로도 처리 가능 

1
session.removeAttribute("MasterLoginID");
cs



로그인 처리를 위해 쿠키 대신에 세션을 사용하는 이유는?

쿠키는 클라이언트에도 정보가 저장되서 관리가 어렵지만 세션을 이용하면 서버에서만 데이터를 관리하면 되기때문에 관리가 용이하고 보안 측면에서 더 강화된다 



Cookie

쿠키(cookie)는 인터넷 사용자가 어떠한 웹 사이트를 방문할 경우 그 사이트가 사용하고 있

는 서버에서 인터넷 사용자의 컴퓨터에 설치하는 작은 기록 정보 파일을 일컫는다. 쿠키에

담긴 정보는 인터넷 사용자가 같은 웹 사이트를 방문할 떄마다 읽혀서 서버로 전송되고 새로운정보로 바뀔 수도 있다.



두 번째 인자로서 쿠키의 값을 지정

Cookie 객체의 멤버 메소드

Cookie의 생성 및 활용

1
2
3
4
<%
  Cookie cookie = new Cookie("cookieName", "cookieValue");
  response.addCookie(cookie);
%>
cs

Cookie 클래스 생성자의 첫 번째 인자로서 쿠키의 이름을, 두 번째 인자로서 쿠키의 값을 지정

createCookie.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- createCookie.jsp -->
<%@ page contentType="text/html;charset=utf-8" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.util.Date" %>
<%
    Cookie cookie = new Cookie("name", URLEncoder.encode("jspbook 쿠키 테스트"));
    Cookie cookie2 = new Cookie("date", new Date().toString());
    response.addCookie(cookie);
    response.addCookie(cookie2);
%>
<html>
<head><title>쿠키생성</title></head>
<body>
쿠키 이름: <%cookie.getName() %><br/>
쿠키 값: <%cookie.getValue() %><br/>
<br/>
쿠키 이름: <%cookie2.getName() %><br/>
쿠키 값: <%cookie2.getValue() %>
<p><a href="getCookies.jsp">Next Page to view the cookie value</a></p>
</body>
</html>
cs

실행화면





쿠키 생성 및 응답전송 단계: JSP를 활용하여 서버 측에서 쿠키를 생성한다. 이렇게 생성

된 쿠키는 응답 데이터와 함께 브라우저로 전송된다.

쿠키 저장 단계: 웹 브라우저는 응답 데이터에 포함된 쿠키를 쿠키 저장소에 보관한다. 

대부분의 경우 하드디스크의 파일 형태로 저장된다.

쿠키 요청전송 단계: 한번 저장된 쿠키는 웹 브라우저에서 서버로 요청을 보낼 때마다 함

께 전송된다. 웹 서버는 웹 브라우저가 전송한 쿠키에서 필요한 데이터를 읽어서 필요한 

작업을 수행할 수 있다.

쿠키의 전송은 1)응답전송과 2)요청전송으로 나뉜다는 점유의하자. 응답전송은 서버가 

생성된 후 서버에서 브라우저로 한 번만 일어난다. 하지만 요청전송은 일단 웹 브라우저에 

쿠키가 저장되면 쿠키가 삭제되기 전까지 매번 웹 서버에 전송된다. 그러므로 쿠키를 활용

해서 지속적으로 브라우저로부터 데이터를 받아낼 수 있으며, 브라우저를 닫은 이후에 다시 

브라우저를 열어서 해당 사이트로 접속할 때에도 전송된다는 점에 유의하자. 


서버 측에서 전송받은 쿠키의 데이터 읽어오기

Cookie[] cookies = request.getCookies();

getCookies.jsp 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page contentType="text/html;charset=utf-8" %>
<%@ page import="java.net.URLDecoder" %>
<html>
<head><title>쿠키 목록</title></head>
<body>
쿠키 목록<br/>
<%
   Cookie[] cookies = request.getCookies();
   if (cookies !null && cookies.length > 0) {
       for (int i = 0 ; i < cookies.length ; i++) {
%>
<%cookies[i].getName() %>=<%URLDecoder.decode(c
ookies[i].getValue()) %><br/>
<%
       }
   } else {
%>
전송 받은 쿠키가 없습니다.
<%
   }
%>
</body>
</html>
cs

※ 쿠키 값이 인코딩되었을 가능성이 있으므로 URLDecorder.decode( ) 메소드를 활용해서 쿠키 값을 디코딩하는 메소드를 활용하면서 쿠키 값을 얻어와야 한다.

쿠키삭제 

아래와같은 방법으로 쿠키 삭제 

1
2
cookie.setMaxAge(0);
response.addCookie(cookie);
cs


deleteCookies.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@ page contentType="text/html;charset=utf-8" %>
<%@ page import = "java.net.URLEncoder" %>
<%
 Cookie[] cookies = request.getCookies();
   if (cookies !null && cookies.length > 0) {
       for (int i = 0 ; i < cookies.length ; i++) {
           if (cookies[i].getName().equals("name
")) {
               cookies[i].setMaxAge(0);
               response.addCookie(cookies[i]);
           }
       }
   }
%>
<html>
<head><title>쿠키 삭제</title></head>
<body>
name 쿠키를 삭제합니다.
<p><a href="getCookies.jsp">Next Page to view the c
ookie value</a></p>
</body>
</html>
cs


쿠키의 유효 시간을 지정하지 않은 경우 웹 브라우저를 닫으면 쿠키는 자동으로 삭제되며 이후에 웹 브라우저를 실행할 때에 지워진 쿠키는 서버로 요청전송되지 않는다. 쿠키의효 시간을 설정하면 웹 브라우저를 닫더라도 유효 시간이 남아 있으면 해당 쿠키가 삭제되지 않고 이후 요청전송될 수 있다.


create1hourCookie.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 <%@ page contentType="text/html;charset=utf-8" %>
 <%
    Cookie cookie = new Cookie("cookieTime", "1 hour");
    cookie.setMaxAge(60 * 60); 
    response.addCookie(cookie);
 %
 
<html>
<head><title>쿠키유효시간설정</title></head>
<body>
유효시간이  1시간인  cookieTime 쿠키 생성.
<p><a href="getCookies.jsp">Next Page to view the c
ookie value</a></p>
</body>
</html>
cs


쿠키를 이용한 ID 기억하기 구현


login2.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 <%@ page contentType="text/html;charset=utf-8" %>
 <html>
 <head><title>로그인</title></head>
 <%
  boolean isIDShow = false;
  String id = null;
  Cookie[] cookies = request.getCookies();
  if (cookies !null && cookies.length > 0) {
    for (int i = 0 ; i < cookies.length ; i++) {
      if (cookies[i].getName().equals("id")) {
       isIDShow = true;
       id = cookies[i].getValue();
      }
    }
  }
 %>
 <body>
관리자  (Master)로 로그인하세요.<br/>
 <form action="loginProcess2.jsp" method="post">
 <%
  if (isIDShow) {
 %>
 ID : <input type="text" name="id" value="<%= id %>">
 <input type="checkbox" name="idstore" value="store" 
checked>ID 기억하기
 </input><br/>
 <%
  } else {
 %>
 ID : <input type="text" name="id">
 <input type="checkbox" name="idstore" value="store
">ID 기억하기</input><br/>
 <%
  }
 %>
cs

login2.jsp는 간단한 로그인 폼 생성 페이지이지만 브라우저로부터 전송된 쿠키 정보 중 "id" 이름의 쿠키가 있는지 확인하여 그 쿠기가 있다면 ID 정보를 폼 입력에 미리 넣어주는 역할을 한다

loginProcess2.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<%@ page contentType="text/html;charset=utf-8" %>
<%
 String storedID = application.getInitParameter("M
asterID");  
 String storedPW = application.getInitParameter("M
asterPassword");  
 String id = request.getParameter("id");
 String pw = request.getParameter("pw");
 if (id.equals(storedID) && pw.equals(storedPW)) { 
   session.setAttribute("MasterLoginID", id);
%>
<html>
<head><title>로그인 처리</title></head>
<body>
로그인에 성공했습니다. <br/><br/>
<a href="loginCheck.jsp">로그인 체크</a
</body>
</html>
<%
   String IDStore = request.getParameter("idstore");
    if (IDStore !null && IDStore.equals("store")) 
{
      Cookie cookie = new Cookie("id", id);
      response.addCookie(cookie);
     out.println("<a href='login2.jsp'>로그인 화면 다
시 보기</a>");
   }
 } else if (id.equals(storedID)) { 
%>
<script>
alert("패스워드가 다릅니다.");  
history.go(-1);
</script>
<%
 } else {
%>
<script>
alert("로그인  ID가 다릅니다.");
history.go(-1);
</script>
<%
 }
%
gcs

getInitParameter 와 getParameter 차이점

getInitParameter 

 web.xml 에다가 지정해둔 파라미터들의 값을 얻어 올수 있다.. 불변의 값들을 미리 xml 에다가 적어놓구 필요할때마다 호출해서 사용

getParameter 

리퀘스트 범위내에서 Parameter 값을 얻어오는 것. 전의 페이지에서 값을 넘겨주면 이 메소드를 활용하여 값ㅇ르 받아온다 


※ setPath() 메소드의 일반적인 활용법

일반적으로 쿠키는 웹 애플리케이션에 포함된 대부분의 JSP, 서블릿에서 공통으로 사용되는 

경우가 많기 때문에 대부분의 쿠키는 경로를 “/”로 지정한다. 즉, 생성된 쿠키가 cookie라면 

cookie.setPath("/")를 호출하면 된다. 

'Java > Servlet, JSP' 카테고리의 다른 글

HTTP 프로토콜의 이해  (0) 2014.11.05

Spring MVC에서 정적 자원(css, js, etc)을 처리해본 경험

ResourceHttpRequestHandler

URL 패턴에 따라 정적 자원 요청을 처리

HTTP 캐시 설정 기능 제공

설정 간소화 기능 제공

:Java 기반 설정시 WebMvcConfigure

Gradle을 이용해서 build 자동화


프로젝트 구조

backend 

 - src

      - main 

                --java    

    -- resource

       - test

frontend 

- package.json

- bower.json

- groundfile.js

- src

-- assets

-- helpers

--layouts

--libs

-- pages


Backend 관리 

Sprinb boot, Spring I/O Platform, 공용 컴포넌트

Thymeleaf

html태그 /속성 기반의 템플릿 엔진

FrontEnd 관리

NPM 

BOWER 

GRUNT 

usermin

Fingerprinting : grunt-filerev 를통해 작동 

캐쉬를 효율적으로 이용하기 위해 이용

템플릿 생성: assemble

프론트 엔드 개발이 분리된 이유

Dependancy management

modularity

tests

build automation


FrontEnd의 자원 사용법

FrontEnd 의존성 활용법

WebJars 

Client-side 웹 라이브러리를 JAR로 묶어서 제공하는 서비스

JVM 기반 빌드 도구를 지원(maven 저장소)

-> frontend.jar로 만든후 backend 모듈에 의존성을 추가(Gradle로 통합)

frontend를 빌드후 jar로 만들기


개발과 배포는 다르다

배포시에는 최적화된 자원을 쓴다

개발시에는 작성죽인 css, js를 사용

backend 환격에 따른 자원 접근 전략 변경

ex) if(개발) { 개발용} else { 배포용 }


(time leaf)타임 리프: 프론트엔드가 개발한 환경 그대로 스프링에서 그대로 쓸수 있다. 

핸들바를 스프링측에 이미 있다. 

Spring 4.1 fingerprinting과 자원 최적화가 Spring에서 runtime 레벨에서 제공해준다.

참고 기트허브 gihub.com/arawn/resource-handling-in-springmvc


HTTP 프로토콜: 웹 브라우저와 웹 서버 사이의 데이터 통신 규칙

'Java > Servlet, JSP' 카테고리의 다른 글

스터디 11장 정리 - 세션과 쿠키  (0) 2015.01.07

스프링 튜토리얼

http://www.codejava.net/frameworks/spring/spring-mvc-beginner-tutorial-with-spring-tool-suite-ide

'Java > Spring Framework' 카테고리의 다른 글

스프링 프레임워크 마이그레이션 3.2.9 to 4.3.5  (0) 2016.12.22
Spring 한글설정  (0) 2015.03.19
Spring AOP  (0) 2015.01.19
스프링 스터디 - 의존성 주입 대상  (0) 2015.01.14
스프링 학습 개발 도구 설치  (0) 2015.01.13

+ Recent posts