RESTful 서비스 만들기

빈 WebApplication 만들기



다른 IDE도 Maven이 아니어도 좋지만
이번에는 NetBeans에서 MavenProject의 WebApplication을 작성.







필요한 라이브러리 설정



jersey와 jackson은 넣어 둔다.
dependencies 태그에 추가.
그리고 이번에는 glassfish-embedded-all 이것도.

pom.xml
       <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.17</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.17</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.main.extras</groupId>
            <artifactId>glassfish-embedded-all</artifactId>
            <type>jar</type>
            <version>4.1</version>
            <scope>provided</scope>
        </dependency>

필터 설정



그 밖에도 방법은 있는 것 같지만, 필터를 추가하는 방식으로.

beans.xml 만들기 (하지 않아도 움직일 것이라고 생각)





beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:weld="http://jboss.org/schema/weld/beans"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"
       bean-discovery-mode="annotated">
    <weld:scan>
    </weld:scan>
    <alternatives></alternatives>
</beans>

web.xml 만들기





web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="false" version="3.0" 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_3_0.xsd">
    <filter>
      <filter-name>servlet-container</filter-name>
      <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
      <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.mycompany.myrestwar.MyWebApplication</param-value>
      </init-param>
    </filter>
    <filter-mapping>
      <filter-name>servlet-container</filter-name>
      <url-pattern>/rest/*</url-pattern>
    </filter-mapping>    
</web-app>

Application 클래스는 계속해서 생성한다.

구현하기



REST 서비스 클래스 작성





TestRestREsource.java
package com.mycompany.myrestwar;

import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

/**
 * RESTのサービスクラス
 * @author foo
 */
@Path("/rest/test")
@RequestScoped
public class TestRestResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of TestResource
     */
    public TestRestResource() {

    }

    /**
     * Retrieves representation of an instance of jp.co.infomart.dataServiceNgs.product.rest.TestResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    public String getText() {
        return "this is just test for restful...";
    }

    /**
     * PUT method for updating or creating an instance of TestResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("text/plain")
    public void putText(String content) {
        // なにもしない
    }

}

Application 클래스 만들기





MyWebApplication.java
package com.mycompany.myrestwar;

import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;

/**
 * RESTのアプリケーションクラス
 * @author foo
 */
@ApplicationPath("rest")
public class MyWebApplication extends ResourceConfig  {

    public MyWebApplication() {

        // 本当はパッケージ配下のやつを全部登録できるが
        // packages(this.getClass().getPackage().getName());

        // 今回は個別で
        this.register(TestRestResource.class);
    }

}

움직이다



이것으로 끝나고 배포하고 URL을 두드리면 ...



안전하게 작동합니다. 정말 이것만.

PUT 및 POST를 구현하거나
json 형식으로 설정이나 취득을 실시하는 것도 jackson을 사용하면 간단하게 할 수 있다.

참고: json 처리



GET 방법
    import java.io.IOException;
    import java.security.InvalidParameterException;
    import com.fasterxml.jackson.core.JsonGenerationException;
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;

    private static ObjectMapper mapper = new ObjectMapper();

    @GET
    @Produces("application/json")
    public String getJson() {

        Map<String, Object> responseData = new HashMap<>();
        responseData.put("Name", "Hakozaki");
        responseData.put("Age", 39);

        try {
            return mapper.writeValueAsString(responseData);
        } catch (JsonMappingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

    }

덧붙여 json -> Object로의 변환은 이하와 같은 느낌

샘플
    Map<String, Object> m 
        = mapper.readValue(
            jsonString, new TypeReference<Map<String, Object>>() {});

POST에서 입출력 처리



POST 메소드
    @POST
    @Produces("text/plain")
    @Consumes("text/plain")
    public String postText(String content) {
        return content + " is Post Data...";
    }    

좋은 웹페이지 즐겨찾기