2016년 7월 26일 화요일

Spring4 RESTFul 웹서비스예제(JSON응답으로오라클테이블데이터를,jackson json 라이브러리사용,@RestController, @ResponseBody) - 스프링실무교육학원



Spring4 RESTFul 웹서비스예제(JSON응답으로오라클테이블데이터를,jackson json 라이브러리사용,@RestController, @ResponseBody) - 스프링실무교육학원

 아래 예제는 오라클의 ONJ 라는 테이블에서 전체데이터를 읽어 JSON 응답으로 만드는 기능과, NAME으로 검색하여 한건의 레코드를 Onj 객체로 만들어 JSON 응답으로 보내는 기능의 예제인데, 응답을 기존에 많이 사용하는 JSP가 아닌 JSON으로 보내기 위해 jackson library 및 Spring4의 @RestController를 사용했다.

 또한 RestFul WebService를 구현하기 위해 파라미터가 아닌 URL경로로 NAME을 넘겨주면 @RequestMapping을 이용하여, 파라미터로 받아서 DB 쿼리에서 인자로 이용해 해당 NAME의 데이터를 검색 후 JSON 응답으로 만들어 클라이언트로 보냈다.

@RestController 어노테이션은@Controller를 상속받아 @Controller + @ResponseBody와 같은 의미로써 Restful웹서비스를 구현할 때  응답은 항상 응답바디(response body)에 보내져야 하는데 이를위해 스프링4.0에서 특별히 @ResrController를 제공한다. 

 도메인객체를 Web Service로 노출 가능하며 각각의 @RequestMapping method에 @ResponseBody할 필요가 없어진다. 그러므로 Spring MVC에서 @ReponseBody를 이용하여  JSON or XML 포맷으로 데이터를 넘길 수 있다.

0. 전체 이클립스 구성화면


1. 오라클 scott/tiger 계정에 실습을 위한 테이블 생성

SQL>  create table onj (
  2  name varchar2(50),
  3  url varchar2(50));

테이블이 생성되었습니다.

SQL>  insert into onj values ('community','ojc.asia');
1 개의 행이 만들어졌습니다.

SQL>  insert into onj values ('edu','ojcedu.com');
1 개의 행이 만들어졌습니다.

SQL> commit;
커밋이 완료되었습니다.



2. spring4rest2 라는 spring mvc 프로젝트 생성(Context이름도 같이 주기위해 top level package 마지막도 spring4rest2로 주자)

3. pom.xml

<?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>onj.spring</groupId>
<artifactId>rest</artifactId>
<name>spring4rest2</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>4.1.0.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</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>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-__EXPRESSION__</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- ORACLE -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.1.0.7.0</version>
</dependency>


<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.2</version>
</dependency>

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

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.2</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.15</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>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<!-- DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>


<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>oracle</id>
<name>ORACLE JDBCRepository</name>
<url>http://maven.jahia.org/maven2</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</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>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</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.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>




4. /WEB-INF/web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">

<display-name>Spring MVC Rest(OracleJava Community)</display-name>

<!-- Processes application requests -->
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>



5.  /WEB-INF/rest-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="controller" />
<context:component-scan base-package="service" />
<context:component-scan base-package="dao" />
<mvc:annotation-driven />
</beans>


6. src/main/resources/db.properties

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@192.168.0.7:1521:onj
user=scott
password=tiger



7. OnjRestController.java


package controller;
import java.util.List;

import model.Onj;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import service.OnjService;

@RestController
@RequestMapping("/service/onj/")
public class OnjRestController {
@Autowired
private OnjService onjService;
@RequestMapping(method=RequestMethod.GET, headers="Accept=application/json")
public List<Onj> getAllOnj() {
List<Onj> onjs = onjService.getAllOnj();
return onjs;
}
@RequestMapping(value="/{name}", method=RequestMethod.GET, headers="Accept=application/json")
public Onj getOnj(@PathVariable String name) {
Onj onj = onjService.getOnjByName(name);
return onj;
}
}





8. DBUtil.java


package dao;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
private static Connection connection = null;

public static Connection getConnection() {
if (connection != null)
return connection;
else {
try {
Properties prop = new Properties();
InputStream inputStream = DBUtil.class.getClassLoader()
.getResourceAsStream("db.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();

} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}

}



9. OnjDAO.java

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import model.Onj;

import org.springframework.stereotype.Repository;

@Repository("onjDao")
public class OnjDAO {
private Connection connection;

public OnjDAO() {
connection = DBUtil.getConnection();
}

//onj 테이블의 모든 데이터를 LIST 구조에 담아 리턴
public List<Onj> getAllOnjs() {
List<Onj> users = new ArrayList<Onj>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement
.executeQuery("select name, url from onj");
while (rs.next()) {
Onj onj = new Onj();
onj.setName(rs.getString("name"));
onj.setUrl(rs.getString("url"));
users.add(onj);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}

//이름을 통래 데이터 한건 SELECT 후 Onj 객체에 담아 리턴
public Onj getOnjByName(String name) {
Onj onj = new Onj();
try {
PreparedStatement preparedStatement = connection
.prepareStatement("select name, url from onj where name=?");
preparedStatement.setString(1, name);

ResultSet rs = preparedStatement.executeQuery();

if (rs.next()) {
onj.setName(rs.getString("name"));
onj.setUrl(rs.getString("url"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return onj;
}
}





10. model쪽의 Onj.java


package model;

import org.springframework.stereotype.Component;

public class Onj {
String name;
String url;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "NAME:" + name + ",URL:" + url;
}
}




11. service쪽의 OnjService.java


package service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.Onj;

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

import dao.OnjDAO;

@Service("onjService")
public class OnjService {
Map<String, Onj> onjs;
@Autowired
private OnjDAO onjDao;
public List<Onj> getAllOnj() {
return onjDao.getAllOnjs();
}
public Onj getOnjByName(String name) {
Onj onj = onjDao.getOnjByName(name);
return onj;
}
}



12. 실행화면

<br><br><br>






댓글 없음:

댓글 쓰기