반응형

https://penthegom.tistory.com/48

 

[Spring Boot]Spring MVC JSP 웹 튜토리얼(인텔리제이용 intelliJ) - 1

이 글에서는 스프링 부트 프레임 워크를 사용하여 스프링 MVC 웹 애플리케이션을 만들고 부트 스트랩하는 방법을 설명하겠다. JSP를 웹 애플리케이션의보기로 사용합니다. 이 응용 프로그램에 사용되는 도구 및 기..

penthegom.tistory.com

앞서 기본 Spring Boot MVC 를 만들어봤다. 이어서 이제 Mybatis와 PostgreSQL을 연결하는 방법을 설명하겠다.

이 응용 프로그램에 사용되는 도구 및 기술은 다음과 같다.

 

  • Spring Boot 2.1.x
  • Tomcat Embedded (Spring Boot 내장)
  • JavaSE 1.8
  • Maven
  • Mybatis
  • PostgreSQL 9.6.15
  • IntelliJ IDEA Ultimate 

 

프로젝트 구조(TREE)

1. DB설치 및 테이블 생성

Oracle, PostgreSQL, MySQL 등등 DB툴을 설치 해야한다. 여기서는 PostgreSQL을 사용하기로 한다.

이번 튜토리얼을 하기 위해 test라는 DB스키마를 생성한다.

 

1
2
3
4
5
6
7
8
CREATE TABLE test (
    id integer NOT NULL,
    name varchar NULL,
    CONSTRAINT test_pkey PRIMARY KEY (id)
);
 
INSERT INTO test (id, "name")
VALUES(1'펜다곰'),(2'홍길동');
cs

 

2. 각종 소스

 

- pom.xml

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.penthegom.example</groupId>
    <artifactId>penthegomdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>penthegomdemo</name>
    <description>Demo project for Spring Boot</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
 
        <!-- JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
 
cs

 

- application.yml(application.properties 를 application.yml로 변경후 적읍시다! 한글주석과 트리형태로 관리가 됩니다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
spring:
  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
    static-path-pattern: /resources/**
  #DB 설정
  datasource:
    url: jdbc:postgresql://127.0.0.1:5432/tutorial
    driver-class-name: org.postgresql.Driver
   username: penthegom
   password: penthegom
  #JSP 바로적용 설정
  devtools:
    livereload:
      enabled: true
#로그 레벨
logging:
  level:
    # 쿼리 보기
    com.penthegom.example.penthegomdemo: DEBUG
 
cs

 

 

- DatabaseConfig.java

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
package com.penthegom.example.penthegomdemo.config;
 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@MapperScan(basePackages="com.penthegom.example.penthegomdemo.mapper")
@EnableTransactionManagement
public class DatabaseConfig {
 
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/postgresql/*.xml"));
        return sessionFactory.getObject();
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
      final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
      return sqlSessionTemplate;
    }
}
cs

 

- HelloController.java

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
package com.penthegom.example.penthegomdemo.controller;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import com.penthegom.example.penthegomdemo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.util.List;
 
@Controller
public class HelloController {
 
    @Autowired
    TestService testService;
 
    @RequestMapping("/")
    public String index() {
 
        return "index";
    }
 
    @RequestMapping("/query")
    public @ResponseBody
    List<Test> query() throws Exception{
        return testService.getAll();
    }
}
 
cs

 

- Test.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.penthegom.example.penthegomdemo.dto;
 
public class Test {
    private String id;
    private String name;
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}
cs

 

- TestMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.penthegom.example.penthegomdemo.mapper;
 
import java.util.List;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import org.springframework.stereotype.Repository;
 
@Repository
public interface TestMapper {
 
    public List<Test> getAll() throws Exception;
    
}
 
cs

 

- TestService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.penthegom.example.penthegomdemo.service;
 
import java.util.List;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import com.penthegom.example.penthegomdemo.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
 
@Service
public class TestService {
 
    @Autowired
    TestMapper testMapper;
    
    public List<Test> getAll() throws Exception{
        return testMapper.getAll();
    }
}
 
cs

 

- test.xml

1
2
3
4
5
6
7
<?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.penthegom.example.penthegomdemo.mapper.TestMapper">
    <select id="getAll" resultType="com.penthegom.example.penthegomdemo.dto.Test">
        SELECT * FROM test
    </select>
</mapper>
cs

 

3. 실행 결과

 

반응형
반응형

spring boot 1.x 버전대

- application.properties

server.jsp-servlet.init-parameters.development=true

 

spring boot 2.x 버전대

dependency 추가

1
2
3
4
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
cs

application.properties 추가

JSP 바로적용 설정

devtools.livereload.enabled=true

반응형
반응형

이 글에서는 스프링 부트 프레임 워크를 사용하여 스프링 MVC 웹 애플리케이션을 만들고 부트 스트랩하는 방법을 설명하겠다. JSP를 웹 애플리케이션의보기로 사용합니다.

이 응용 프로그램에 사용되는 도구 및 기술은 다음과 같습니다.

 

 

  • Spring Boot 2.1.x
  • Tomcat Embedded (Spring Boot 내장)
  • JavaSE 1.8
  • Maven
  • IntelliJ IDEA Ultimate 

 

프로젝트 구조(TREE)

 

1. 프로젝트 추가

 

2. 실행해보기(오류 발생)

 

우측 상단에 빨간펜으로 칠한 실행버튼을 누르면 프로젝트를 받자마자 에러가 납니다.

properties 에 db관련정보가 없어서 에러가 납니다. 

방법은 db접속정보를 넣어주거나 일단 tutorial이니 어노테이션 하나로 처리합시다.

 

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

 

 

실행이 잘 성공한다면 아래와같이 나온다.

 

 

 

3. 각종 소스

 

- pom.xml

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.penthegom.example</groupId>
    <artifactId>penthegomdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>penthegomdemo</name>
    <description>Demo project for Spring Boot</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
 
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
 
        <!-- JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
 
cs

- application.yml(application.properties 를 application.yml로 변경후 적읍시다! 한글주석과 트리형태로 관리가 됩니다.)

1
2
3
4
5
6
spring:
  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
    static-path-pattern: /resources/**
cs

- index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ 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>JSP - Hello World Tutorial - penthegom</title>
</head>
<body>
<%= "Hello World!" %>
Hi penthegom !!
</body>
</html>
cs

 

- test.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
resources test
</body>
</html>
cs

 

- HelloController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.penthegom.example.penthegomdemo.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class HelloController {
 
    @RequestMapping("/")
    public String index() {
        return "index";
    }
}
 
cs

 

4. 실행 결과 화면

 

################## 필자가 하면서 에러 났던 부분 혹은 참고사항 ##################

 

문제 -> No mapping for GET /WEB-INF/views 어쩌구 저쩌구... 와 함께 404에러

해결 -> pom.xml에 jsp읽을 수 있는 디펜던시 추가(위 pom.xml 47라인 참고)

 

문제 -> jsp나 html수정시 재기동 해야만 적용되는거 바로바로 적용되게 하려면?

해결 -> https://penthegom.tistory.com/50 글 참고

 

문제 -> 이클립스에서 maven 관련 꼬임현상(?)이 빈번하게 일어나 항상 project-clean, maven clean 등 인텔리제이에서도 무언가가 적용이 되지 않을때.. 예) 디펜던시 추가 후 라이브러리가 제대로 추가가 되지 않는다면?

 

해결 -> 빨간 새로고침 버튼 클릭(Reimport All Maven Projects)

 

반응형
반응형

 요즘 Spring Boot를 이용해서 Non-web application을 만드는 작업에 빠져서 Spring에 대해 많은 걸 배우고 공부하는 중이다. 그래서 이번에는 Spring Boot application을 위한 설정파일로 가장 간단하게 이용할 수 있는 방법인 application.properties를 이용하는 방법을 간단히 설명해 보려고 한다.


 Spring Boot를 이용할 때 대부분의 경우 설정 파일로 application.properties를 이용한다. application.properties는 기본적으로 Spring Boot가 읽어들이도록 되어있기 때문에 사실 파일만 만들어서 'src/main/resources' 폴더에 넣어주면 바로 설정파일로 이용이 가능하다. 이렇게 편한 방법이 있는데 따로 만들어서 사용할 이유가 없다.

 간단한 사용법을 보자.

# application.properties
name=Michael
import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}
 위의 MyBean 클래스의 name 멤버변수는 @Value 어노테이션을 지정한 것만으로 application.properties에 있는 name속성 값 "Michael"로 초기화가 된다. 

 만약에 application.properties 파일에 name 속성이 정의되어있지 않았을 때 default값을 지정하는 방법도 있다. 아래와 같이 @Value 어노테이션에서 속성 이름 옆에 콜론(:)을 찍고 직접 지정해 주면 된다.

    @Value("${name:Michael}")
    private String name;

    @Value("${age:20}")
    private int age;
 위 예에서 지정된 default 값들은 application.properties에 값이 정의되어있지 않으면 각 변수의 타입에 맞게 변환되어 대입된다. 

 사실 Spring Boot의 문서를 보면 property source를 설정하는 다양한 방법이 제공된다.

  1. Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
  2. @TestPropertySource annotations on your tests.
  3. @SpringBootTest#properties annotation attribute on your tests.
  4. Command line arguments.
  5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
  6. ServletConfig init parameters.
  7. ServletContext init parameters.
  8. JNDI attributes from java:comp/env.
  9. Java System properties (System.getProperties()).
  10. OS environment variables.
  11. A RandomValuePropertySource that only has properties in random.*.
  12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
  13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  14. Application properties outside of your packaged jar (application.properties and YAML variants).
  15. Application properties packaged inside your jar (application.properties and YAML variants).
  16. @PropertySource annotations on your @Configuration classes.
  17. Default properties (specified using SpringApplication.setDefaultProperties).

 위의 목록은 더 높은 우선순위를 갖는 property source부터 차례대로 나열한 것이다. 여기서 소개하는 application.properties 파일을 'src/main/resources' 폴더에 넣는 방법은 위의 목록 중 15번에 나오는 방법으로 우선순위로 보면 상당히 아래쪽에 나온다. 즉 상당히 우선순위가 낮다는 말이다. 'src/main/resources' 폴더에 application.properties 파일을 넣어 놓는다는 것은 배포 시에 jar 파일에 함께 묶여서 배포가 된다는 것이고 따라서 배포 후에 설정 값을 변경하려는 의도로 사용하기에는 적합하지 않다. 그러한 용도로 사용하려면 14번에서 말하는 jar 외부의 application.properties를 사용하면 된다. 그냥 application.properties 파일을 따로 만들어서 jar를 실행하는 directory에 두면 된다. jar 안에 있는 application.properties 파일보다 우선순위가 높기 때문에 둘 다 있는 경우 jar 외부의 application.properties 파일의 값이 더 높은 우선순위를 갖는다.

 여기서 많은 사람들이 우선순위에 대해서 오해하는 점 하나를 짚고 가야겠다. 예를 들어 jar안에 같이 포함된 application.properties파일과 jar 외부의 application.properties 파일이 둘 다 존재할 때 외부의 application.properties 파일이 더 우선순위가 높기 때문에 내부의 application.properties 파일이 완전히 무시된다고 생각하기 쉽다. 하지만 그렇지 않다. 우선순위가 높은 property source의 값들은 더 낮은 property source의 값들을 덮어쓰는 것이지 낮은 우선순위의 property source를 읽어들이지 않는 다는 뜻이 아니다. 즉 둘 다 name 속성이 정의되어있다면 더 높은 우선순위의 property source에 선언된 name 속성 값이 사용된다. 하지만 age라는 속성이 더 낮은 우선순위의 property source에만 선언되어있다면 낮은 우선순위의 property에 선언되었지만 그 값이 사용된다. (더 높은 우선순위에 값이 정의되지 않았으므로)

 즉 위 목록의 모든 property source들을 아래쪽부터 윗쪽으로 차례대로 다 찾아서 읽어들이면서 이미 정의된 property들은 덮어 쓰는 개념이다. 목록을 보면 테스트 환경을 제외하고 command line argument가 가장 우선순위가 높으므로 임시로 특정 값을 override하고 싶다면 command line을 이용해서 property를 전달하면 무조건 전달된 값이 이용될 것이다.

 command line을 이용하는 방법은 아래와 같은 방법으로 전달하면 된다. ('server.port' 속성값 지정)

$ java -jar myapp.jar --server.port=9000

 위 목록에 나열된 방법은 많지만 흔히 사용하는 방법으로 이 정도만 알고 있으면 대부분의 경우 문제없이 개발을 진행할 수 있다. 개념적으로 잘 이해하고 있다면 다른 나머지 방법을 이용하는 것도 사실 시간문제일 뿐 크게 어려운 부분은 없을 것이다.



출처 : http://progtrend.blogspot.kr/2017/07/spring-boot-applicationproperties.html

반응형
반응형

https://mvnrepository.com/artifact/org.openpnp/opencv


OpenPnP OpenCV

OpenCV packaged with native libraries and loader for multiple platforms.


LicenseBSD
Used By5 artifacts


VersionRepositoryUsagesDate
3.2.x3.2.0-1Central4(Dec, 2016)
3.2.0-0Central0(Dec, 2016)
2.4.x2.4.13-0Central2(Aug, 2016)
2.4.11-2Central0(Nov, 2015)
2.4.11-1Central0(Oct, 2015)
2.4.9-8Central0(Oct, 2015)


<dependency>

<groupId>org.openpnp</groupId>

<artifactId>opencv</artifactId>

<version>3.2.0-1</version>

</dependency>



pom.xml에 디펜던시에 추가하면 된다.


필자는 spring-boot 사용하고 있고, 아래 config 클래스를 추가하였다.


@Configuration

public class LibLoadingConfig {

    static {

    nu.pattern.OpenCV.loadShared();

        System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);

    }

}


*** 위 버전중 2.x 버전중에 몇가지가 nu.pattern.OpenCV.loadShared(); 가 먹히질 않음.. ***





반응형
반응형

예제에 앞서 REST 에 대한 정의는 Representational state transfer 이다. RESTFul을 이용하는 이유에 대해서는 굳이 설명을 하지 않아도 될 듯 하다. 간단히 내 생각을 이야기 하자면, 우선 cloud 가 아닌 단일 Web Application만 생각해 볼때 현재 개발 추세가 Back-end 의 중요성 보다는 Front-end 의 UI/UX 디자인의 비중이 좀더 커가고 있다. 예전에 그저 model을 던저 주고 JSP 에서 그 모델을 JSP 페이지 쪽에 던져 주어 content를 만드는 방법에서 이제는 Front-end 가 로딩 되어진 상태에서 asynchronous 방식으로 content를 서버쪽에서 받아와 보여주는 방식을 선호 하게 되었다. 이렇게 하여 우선 Front-end의 로딩 속도를 빨리 가져 갈수 있다. 머 사실 어찌 되었던 간에 Back-end 데이타 가져 오는 데 걸리는 시간은 같지만…. 그래도 페이지 전체가 먼저 보여 졌을 때랑, 그렇지 않고 back-end 데이타를 기다리는 동안 페이지르 볼 수 없는 것이랑은 느낌이 틀리니. 이런 이유로 RESTFul Web Service 의 비중도 커졌고 이에 대한 개발도 좀더 구체화 되었다.

먼저 내가 사용한 개발 환경은:

  • Spring Boot 1.4.3.RELEASE (Spring Framework 4.3.5.RELEASE 가 사용 되어 진다.)
  • Java 1.7 version으로 세팅 (1.8로 해도 무난)
  • Postman – RESTFul 개발시 test 를 위해 사용 되어 지는 GUI 이다. Mac OS, Windows, Chrome browser 용으로 설치 하면 된다.
  • Eclipse

자 그럼 시작에 앞서 아래 5가지의 HTTP request method type 들에 대해서 알아 보자.

  • GET – 데이타를 검색하여 해당 값을 받아 올때 사용한다. (CRUD 에서 Retrieve 할 때 사용)
  • POST – 새롭게 데이타를 생성 할 때 사용 한다. (CRUD 에서  Create 할 때 사용)
  • PUT – 데이타를 업데이트 할 때 사용 한다. (CRUD 에서  Update 할 때 사용)
  • PATCH – PUT 과 마찬가지로 데이타를 업데이트 할 때 사용하지만 PUT 과 달리 전체 Entity 데이타의 업데이트가 아닌 부분의 값을 업데이트 할 때 사용한다.
  • DELETE – 데이타를 삭제 할 때 사용한다. (CRUD 에서  Delete 할 떄 사용)

이렇게 HTTP request method type 에 대해 Front-end 개발자와 Back-end 개발자 사이에 확실한 이해를 하고 넘어 가야 한다. 물론 Back-end 개발자의 경우 Front-end 개발자가 사용 할 수 있도록 정확한 문서를 제공해야 한다.

먼저 아래와 같이 Eclipse 를 이용하여 sbrest 라고 하는 프로젝트를 만들고 pom.xml 을 설정하자.

그러면 이제 Customer Entity 를 이용한 CRUD 를 하는 간단한 RESTFul 을 만들어 보자. 우선 아래와 같이 Customer entity를 만든다.

Spring framework 4.0 이후 버전에서는 Entity class 에서 @Table annotation 을 사용 하지 않으면 기본적으로 class 이름과 같은 table 을 맵핑한다. 따라서 class 이름과 다른 table 이름을 사용 한다면 @Table(name = “tbl_customer”) 처럼 명시 하여 주어야 한다. 또 한 가지는 class의 property 들도 @Column annotation을 사용 하지 않는 다면 기본적으로 property 이름을 이용하여 table column 이름과 맵핑을 하게 된다. 위에서는 firstname과 lastname이 이 경우에 해당한다.

다음으로 Spring Data JPA 를 이용하여 아래와 같이 간단하게 Repository 인터페이스와 Service 를 만들자.

 

 

여기 까지 간단하게 Customer entity 에 대한 CRUD 오퍼레이션을 하는 Repository와 Service 를 만들어 보았다. 이제 RESTFul 을 만들어 보자. 개인적으로 @RestController 들을 따로 package를 만들어 관리를 하는 것을 선호 한다. 따라서 아래와 같이 rest package를  만들어 그곳에 Rest Controller 들을 정의 한다.

위와 같이 RestCustomerConstroller.java 를 만들고 @RestController annotation을 설정 하여 Rest Controller를 만들었다. 먼저 GET/POST/PUT/PATCH/DELETE 를 이용한 Rest 코드 부터 하나 하나 알아 보겠다.

 

GET – To retrieve data

GET 을 이용 하는 경우는 Data를 검색할 때 사용 한다.

위에서 보면 전체 customer list를 가져오거나 @PathVariable을 이용하여 customer ID 를 보내 특정 customer 를 검색하여 데이타를 받는 경우이다. method = RequestMethod.GET 을 @RequestMapping 에 정의 하면 된다. 리턴은 ReponseEntity<T> 클래스를 이용하여 검색이 되지 않았을 경우에는 HttpStatus.NOT_FOUND 를 넘겨 주고, 검색이 되었을 경우에는 검색한 결과 object을 HttpStatus.OK 와 함께 넘겨 준다. 이때 Spring 에서는 자동으로 jackson-databind 를 이용하여 JSON 포맷으 데이타를 넘겨 준다.

 

POST – To create data

POST 를 이용 하는 경우는 Data를 새롭게 만들 때 사용 한다.

POST 는 새로운 Data를 생성 할 때 사용 하는 방법으로 method = RequestMethod.POST 로 설정을 해 준다. argument 들로 Customer 객체를 @RequestBody 를 이용하여 받아 왔다. Front-end 쪽에서 JSON 포맷으로 Customer 데이타를 보내 주면 된다. 이 떄 Front-end 개발자는 POST 이기 때문에 새로운 객체를 생성해야 하는 것으로 알고 데이타를 보내 주어야 한다. 두번 째 argument 로 UriComponentBuilder 를 설정 했다. 이유는 Customer를 생성하고 HttpHeaders 객체의 location 정보를 넣어 주기 위함이다. 이렇게 해 주면 Front-end 쪽 개발자는 새로운 데이타가 성공적으로 생성 (HttpStatus.CREATED) 되었을 경우 header 정보에서 location 값을 찾아 redirect 해 줄 수 있게 된다.

위에서 보면 만약 새롭게 생성하려고 하는 데이타가 이미 존재 하는 경우라면 HttpStatus.CONFLICT를 ResponseEntity<Void> 를 통해 리턴해 준다.

 

PUT –  To update data

PUT 을 이용 하는 경우는 존재 하는 Data를 업데이트 할 때 사용 한다.

 

PATCH – To update partial data

PATCH 는 부분적이 Data를 업데이트 할 때 사용 한다. 즉 Front-end 쪽에서 객체 전체 업데이트가 아닌 부분만 업데이트 할 때 업데이트 하는 부분만 RESTFul 에 보내 준다. PUT 과 PATCH 는 공통적으로 update 할 때 사용 하지만 PATCH 가 부분 데이타를 업데이트 한다는 점에서 PUT 과 차이가 있다.

위에서 method = RequestMethod.PATCH 를 설정해 주었고 업데이트 하려는 Customer의 ID와 Customer 객체를 받았다. 받은 Customer 객체의 경우 실제 업데이트 하려는 property 에만 값이 들어 있고 나머지는 null 이 들어 있게 된다. PATCH 가 성공적으로 되었으면 업데이트된 Customer 와 HttpStatus.OK 를 ResponseEntity<Customer> 에 넣어 보내 주고, 그렇지 않을 경우에는 HttpStatus.NOT_FOUND 를 넘겨준다. CustomerServiceImpl.java 의 patchCustomer 메소드를 참고 하기 바란다.

 

DELETE – To delete data

DELETE 를 이용 하는 경우는  Data를 삭제 할 때 사용 한다.

method = RequestMethod.DELETE 를 이용 하고 성공했을 경우 ResponseEntity<Void> 에 HttpStatus.OK 를 넣어 주고 그렇지 않을 경우 HttpStatus.NOT_FOUND 를 넣어 넘겨주었다.

 

지금 까지 RESTFul controller 를 개발 하는 방법을 설명 하였다. 아래는 최종 파일 이다.

이렇게 하여 간단하게 Spring Boot 을 이용한 REST web application을 만들어 보았다.

 

최종 프로젝트는 위와 같을 것이다. 자 그러면 이제 Postman 을 이용하여 위에서 만든 RESTFul web application을 테스트 해 보자. 아직 Postman을 설치 하지 않았다면 아래 사이트에 가서 각자의 환경에 맞게 다운 받아 설치를 하자.

Postman

 

TEST

자 그러면 먼저 Spring Boot application을 실행 하자.

그리고 이제 Postman을 실행 하자. 원하면 Sign up을 해서 자신이 test 한 것을 저장할 수 있다.

먼저 Data 가 아무 것도 없으니 CREATE method 를 이용하여 생성 해 보자.

위와 같이 POST 로 http://localhost:8080/customer 를 호출 하였다. 이때 Body 에는 javascript의 AJAX 를 이용하여 업데이트 한다는 가정으로 raw 와 JSON (application/json) 을 설정하고 JSON 데이타를 타입한 후에 Send 버튼을 눌러 호출 하면 된다. 이렇게 하면 아래 보는 것과 같이 Status: 201 Created 가 넘어 오는 것을 확인 할 수 있다. 다른 이름을 이용하여 하나 더 만들어 보자.

그 다음으로 위에서 생성한 데이타를 검색해 보자.

위에서는 http://localhost:8080/customer 를 GET 방식을 이용하여 Send 를 눌렀다. 그리고 나면 아래와 같이 Status: 200 OK 와 생성한 Customer 리스트를 볼 수 있다.

위에서는 http://localhost:8080/customer/2 를 GET 방식을 이용하여 Send 를 눌렀다. 그리고 나면 아래와 같이 Status: 200 OK 와 id 값이 2 인 Customer 검색 결과가 리턴 된다.

이번엔 PUT을 이용한 Update 이다.

보는 것과 같이 Front-end 쪽에서는 객체 전체 데이타를 update 하기 위해 보내 주었다. 위와 같이 PUT으로 설정해서 Send 를 누르면 업데이트 된 결과 값이 Status: 200 OK 와 함께 넘어 온다.

이제 PATCH 를 보자.

위에서 보면 front-end 에서는 lastname 만 넣어 PATCH 를 이용하여 request를 보냈다. 이렇게 하면 back-end 쪽에서는 부분 업데이트로 알고 lastname 만 업데이트 해 주었다. 리턴된 결과를 보면 Status: 200 OK 와 lastname 이 업데이트된 JSON 데이타 결과 같이 넘어 왔다.

마지막으로 아래 DELETE 를 해 보자.

DELETE 를 이용 http://localhost:8080/customer/2 를 호출 하여보면 ID 가 2 인 Customer 가 삭제 되고 Status: 200 OK 가 넘어 왔다.

 

이상 Spring Boot 을 이용한 RESTFul web service 를 만들어 보았다.

 

** DOWNLOAD this project

 

** Reference


반응형
반응형

사용 된 기술 :   Java SE 1.8 | Log4j 2.8.2 | 메이븐 3.3.9 | Jackson API 2.8.7 | Eclipse Neon.3

RollingFileAppender는 특정 크기 제한에 도달하거나 날짜 / 시간 패턴이 더 이상 적용되지 않으면 로그 파일을 롤오버하는 파일 첨부 프로그램입니다.

이 글에서는,를 사용 RollingFileAppender하여 이전 로그 파일을 백업하고 압축하는 방법을 설명합니다 

Jar dependencies

pom.xml 파일을 편집하고 log4j2 및 Jackson API 종속성을 추가하십시오.

<dependencies>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.2</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.7</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.7</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.7</version>
  </dependency>
</dependencies>

날짜 및 시간을 기준으로 롤링

TimeBasedTriggeringPolicy 를 사용하여 <FilePattern/>다음과 같이 요소에 사용 된 날짜 및 시간 패턴을 기반으로 로그 파일을 롤오버 할 수 있습니다 .

<RollingFile name="RollingFile">
  <FileName>C:/log/mylog.log</FileName>
  <FilePattern>C:/log/time-based-logs/%d{yyyy-MM-dd-hh-mm}.log.zip</FilePattern>
  <PatternLayout>
    <Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
  </PatternLayout>
  <Policies>
    <TimeBasedTriggeringPolicy interval="2" modulate="true" />
  </Policies>
  <DefaultRolloverStrategy max="5" />
</RollingFile>

다음은 날짜 / 시간에 기초한 파일 롤링의 날짜 / 시간 패턴 샘플입니다.

날짜 / 시간 패턴기술Intervale 속성 예
% d {yyyy-MM-dd-hh-mm} .log.zip매분마다 로그 파일 롤링

interval = 2이면 2 분마다 롤오버가 발생합니다.

예 :  2017-07-26-09-57.log.zip ,  2017-07-26-09-59.log.zip ,  2017-07-26-10-01.log.zip ,  2017-07-26- 10-03.log.zip 등 ..

% d {yyyy-MM-dd-hh} .log.zip로그 파일을 매 시간 롤업하십시오.

interval = 4이면 4 시간마다 롤오버가 발생합니다.

예 :  2017-07-26-09.log.zip ,  2017-07-26-10.log.zip ,  2017-07-26-11.log.zip  

% d {yyyy-MM-dd} .log.zip매일 로그 파일 롤링

interval = 1이면 롤오버가 매일 발생합니다.

예 :  2017-07-26.log.zip ,  2017-07-27.log.zip 등

다음은 log4j2.xml2 분마다 파일을 롤링하기위한 파일 의 전체 예제입니다  .

log4j2.xml

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

    <!-- Console Appender -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
    </Console>

    <!-- Rolling File Appender -->
    <RollingFile name="RollingFile">
      <FileName>C:/log/mylog.log</FileName>
      <FilePattern>C:/log/time-based-logs/%d{yyyy-MM-dd-hh-mm}.log.zip</FilePattern>
      <PatternLayout>
        <Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
      </PatternLayout>
      <Policies>
        <TimeBasedTriggeringPolicy interval="2" modulate="true" />
      </Policies>
      <DefaultRolloverStrategy max="5" />
    </RollingFile>

  </Appenders>
  <Loggers>
    <Logger name="com.boraji.tutorial.log4j2" level="debug" additivity="false">
      <AppenderRef ref="RollingFile" />
      <AppenderRef ref="Console" />
    </Logger>
    <Root level="trace">
      <AppenderRef ref="Console" />
    </Root>
  </Loggers>
</Configuration>

<DefaultRolloverStrategy>요소를 제거하기 전에 5 개의 파일을 유지하는 롤오버 전략을 정의합니다.

위의 log4j 2 구성을 테스트하는 간단한 Java 프로그램.

MainApp.java

package com.boraji.tutorial.log4j2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class MainApp {

   private static final Logger logger = LogManager.getLogger(MainApp.class);

   public static void main(String[] args) {

      for (int i = 0; i < 10000; i++) {
         logger.info("Rolling file appender example...");
         try {
            Thread.sleep(500);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }

   }
}

 

파일 크기에 따른 롤링

SizeBasedTriggeringPolicy 를 사용하여 다음과 같이 파일 크기에 따라 로그 파일을 롤오버 할 수 있습니다 .

<RollingFile name="RollingFile">
  <FileName>C:/log/mylog.log</FileName>
  <FilePattern>C:/log/size-based-logs/%d{yyyy-MM-dd-hh}-%i.log.zip</FilePattern>
  <PatternLayout>
    <Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
  </PatternLayout>
  <Policies>
    <SizeBasedTriggeringPolicy size="10 KB"/>
  </Policies>
  <DefaultRolloverStrategy max="5" />
</RollingFile>

KB, MB 또는 GB 접미 부와 함께 파일 크기를 바이트 단위로 지정할 수 있습니다.

다음은 요소 log4j2.xml의 지정된 크기를 기반으로 파일 롤링을위한 전체  파일입니다 <SizeBasedTriggeringPolicy/>.

log4j2.xml

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

    <!-- Console Appender -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
    </Console>

    <!-- Rolling File Appender -->
    <RollingFile name="RollingFile">
      <FileName>C:/log/mylog.log</FileName>
      <FilePattern>C:/log/size-based-logs/%d{yyyy-MM-dd-hh}-%i.log.zip</FilePattern>
      <PatternLayout>
        <Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
      </PatternLayout>
      <Policies>
        <SizeBasedTriggeringPolicy size="10 KB" />
      </Policies>
      <DefaultRolloverStrategy max="5" />
    </RollingFile>

  </Appenders>
  <Loggers>
    <Logger name="com.boraji.tutorial.log4j2" level="debug" additivity="false">
      <AppenderRef ref="RollingFile" />
      <AppenderRef ref="Console" />
    </Logger>
    <Root level="trace">
      <AppenderRef ref="Console" />
    </Root>
  </Loggers>
</Configuration>

다음은 위의 log4j2.xml 설정을 테스트하는 간단한 자바 프로그램이다.

package com.boraji.tutorial.log4j2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class MainApp {

   private static final Logger logger = LogManager.getLogger(MainApp.class);

   public static void main(String[] args) {

      for (int i = 0; i < 50000; i++) {
         logger.info("Rolling file appender example...");
      }

   }
}

cron 표현식을 기반으로 한 롤링

다음과 같이 CronTriggeringPolicy 를 사용하여 지정된 cron 표현식을 기반으로 로그 파일을 롤오버 할 수 있습니다 .

<RollingFile name="RollingFile">
  <FileName>C:/log/mylog.log</FileName>
  <FilePattern>C:/log/cron-based-logs/%d{yyyy-MM-dd-hh-mm}-%i.log.zip</FilePattern>
  <PatternLayout>
    <Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
  </PatternLayout>
  <Policies>
    <CronTriggeringPolicy schedule="0 0/2 * 1/1 * ? *" />
  </Policies>
  <DefaultRolloverStrategy max="5" />
</RollingFile>

다음은 cron 표현식에 의해 엘리먼트의 속성에 log4j2.xml지정된 매 2 분마다 롤오버를 트리거 하는 전체  파일 입니다.schedule<CronTriggeringPolicy/>

log4j2.xml

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

    <!-- Console Appender -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
    </Console>

    <!-- Rolling File Appender -->
    <RollingFile name="RollingFile">
      <FileName>C:/log/mylog.log</FileName>
      <FilePattern>C:/log/cron-based-logs/%d{yyyy-MM-dd-hh-mm}-%i.log.zip</FilePattern>
      <PatternLayout>
        <Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
      </PatternLayout>
      <Policies>
        <CronTriggeringPolicy schedule="0 0/2 * 1/1 * ? *" />
      </Policies>
      <DefaultRolloverStrategy max="5" />
    </RollingFile>

  </Appenders>
  <Loggers>
    <Logger name="com.boraji.tutorial.log4j2" level="debug" additivity="false">
      <AppenderRef ref="RollingFile" />
      <AppenderRef ref="Console" />
    </Logger>
    <Root level="trace">
      <AppenderRef ref="Console" />
    </Root>
  </Loggers>
</Configuration>

다음은 위의 log4j2.xml 설정을 테스트하는 간단한 자바 프로그램이다.

package com.boraji.tutorial.log4j2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class MainApp {

   private static final Logger logger = LogManager.getLogger(MainApp.class);

   public static void main(String[] args) {

      for (int i = 0; i < 1000; i++) {
         logger.info("Rolling file appender example...");
         try {
            Thread.sleep(1000);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }

   }
}


반응형
반응형

기본적으로 Spring Boot 애플리케이션에서 'Starter'를 사용하는 경우 Logback 프레임 워크가 로깅에 사용됩니다. 

이 글에서는 Spring 부팅 애플리케이션에서 log4j 2 프레임 워크를 설정하는 방법을 배우게 될 것이다.

이 예제에 사용 된 도구 및 기술은 다음과 같습니다.

  • Spring Boot 1.5.8.RELEASE
  • Log4j 2.7
  • Maven 3.5.2
  • Eclipse Neon.3 (4.6.3)

예를 보자 ...

프로젝트 구조

다음과 같은 프로젝트 구조를 검토하십시오.

spring-boot-log4j.png

관련 -  이클립스 IDE에서 메이븐 프로젝트를 만드는 방법 .

Jar dependencies

우리가 알고있는 것처럼 기본적으로 의존 관계 관리를 위해 Starter 를 사용하는 경우 Logback이 로깅에 사용됩니다 스프링 부트 응용 프로그램에서 log4j 2를 사용하려면 Logback을 제외시킨 다음 log4j 2 Starter 를 다음과 같이 포함시켜야 합니다.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.boraji.tutorial.springboot</groupId>
  <artifactId>spring-boot-log4j2-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Log4j 2 구성

 src/main/resources폴더안에 log4j2.xml생성 후 파일을 그 안에 넣고, 다음과 같은 코드를 작성합니다.

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <!-- Console Appender -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
    </Console>
    <!-- File Appender -->
    <File name="File" fileName="d:/app.log">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
    </File>
    
  </Appenders>

  <Loggers>
    <!-- Log everything in custom package -->
    <Logger name="com.boraji.tutorial.springboot" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <!-- Log everything in Spring Boot -->
    <Logger name="org.springframework.boot" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <!-- Log everything in Spring Core -->
    <Logger name="org.springframework.core" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <Root level="error">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Root>
    
  </Loggers>
</Configuration>

 

Run application

주석으로 @SpringBootApplication 주석이 달린 메인 클래스를 작성  하여 log4j 2 구성을 다음과 같이 테스트하십시오.

MainApp.java

package com.boraji.tutorial.springboot;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApp {
  
  private static Logger logger = LogManager.getLogger(MainApp.class);

  public static void main(String[] args) {
    logger.info("Starting Spring Boot application..");
    SpringApplication app = new SpringApplication(MainApp.class);
    app.run(args);
  }
}

를 실행하면 MainApp.java콘솔 출력은 다음과 같이 보입니다.

spring-boot-log4j_01.png

소스 다운로드


반응형
반응형

이 글에서는 스프링 부트 프레임 워크를 사용하여 스프링 MVC 웹 애플리케이션을 만들고 부트 스트랩하는 방법을 설명하겠다. JSP를 웹 애플리케이션의보기로 사용합니다.

이 응용 프로그램에 사용되는 도구 및 기술은 다음과 같습니다.


  • Spring Boot 1.5.4.RELEASE
  • Spring WebMVC 4.3.9.RELEASE
  • Tomcat Embedded 8.5
  • JavaSE 1.8
  • Maven 3.3.9
  • Eclipse Neon.3


프로젝트 구조 

스프링 부트 프로젝트 구조를 검토하십시오.

spring-boot-mvc-jsp.png

관련 -  이클립스 IDE에서 메이븐 프로젝트를 만드는 방법 .

Jar dependencies

스프링 부트에서 스프링 MVC 웹 애플리케이션을 생성하고 실행하려면  파일에 spring-boot-starter 의존성  을 추가해야한다  pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

다음은 전체 pom.xml파일입니다.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.boraji.tutorial.springboot</groupId>
  <artifactId>spring-boot-web-application-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- JSTL tag lib -->
    <dependency>
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>javax.servlet.jsp.jstl-api</artifactId>
      <version>1.2.1</version>
    </dependency>

    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- Tomcat for JSP rendering -->
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
      <scope>provided</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
  <packaging>war</packaging>
</project>

컨트롤러 클래스

 패키지 HelloController아래 에 클래스를 com.boraji.tutorial.springboot.controller만들고 다음 코드를 작성하십시오.

HelloController.java

package com.boraji.tutorial.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

   @RequestMapping("/")
   public String index() {
      return "index";
   }

   @PostMapping("/hello")
   public String sayHello(@RequestParam("name") String name, Model model) {
      model.addAttribute("name", name);
      return "hello";
   }
}

JSP 뷰

프로젝트 구조에 표시된대로 폴더  아래에 파일을 index.jsp만들고 hello.jsp파일을 만듭니다 src/main/webapp/WEB-INF/views.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<!-- Static content -->
<link rel="stylesheet" href="/resources/css/style.css">
<script type="text/javascript" src="/resources/js/app.js"></script>

<title>Spring Boot</title>
</head>
<body>
  <h1>Spring Boot - MVC web application example</h1>
  <hr>

  <div class="form">
    <form action="hello" method="post" onsubmit="return validate()">
      <table>
        <tr>
          <td>Enter Your name</td>
          <td><input id="name" name="name"></td>
          <td><input type="submit" value="Submit"></td>
        </tr>
      </table>
    </form>
  </div>

</body>
</html>

hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring Boot</title>
</head>
<body>
  <h1>Spring Boot - MVC web application example</h1>
  <hr>

  <h2>Your name is ${name}</h2>

</body>
</html>

 

Static web resources

기본적으로 봄 부팅은에서 정적 웹 콘텐츠를 제공 /static또는 /public또는 /resources또는 /META-INF/resources폴더 클래스 경로에 있습니다. 이 예제에서는 스타일 시트, 자바 스크립트 파일과 같은 모든 정적 리소스를 /static폴더에 저장합니다.

src/main/resources/static/css폴더 아래에 스타일 시트 파일을 만들고 그 안에 다음 코드를 작성하십시오.

style.css

.form {
	background-color: #efefef;
	width: 400px;
	height: 50px;
	border-radius: 7px;
	padding: 20px;
}

자, src/main/resources/static/js폴더 아래에 javascript 파일을 만들고 다음 코드를 작성하십시오.

app.js

function validate() {
	var name = document.getElementById("name").value;
	if (name == '') {
		alert('Please enter a valid name.');
		return false;
	} else {
		return true;
	}
}

Application properties

봄 부팅은에서 속성을로드하고 스프링에 application.properties추가합니다 EnvironmentSpring MVC 또는 정적 웹 컨텐트와 관련된 속성을 application.properties파일에 설정할 수 있습니다 .

원본 폴더 application.properties아래 에 파일을 src/main/resources만들고 그 안에 다음 속성을 작성합니다.

application.properties

spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**

주 - spring.mvc.static-path-pattern=/resources/** (가) 매핑됩니다 classpath:/static/css/style.css에 /resources/css/style.css마찬가지로,에 classpath:/static/js/app.js  매핑됩니다 /resources/js/app.js다음과 같이 jsp에서 이러한 정적 자원을 사용할 수 있습니다.

<link rel="stylesheet" href="/resources/css/style.css">
<script type="text/javascript" src="/resources/js/app.js"></script>

메인 클래스

Spring Boot를 사용하여 Spring MVC 애플리케이션을 부트 스트랩하려면 @SpringBootApplication 다음과 같이 annotation으로 주석이 달린 메인 클래스를 생성한다  .

MainApp.java

package com.boraji.tutorial.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApp {
   public static void main(String[] args) {
      SpringApplication.run(MainApp.class, args);
   }
}

 

응용 프로그램 실행

실행  MainApp.java 예 → 자바 응용 프로그램으로 실행 → 실행으로 이동 Java 응용 프로그램과 같은 클래스를

이 mvn spring-boot:run 명령을 사용하여 스프링 부팅 응용 프로그램을 실행할 수 있습니다  .

메인 클래스를 실행하면 콘솔 출력은 다음과 같이 보입니다.

이제   브라우저 주소에 http : // localhost 8080 을 입력하고 입력 필드에 사용자 이름을 입력하십시오.

 

이제   브라우저 주소에 http : // localhost 8080 을 입력하고 입력 필드에 사용자 이름을 입력하십시오.

spring-boot-mvc-jsp1.png

제출 버튼을 클릭하고 결과 페이지를보십시오.

spring-boot-mvc-jsp2.png

Spring 부트 애플리케이션을 실행 가능한 전쟁으로 패키징하기

임베디드 서블릿 컨테이너를 사용하고 있다면 jar 대신에 스프링 부트 애플리케이션을 war로 패키징해야한다. JSP 지원에는 몇 가지 제한 사항이 있습니다. 더 읽기 ..

다음 maven 명령을 사용하여 스프링 부트 응용 프로그램을 전쟁으로 패키지 할 수 있습니다.

mvn clean package

명령 줄에서 실행 가능한 전쟁 실행

다음 명령을 사용하여 CMD에서 전쟁을 실행하십시오.

>java -jar spring-boot-web-application-example-0.0.1-SNAPSHOT.war
소스 다운로드


반응형
반응형

Spring Boot Samples

The following sample applications are provided:

SampleDescription

spring-boot-sample-activemq

JMS consumer and producer using Apache ActiveMQ

spring-boot-sample-actuator

REST service with production-ready features

spring-boot-sample-actuator-log4j2

Production-ready features using log4j 2 for logging (instead of logback)

spring-boot-sample-actuator-noweb

Non-web application with production-ready features

spring-boot-sample-actuator-ui

Web UI example with production-ready features

spring-boot-sample-amqp

Message-oriented application using AMQP and RabbitMQ

spring-boot-sample-ant

Executable JAR build using Ant

spring-boot-sample-aop

Demonstrates explicit usage of Spring AOP

spring-boot-sample-atmosphere

Chat service built using Atmosphere

spring-boot-sample-batch

Define and run a Batch job in a few lines of code

spring-boot-sample-cache

Web application that uses Spring’s cache abstraction

spring-boot-sample-custom-layout

Creates custom Jar Layout

spring-boot-sample-data-cassandra

Stores data using Spring Data Cassandra

spring-boot-sample-data-couchbase

Stores data using Spring Data Couchbase

spring-boot-sample-data-elasticsearch

Stores data using Spring Data Elasticsearch

spring-boot-sample-data-jpa

Stores data using Spring Data JPA with Hibernate

spring-boot-sample-data-ldap

Stores data using Spring Data LDAP

spring-boot-sample-data-mongodb

Stores data using Spring Data MongoDB

spring-boot-sample-data-neo4j

Stores data using Spring Data Neo4j

spring-boot-sample-data-redis

Stores data using Spring Data Redis

spring-boot-sample-data-rest

RESTful service built using Spring Data REST

spring-boot-sample-data-solr

Stores data using Spring Data Solr

spring-boot-sample-devtools

Using DevTools for rapid application development

spring-boot-sample-flyway

Database migrations with Flyway

spring-boot-sample-hateoas

RESTful API built using Spring Hateoas

spring-boot-sample-integration

Integration application built using Spring Integration and its Java DSL

spring-boot-sample-jersey

RESTful service built using Jersey 2

spring-boot-sample-jersey1

RESTful service built using Jersey

spring-boot-sample-jetty

Embedded Jetty

spring-boot-sample-jetty-ssl

Embedded Jetty configured to use SSL

spring-boot-sample-jetty-jsp

Web application that uses JSP templates with Jetty

spring-boot-sample-jooq

Stores data using jOOQ

spring-boot-sample-jpa

Uses plain JPA (Hibernate)

spring-boot-sample-jta-atomikos

JTA transactions with Atomikos

spring-boot-sample-jta-bitronix

JTA transactions with Bitronix

spring-boot-sample-jta-jndi

JTA transactions using a TransactionManager and DataSource from JNDI

spring-boot-sample-jta-narayana

JTA transactions with Narayana

spring-boot-sample-junit-jupiter

Demonstrates JUnit Jupiter-based testing

spring-boot-sample-liquibase

Database migrations with Liquibase

spring-boot-sample-logback

Demonstrates Spring Boot’s custom Logback functionality configured in logback-spring.xml

spring-boot-sample-metrics-dropwizard

Demonstrates support for Dropwizard metrics

spring-boot-sample-metrics-opentsdb

Exports metrics to OpenTSDB

spring-boot-sample-metrics-redis

Exports metrics to Redis

spring-boot-sample-parent-context

Application that uses an ApplicationContext with a parent

spring-boot-sample-profile

Demonstrates some of Spring Framework’s @Profile capabilities

spring-boot-sample-property-validation

Demonstrates the usage of @ConfigurationProperties with a Spring Validator

spring-boot-sample-secure

Non-web application that uses Spring Security

spring-boot-sample-servlet

Web application with a "raw" Servlet returning plain text content

spring-boot-sample-session

Web Application that uses Spring Session to manage session data

spring-boot-sample-simple

Simple command line application

spring-boot-sample-test

Demonstrates Spring Boot’s testing capabilities

spring-boot-sample-testng

Demonstrates TestNG-based testing

spring-boot-sample-tomcat

Embedded Tomcat

spring-boot-sample-tomcat-jsp

Web application that uses JSP templates with Tomcat

spring-boot-sample-tomcat-multi-connectors

Web application that uses Tomcat configured with multiple connectors

spring-boot-sample-tomcat-ssl

Web application that uses Tomcat configured with SSL

spring-boot-sample-traditional

Traditional WAR packaging (but also executable using java -jar)

spring-boot-sample-undertow

Embedded Undertow

spring-boot-sample-undertow-ssl

Embedded Undertow configured to use SSL

spring-boot-sample-war

Web application packaged as a war file

spring-boot-sample-web-freemarker

Web application that uses FreeMarker templates

spring-boot-sample-web-groovy-templates

Web application that uses Groovy templates

spring-boot-sample-web-jsp

Web application that uses JSP templates

spring-boot-sample-web-method-security

Web application with Security configuration enabling global method security

spring-boot-sample-web-mustache

Web application that uses Mustache views

spring-boot-sample-web-secure

Web application with typical Security configuration enabling a login form

spring-boot-sample-web-secure-custom

Web application with custom Spring Security configuration

spring-boot-sample-web-secure-jdbc

Web application with Spring Security configured to use JDBC authentication

spring-boot-sample-web-static

Web application that serves static files

spring-boot-sample-web-ui

Web application with a basic UI built using Bootstrap and JQuery

spring-boot-sample-webservices

Simple contract-first SOAP web service with Spring Web Services

spring-boot-sample-websocket-jetty

WebSocket application that uses Jetty

spring-boot-sample-websocket-tomcat

WebSocket application that uses Tomcat

spring-boot-sample-websocket-undertow

WebSocket application that uses Undertow

spring-boot-sample-xml

Example show how Spring Boot can be mixed with traditional XML configuration (we generally recommend using Java @Configuration whenever possible


반응형

+ Recent posts