<REST(Representational State Transfer>


- 하나의 URI는 하나의 고유한 Resource를 대표하도록 설계

- 특정 URI는 각각 상응하는 데이터를 의미

- 데이터에 대한 처리는 HTTP 방식(GET, POST, PUT, DELETE 등)과 같은 추가적인 정보를 통해서 결정

- REST 서비스 : 특정 URI를 통해서 사용자가 원하는 정보를 제공하는 방식

- RESTful API : REST  방식으로 제공되는 외부 연결 URI



<REST와 HTTP methods>


- GET : 리소스 또는 리소스 컬렉션을 얻어옴

- POST : 리소스 생성

- PUT : 리소스 업데이트

- DELETE : 리소스 삭제



<REST Annotation>


* @ResponseBody

  - 메소드 또는 메소드의 리턴 타입에 사용하는 어노테이션

  - @Controller 어노테이션이 있는 클래스에서 정의된 메소드 (리턴타입)에

  - @ResponseBody 어노테이션을 사용하면, 클라이언트로 JSP가 아닌 데이터 자체가

  - 메시지를 가공해서 클라이언트에게 전달

  - Spring 3 버전부터 지원


* @RestController

  - Controller 클래스에 사용되는 어노테이션

  - JSP와 같은 View를 만들어 내는 것이 목적이 아닌, REST 방식의 데이터 처리를 위한 콘트롤러

클래스임을 선언하는 어노테이션

  - @RestController의 모든 콘트롤러 메소드들은, @ResponseBody 어노테이션 없이, 뷰가 아닌

데이터 자체를 클라이언트(브라우저)에게 서비스(리턴)하는 메소드가 됨

  - Spring 4 버전부터 지원

  1. 우키러브 2017.10.08 03:41 신고

    안녕하세요. RESTful 관련 내용이 너무 정리가 잘 되어 있어 제 블로그에 재정리하여 글을 옮겨 적었습니다. 혹시 불편하시면 글을 내리겠습니다. http://nanamix.tistory.com/500

<사전 설정>


* src/main/resources/mybatis-config.xml

- DB 테이블 컬럼 명을 지정하여 Spring 내에서 사용가능하게 설정


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
  
<configuration>
    <properties>
        <property name="test_board" value="test_board"/>
        <property name="bno" value="bno"/>
        <property name="title" value="title"/>
        <property name="content" value="content"/>
        <property name="userid" value="userid"/>
        <property name="regdate" value="regdate"/>
    </properties>
    
    <typeAliases>
        <package name="edu.spring.ex02.domain"/>
    </typeAliases>
    
</configuration>
cs



* src/main/resources/mappers/board-mapper.xml

- Query문 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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="edu.spring.ex02.BoardMapper">
    <select id="select_all" resultType="BoardVO">
    select * from ${test_board} order by ${bno} desc
    </select>
    <!--  
    resultType: select를 했을 때 레코드 하나의 타입
        원래는 패키지 이름을 포함한 전체경로의 클래스 이름을 사용해야 함
        mybatis-config.xml에서 typeAliases 속성에서 package를 
        정의했기 때문에 클래스 이름만 사용해도 됨
    
    ${test_board}: mybatist-config.xml 파일에서
    "test_board" 프로퍼티에 저장된 값(value)를 읽어 옴
    -->
    
</mapper>
cs



*BoardVO.java

- VO 객체 선언


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
package edu.spring.ex02.domain;
 
import java.util.Date;
 
public class BoardVO {
    private int bno;
    private String title;
    private String content;
    private String userid;
    private Date regdate;
 
    public BoardVO() {}
 
    public BoardVO(int bno, String title, String content, String userid, Date regdate) {
        super();
        this.bno = bno;
        this.title = title;
        this.content = content;
        this.userid = userid;
        this.regdate = regdate;
    }
 
    public int getBno() {
        return bno;
    }
 
    public void setBno(int bno) {
        this.bno = bno;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
 
    public String getUserid() {
        return userid;
    }
 
    public void setUserid(String userid) {
        this.userid = userid;
    }
 
    public Date getRegdate() {
        return regdate;
    }
 
    public void setRegdate(Date regdate) {
        this.regdate = regdate;
    }
    
// end class BoardVO
 
 
cs



* SqlSessionTest.java

- ibatis의 session을 이용 데이터 값 받기


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
package edu.spring.ex02;
 
import java.util.List;
 
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
 
import edu.spring.ex02.domain.BoardVO;
 
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/**/*.xml" })
public class SqlSessionTest {
    private static final Logger logger = LoggerFactory.getLogger(SqlSessionTest.class);
    private static final String NAMESPACE =
            "edu.spring.ex02.BoardMapper";
    
    @Autowired
    private SqlSession sqlSession;
    
    @Test
    public void testSelectAll(){
        List<BoardVO> list = sqlSession.selectList(NAMESPACE + ".select_all");
        
        for(BoardVO vo : list){
            logger.info(vo.getTitle());
        }
    }
}
 
cs




- 결과화면



<Oracle 사용을 위한 설정>


- Oracle XE 11g가 설치가 되어있어야 함

- 다음 경로에 jar파일이 있어야함

  C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib

- Oracle JDBC driver를 로컬 메이븐 저장소에 추가

  1) 윈도우에서 실행창을 연다.

  2) 다음 내용을 입력 :

  mvn install:install-file -Dfile=C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar

  3) 확인:

  C:\Users\사용자계정\.m2\repository





* porm.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
<?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 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>edu.spring</groupId>
   <artifactId>ex02</artifactId>
   <name>Spring02</name>
   <packaging>war</packaging>
   <version>1.0.0-BUILD-SNAPSHOT</version>
   <properties>
      <java-version>1.8</java-version>
      <org.springframework-version>4.3.8.RELEASE</org.springframework-version>
      <org.aspectj-version>1.8.10</org.aspectj-version>
      <org.slf4j-version>1.7.25</org.slf4j-version>
   </properties>
   <dependencies>
      <!-- Spring -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${org.springframework-version}</version>
         <exclusions>
            <!-- Exclude Commons Logging in favor of SLF4j -->
            <exclusion>
               <groupId>commons-logging</groupId>
               <artifactId>commons-logging</artifactId>
             </exclusion>
         </exclusions>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>${org.springframework-version}</version>
      </dependency>
            
      <!-- AspectJ -->
      <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjrt</artifactId>
         <version>${org.aspectj-version}</version>
      </dependency>   
      
      <!-- Logging -->
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-api</artifactId>
         <version>${org.slf4j-version}</version>
      </dependency>
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>jcl-over-slf4j</artifactId>
         <version>${org.slf4j-version}</version>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
         <version>${org.slf4j-version}</version>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>log4j</groupId>
         <artifactId>log4j</artifactId>
         <version>1.2.17</version>
         <exclusions>
            <exclusion>
               <groupId>javax.mail</groupId>
               <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
               <groupId>javax.jms</groupId>
               <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
               <groupId>com.sun.jdmk</groupId>
               <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
               <groupId>com.sun.jmx</groupId>
               <artifactId>jmxri</artifactId>
            </exclusion>
         </exclusions>
         <scope>runtime</scope>
      </dependency>
 
      <!-- @Inject -->
      <dependency>
         <groupId>javax.inject</groupId>
         <artifactId>javax.inject</artifactId>
         <version>1</version>
      </dependency>
            
      <!-- Servlet -->
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>javax.servlet-api</artifactId>
         <version>3.1.0</version>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>javax.servlet.jsp</groupId>
         <artifactId>javax.servlet.jsp-api</artifactId>
         <version>2.3.1</version>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>jstl</artifactId>
         <version>1.2</version>
      </dependency>
   
      <!-- Test -->
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
         <scope>test</scope>
      </dependency
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-test</artifactId>
         <version>${org.springframework-version}</version>
      </dependency>  
      <!-- oracle JDBC --> 
      <dependency>
         <groupId>com.oracle</groupId>
         <artifactId>ojdbc6</artifactId>
         <version>11.2.0</version>
      </dependency>   
      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis</artifactId>
         <version>3.4.4</version>
      </dependency
      <!-- mybatis-spring라이브러리 추가 -->
      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis-spring</artifactId>
         <version>1.3.1</version>
      </dependency>
      <!-- spring-jdbc -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>${org.springframework-version}</version>
      </dependency>
   </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.10</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
cs

 


* web.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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
</web-app>
 
cs



* root-context.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
<?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:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   
   <!-- Root Context: defines shared resources visible to all other web components -->
   
   <!-- DataSource Bean -->
   <bean id = "ds"
         class="oracle.jdbc.pool.OracleDataSource"
         destroy-method="close">
         <property name ="dataSourceName" value = "ds" />
         <property name = "URL" value="jdbc:oracle:thin:@localhost:1521:XE" />
         <property name = "user" value = "scott" />
         <property name = "password" value = "tiger" />
         
   </bean>
   
   
   
   <!-- MyBatis 프레임워크가 사용할 SqlSessionFactory Bean -->
   
   <bean id = "sqlSessionFactory"
   class = "org.mybatis.spring.SqlSessionFactoryBean">
   <property name="dataSource" ref="ds" />
   <property name = "configLocation" value = "classpath:/mybatis-config.xml"/>
   <property name="mapperLocations" value = "classpath:mappers/*.xml" />
                                           
   </bean>
   
   <!-- MyBatis에서 사용하는 SqlSession Bean -->
   <bean id = "sqlSession"
      class = "org.mybatis.spring.SqlSessionTemplate"
      destroy-method = "clearCache" >
   
   <constructor-arg name="sqlSessionFactory"
      ref = "sqlSessionFactory" />
   
   </bean>
   
</beans>
 
cs


** classpath는 src/main/resources 경로를 의미 **


* servlet-context.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
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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">
 
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
 
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
 
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    
    <context:component-scan base-package="edu.spring.ex02" />
    
</beans:beans>
cs



위 XML 파일들을 수정하면 JDBC와 Mybatis를 사용하기 위한 환경설정이 끝이난다.


+ Recent posts