SlideShare a Scribd company logo
1 of 22
Jersey Framework 맛보기 2011.8.5 김용환  knight76 at gmail.com
특징  REST 표준 API 구현  JAX-RS: Java API for RESTful Web Services (JSR-311)  Servlet 3.0 지원 HTML 포스트 요청에도 사용가능 JAXB / JSON 지원 JRebel(kill 프로세스 없이 웹 어플재시작 가능한 솔루션) 연동 Test Framework이 잘되어 있음 Spring/Juice과 연동 쉬움 용도 REST 방식의 OPEN API Framework.
정보 홈페이지 : http://jersey.java.net/ 사용팀 Ehcache Server (Terracotta) Apache Camel (The Apache Software Foundation) Apache ActiveMQ (The Apache Software Foundation) Dependency Grizzly servlet webserver  (Tomcat에서 사용할 수 있음) Jersey-server JAXB
정보 최신 버전 Jersey 1.0.3.1 implements JAX-RS 1.0. Jersey 1.8 implements JAX-RS 1.1. 문서화 : 잘되어 있음 http://jersey.java.net/nonav/documentation/latest/user-guide.html http://wikis.sun.com/display/Jersey/Main 커뮤니티 활동성 : 무난함 한 달에 user 메일은 200~400 통 사이 버전업 : 1~4개월 사이에 꾸준한 버전업 2010년 5월 1.2 2011년 8월 1.9 개발 중 (조만간 출시 예정)
맛보기 Demo import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces;   1     // The Java class will be hosted at the URI path "/helloworld"   2     @Path("/helloworld")   3     public class HelloWorldResource {   4        5         // The Java method will process HTTP GET requests   6         @GET    7         // The Java method will produce content identified by the MIME Media   8         // type "text/plain"   9         @Produces("text/plain")  10         public String getClichedMessage() {  11             // Return some cliched textual content  12             return "Hello World";  13         }  14     }
맛보기 Demo   1 public class Main {   2              3      public static void main(String[] args) throws IOException {   4                 5          final String baseUri = "http://localhost:9998/";   6          final Map<String, String> initParams =    7 	                       new HashMap<String, String>();   8   9          initParams.put("com.sun.jersey.config.property.packages",   10                  "com.sun.jersey.samples.helloworld.resources");  11   12         System.out.println("Starting grizzly...");  13         SelectorThreadthreadSelector =   14 	          GrizzlyWebContainerFactory.create(baseUri, initParams);  15         System.out.println(String.format(  16           "Jersey app started with WADL available at %sapplication.wadl” +   17           “Try out %shelloworldHit enter to stop it...", baseUri, baseUri));  18         System.in.read();  19         threadSelector.stopEndpoint();  20         System.exit(0);  21     }      22 }
맛보기 DEMO 서버 실행 (main) Client Starting grizzly... 8월 05, 2011 11:01:55 오전 org.glassfish.grizzly.http.server.NetworkListener start 정보: Started listener bound to [localhost:9998] 8월 05, 2011 11:01:55 오전 org.glassfish.grizzly.http.server.HttpServer start 정보: [HttpServer] Started. Jersey app started with WADL available at http://localhost:9998/application.wadl Try out http://localhost:9998/helloworld Hit enter to stop it... $ curl http://localhost:9998/helloworld 8월 05, 2011 11:02:33 오전 com.sun.jersey.api.core.PackagesResourceConfiginit 정보: Scanning for root resource and provider classes in the packages: com.sun.jersey.samples.helloworld.resources 8월 05, 2011 11:02:33 오전 com.sun.jersey.api.core.ScanningResourceConfiglogClasses 정보: Root resource classes found:   class com.sun.jersey.samples.helloworld.resources.HelloWorldResource 8월 05, 2011 11:02:33 오전 com.sun.jersey.api.core.ScanningResourceConfiginit 정보: No provider classes found. 8월 05, 2011 11:02:33 오전 com.sun.jersey.server.impl.application.WebApplicationImpl _initiate 정보: Initiating Jersey application, version 'Jersey: 1.8 06/24/2011 12:17 PM' (결과출력) Hello World
맛보기 DEMO Description 정보 $ curl http://localhost:9998/application.wadl <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <application xmlns="http://research.sun.com/wadl/2006/10">     <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.8 06/24/2011 12:17 PM"/>     <resources base="http://localhost:9998/">         <resource path="/helloworld">             <method id="getClichedMessage" name="GET">                 <response>                     <representation mediaType="text/plain"/>                 </response>             </method>         </resource>     </resources> </application>
@PATH 상대적인 URI path를 의미 예) @Path("/users/{username}") -> http://example.com/users/Galileo  1 @Path("/users/{username}")   2 public class UserResource {   3    4     @GET   5     @Produces("text/xml")   6     public String getUser(@PathParam("username") String userName) {   7         ...   8     }   9 } @Path("users/{username: [a-zA-Z][a-zA-Z_0-9]}")가능
Http Method @GET, @PUT, @POST, @DELETE, @HEAD   1 @PUT   2 public Response putContainer() {   3     System.out.println("PUT CONTAINER " + container);   4    5     URI uri =  uriInfo.getAbsolutePath();   6     Container c = new Container(container, uri.toString());   7    8     Response r;   9     if (!MemoryStore.MS.hasContainer(c)) {  10         r = Response.created(uri).build();  11     } else {  12         r = Response.noContent().build();  13     }  14   15     MemoryStore.MS.createContainer(c);  16     return r;  17 }
@Produce MIME media type 정보 알림   1 @Path("/myResource")   2 @Produces("text/plain")   3 public class SomeResource {   4     @GET   5     public String doGetAsPlainText() {   6         ...   7     }   8    9     @GET  10     @Produces("text/html")  11     public String doGetAsHtml() {  12         ...  13     }  14 }   1 @GET   2 @Produces({"application/xml", "application/json"})   3 public String doGetAsXmlOrJson() {   4     ...   5 } Accept: text/plain 여러 개의 Acception타입지정가능
@Produce XML또는 JSON으로 전달 가능 @Singleton@Path("/person")public class PersonAction {    @GET    @Produces("text/xml")    public Person getPersonMessage() { @Singleton@Path("/person")public class PersonAction{    @GET   @Produces("application/json")    public Person getPersonMessage() {
@QueryParam Query paramter를 받을 수 있음 Default  값 지정 가능   1 @Path("smooth")   2 @GET   3 public Response smooth(   4         @DefaultValue("2") @QueryParam("step") int step,   5         @DefaultValue("true") @QueryParam("min-m") booleanhasMin,   6         @DefaultValue("true") @QueryParam("max-m") booleanhasMax,   7         @DefaultValue("true") @QueryParam("last-m") booleanhasLast,              8         @DefaultValue("blue") @QueryParam("min-color") ColorParamminColor,   9         @DefaultValue("green") @QueryParam("max-color") ColorParammaxColor,  10         @DefaultValue("red") @QueryParam("last-color") ColorParamlastColor  11         ) { ... }
Parameter 구하기  1 @GET   2 public String get(@Context UriInfoui) {   3     MultivaluedMap<String, String> queryParams = ui.getQueryParameters();   4     MultivaluedMap<String, String> pathParams = ui.getPathParameters();   5 }  1 @GET   2 public String get(@Context HttpHeadershh) {   3     MultivaluedMap<String, String> headerParams =hh.getRequestHeaders();   4     Map<String, Cookie> pathParams = hh.getCookies();   5 }   1 @POST   2 @Consumes("application/x-www-form-urlencoded")   3 public void post(MultivaluedMap<String, String>formParams) {   4     // Store the message   5 }
Sub Resource   1 @Singleton   2 @Path("/printers")   3 public class PrintersResource {   4    5     @GET   6     @Produces({"application/json", "application/xml"})   7     public WebResourceListgetMyResources() { ... }   8       9     @GET @Path("/list")  10     @Produces({"application/json", "application/xml"})  11     public WebResourceListgetListOfPrinters() { ... }  12   13     @GET @Path("/jMakiTable")  14     @Produces("application/json")  15     public PrinterTableModelgetTable() { ... } …..
URI building   1 UriBuilder.fromUri("http://localhost/").   2     path("{a}").   3     queryParam("name", "{value}").   4     build("segment", "value"); "http://localhost/segment?name=value":
Exception 처리  1 @Path("items/{itemid}/")   2 public Item getItem(@PathParam("itemid") String itemid) {   3     Item i = getItems().get(itemid);   4     if (i == null)   5         throw new NotFoundException("Item, " + itemid + ", is not found");   6    7     return i;   8 }  1 public class NotFoundException extends WebApplicationException {   2     /**     * Create a HTTP 404 (Not Found) exception.      */   6     public NotFoundException() {   7         super(Responses.notFound().build());   8     }   9    public NotFoundException(String message) {  15         super(Response.status(Responses.NOT_FOUND).  16                 entity(message).type("text/plain").build());  17     }  18 } 404 Error
304 Response  1 public SparklinesResource(   2         @QueryParam("d") IntegerList data,   3         @DefaultValue("0,100") @QueryParam("limits") Interval limits,   4         @Context Request request,   5         @Context UriInfoui) {   6     if (data == null)   7         throw new WebApplicationException(400);   8    9     this.data = data;  10   11     this.limits = limits;  12   13     if (!limits.contains(data))  14         throw new WebApplicationException(400);  15   16     this.tag = computeEntityTag(ui.getRequestUri());  17     if (request.getMethod().equals("GET")) {  18         Response.ResponseBuilderrb = request.evaluatePreconditions(tag);  19         if (rb != null)  20             throw new WebApplicationException(rb.build());  21     }  22 } Request의 Etag확인
Security   1 @Path("basket")   2 public ShoppingBasketResource get(@Context SecurityContextsc) {   3     if (sc.isUserInRole("PreferredCustomer") {   4        return new PreferredCustomerShoppingBaskestResource();   5     } else {   6        return new ShoppingBasketResource();   7     }   8 }
Rules of Injection  1 @Path("id: +")   2 public class InjectedResource {   3     // Injection onto field   4     @DefaultValue("q") @QueryParam("p")   5     private String p;   6    7     // Injection onto constructor parameter   8     public InjectedResource(@PathParam("id") int id) { ... }   9   10     // Injection onto resource method parameter  11     @GET  12     public String get(@Context UriInfoui) { ... }  13   14     // Injection onto sub-resource resource method parameter  15     @Path("sub-id")  16     @GET  17     public String get(@PathParam("sub-id") String id) { ... }  18   19     // Injection onto sub-resource locator method parameter  20     @Path("sub-id")  21     public SubResourcegetSubResource(@PathParam("sub-id") String id) { ... }  22   23     // Injection using bean setter method  24     @HeaderParam("X-header")  25     public void setHeader(String header) { ... }  26 }
API Client/WebResource Building Request Receiving Response
End of Document

More Related Content

What's hot

Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門tamtam180
 
On UnQLite
On UnQLiteOn UnQLite
On UnQLitecharsbar
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기Ji Hun Kim
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM ProfilingAndrei Pangin
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistAnton Arhipov
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsAndrei Pangin
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with nettyZauber
 
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~ikikko
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортSergey Platonov
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGuillaume Laforge
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsAndrei Pangin
 
Oredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsOredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsAnton Arhipov
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Sergey Platonov
 
Hibernate Import.Sql I18n
Hibernate Import.Sql I18nHibernate Import.Sql I18n
Hibernate Import.Sql I18nyifi2009
 
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ..."Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...Vadym Kazulkin
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?Andrei Pangin
 

What's hot (20)

Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
 
On UnQLite
On UnQLiteOn UnQLite
On UnQLite
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репорт
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
Oredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsOredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java Agents
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++
 
Hibernate Import.Sql I18n
Hibernate Import.Sql I18nHibernate Import.Sql I18n
Hibernate Import.Sql I18n
 
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ..."Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
 

Similar to Jersey Framework 맛보기

Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restfulknight1128
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long jaxconf
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxcelenarouzie
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the networkMu Chun Wang
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programingwahyuseptiansyah
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfmeerobertsonheyde608
 
Iss letcure 7_8
Iss letcure 7_8Iss letcure 7_8
Iss letcure 7_8Ali Habeeb
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습DoHyun Jung
 

Similar to Jersey Framework 맛보기 (20)

Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restful
 
My java file
My java fileMy java file
My java file
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
servlets
servletsservlets
servlets
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
03 form-data
03 form-data03 form-data
03 form-data
 
In kor we Trust
In kor we TrustIn kor we Trust
In kor we Trust
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
REST made simple with Java
REST made simple with JavaREST made simple with Java
REST made simple with Java
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
 
Iss letcure 7_8
Iss letcure 7_8Iss letcure 7_8
Iss letcure 7_8
 
Server1
Server1Server1
Server1
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Xml & Java
Xml & JavaXml & Java
Xml & Java
 

More from knight1128

Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)knight1128
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol bufferknight1128
 
Jdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamicJdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamicknight1128
 
공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coinknight1128
 
공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introductionknight1128
 
아마존 Aws 서비스_연구
아마존 Aws 서비스_연구아마존 Aws 서비스_연구
아마존 Aws 서비스_연구knight1128
 
구글크롬Os
구글크롬Os구글크롬Os
구글크롬Osknight1128
 
하이브리드앱
하이브리드앱하이브리드앱
하이브리드앱knight1128
 
오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유knight1128
 
Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상knight1128
 

More from knight1128 (16)

Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
Hancom MDS Conference - KAKAO DEVOPS Practice (카카오 스토리의 Devops 사례)
 
Comet
CometComet
Comet
 
Apache avro
Apache avroApache avro
Apache avro
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Redis
RedisRedis
Redis
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
 
Jdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamicJdk(java) 7 - 5. invoke-dynamic
Jdk(java) 7 - 5. invoke-dynamic
 
Jdk 7 3-nio2
Jdk 7 3-nio2Jdk 7 3-nio2
Jdk 7 3-nio2
 
공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin
 
공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction공유 Jdk 7-1-short introduction
공유 Jdk 7-1-short introduction
 
아마존 Aws 서비스_연구
아마존 Aws 서비스_연구아마존 Aws 서비스_연구
아마존 Aws 서비스_연구
 
속도체크
속도체크속도체크
속도체크
 
구글크롬Os
구글크롬Os구글크롬Os
구글크롬Os
 
하이브리드앱
하이브리드앱하이브리드앱
하이브리드앱
 
오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유오픈소스를 활용한 Batch_처리_플랫폼_공유
오픈소스를 활용한 Batch_처리_플랫폼_공유
 
Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상Ssl 하드웨어 가속기를 이용한 성능 향상
Ssl 하드웨어 가속기를 이용한 성능 향상
 

Recently uploaded

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Recently uploaded (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Jersey Framework 맛보기

  • 1. Jersey Framework 맛보기 2011.8.5 김용환 knight76 at gmail.com
  • 2. 특징 REST 표준 API 구현 JAX-RS: Java API for RESTful Web Services (JSR-311) Servlet 3.0 지원 HTML 포스트 요청에도 사용가능 JAXB / JSON 지원 JRebel(kill 프로세스 없이 웹 어플재시작 가능한 솔루션) 연동 Test Framework이 잘되어 있음 Spring/Juice과 연동 쉬움 용도 REST 방식의 OPEN API Framework.
  • 3. 정보 홈페이지 : http://jersey.java.net/ 사용팀 Ehcache Server (Terracotta) Apache Camel (The Apache Software Foundation) Apache ActiveMQ (The Apache Software Foundation) Dependency Grizzly servlet webserver (Tomcat에서 사용할 수 있음) Jersey-server JAXB
  • 4. 정보 최신 버전 Jersey 1.0.3.1 implements JAX-RS 1.0. Jersey 1.8 implements JAX-RS 1.1. 문서화 : 잘되어 있음 http://jersey.java.net/nonav/documentation/latest/user-guide.html http://wikis.sun.com/display/Jersey/Main 커뮤니티 활동성 : 무난함 한 달에 user 메일은 200~400 통 사이 버전업 : 1~4개월 사이에 꾸준한 버전업 2010년 5월 1.2 2011년 8월 1.9 개발 중 (조만간 출시 예정)
  • 5. 맛보기 Demo import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; 1 // The Java class will be hosted at the URI path "/helloworld" 2 @Path("/helloworld") 3 public class HelloWorldResource { 4 5 // The Java method will process HTTP GET requests 6 @GET 7 // The Java method will produce content identified by the MIME Media 8 // type "text/plain" 9 @Produces("text/plain") 10 public String getClichedMessage() { 11 // Return some cliched textual content 12 return "Hello World"; 13 } 14 }
  • 6. 맛보기 Demo 1 public class Main { 2 3 public static void main(String[] args) throws IOException { 4 5 final String baseUri = "http://localhost:9998/"; 6 final Map<String, String> initParams = 7 new HashMap<String, String>(); 8 9 initParams.put("com.sun.jersey.config.property.packages", 10 "com.sun.jersey.samples.helloworld.resources"); 11 12 System.out.println("Starting grizzly..."); 13 SelectorThreadthreadSelector = 14 GrizzlyWebContainerFactory.create(baseUri, initParams); 15 System.out.println(String.format( 16 "Jersey app started with WADL available at %sapplication.wadl” + 17 “Try out %shelloworldHit enter to stop it...", baseUri, baseUri)); 18 System.in.read(); 19 threadSelector.stopEndpoint(); 20 System.exit(0); 21 } 22 }
  • 7. 맛보기 DEMO 서버 실행 (main) Client Starting grizzly... 8월 05, 2011 11:01:55 오전 org.glassfish.grizzly.http.server.NetworkListener start 정보: Started listener bound to [localhost:9998] 8월 05, 2011 11:01:55 오전 org.glassfish.grizzly.http.server.HttpServer start 정보: [HttpServer] Started. Jersey app started with WADL available at http://localhost:9998/application.wadl Try out http://localhost:9998/helloworld Hit enter to stop it... $ curl http://localhost:9998/helloworld 8월 05, 2011 11:02:33 오전 com.sun.jersey.api.core.PackagesResourceConfiginit 정보: Scanning for root resource and provider classes in the packages: com.sun.jersey.samples.helloworld.resources 8월 05, 2011 11:02:33 오전 com.sun.jersey.api.core.ScanningResourceConfiglogClasses 정보: Root resource classes found: class com.sun.jersey.samples.helloworld.resources.HelloWorldResource 8월 05, 2011 11:02:33 오전 com.sun.jersey.api.core.ScanningResourceConfiginit 정보: No provider classes found. 8월 05, 2011 11:02:33 오전 com.sun.jersey.server.impl.application.WebApplicationImpl _initiate 정보: Initiating Jersey application, version 'Jersey: 1.8 06/24/2011 12:17 PM' (결과출력) Hello World
  • 8. 맛보기 DEMO Description 정보 $ curl http://localhost:9998/application.wadl <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <application xmlns="http://research.sun.com/wadl/2006/10"> <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.8 06/24/2011 12:17 PM"/> <resources base="http://localhost:9998/"> <resource path="/helloworld"> <method id="getClichedMessage" name="GET"> <response> <representation mediaType="text/plain"/> </response> </method> </resource> </resources> </application>
  • 9. @PATH 상대적인 URI path를 의미 예) @Path("/users/{username}") -> http://example.com/users/Galileo 1 @Path("/users/{username}") 2 public class UserResource { 3 4 @GET 5 @Produces("text/xml") 6 public String getUser(@PathParam("username") String userName) { 7 ... 8 } 9 } @Path("users/{username: [a-zA-Z][a-zA-Z_0-9]}")가능
  • 10. Http Method @GET, @PUT, @POST, @DELETE, @HEAD 1 @PUT 2 public Response putContainer() { 3 System.out.println("PUT CONTAINER " + container); 4 5 URI uri = uriInfo.getAbsolutePath(); 6 Container c = new Container(container, uri.toString()); 7 8 Response r; 9 if (!MemoryStore.MS.hasContainer(c)) { 10 r = Response.created(uri).build(); 11 } else { 12 r = Response.noContent().build(); 13 } 14 15 MemoryStore.MS.createContainer(c); 16 return r; 17 }
  • 11. @Produce MIME media type 정보 알림 1 @Path("/myResource") 2 @Produces("text/plain") 3 public class SomeResource { 4 @GET 5 public String doGetAsPlainText() { 6 ... 7 } 8 9 @GET 10 @Produces("text/html") 11 public String doGetAsHtml() { 12 ... 13 } 14 } 1 @GET 2 @Produces({"application/xml", "application/json"}) 3 public String doGetAsXmlOrJson() { 4 ... 5 } Accept: text/plain 여러 개의 Acception타입지정가능
  • 12. @Produce XML또는 JSON으로 전달 가능 @Singleton@Path("/person")public class PersonAction {    @GET    @Produces("text/xml")    public Person getPersonMessage() { @Singleton@Path("/person")public class PersonAction{    @GET   @Produces("application/json")    public Person getPersonMessage() {
  • 13. @QueryParam Query paramter를 받을 수 있음 Default 값 지정 가능 1 @Path("smooth") 2 @GET 3 public Response smooth( 4 @DefaultValue("2") @QueryParam("step") int step, 5 @DefaultValue("true") @QueryParam("min-m") booleanhasMin, 6 @DefaultValue("true") @QueryParam("max-m") booleanhasMax, 7 @DefaultValue("true") @QueryParam("last-m") booleanhasLast, 8 @DefaultValue("blue") @QueryParam("min-color") ColorParamminColor, 9 @DefaultValue("green") @QueryParam("max-color") ColorParammaxColor, 10 @DefaultValue("red") @QueryParam("last-color") ColorParamlastColor 11 ) { ... }
  • 14. Parameter 구하기 1 @GET 2 public String get(@Context UriInfoui) { 3 MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); 4 MultivaluedMap<String, String> pathParams = ui.getPathParameters(); 5 } 1 @GET 2 public String get(@Context HttpHeadershh) { 3 MultivaluedMap<String, String> headerParams =hh.getRequestHeaders(); 4 Map<String, Cookie> pathParams = hh.getCookies(); 5 } 1 @POST 2 @Consumes("application/x-www-form-urlencoded") 3 public void post(MultivaluedMap<String, String>formParams) { 4 // Store the message 5 }
  • 15. Sub Resource 1 @Singleton 2 @Path("/printers") 3 public class PrintersResource { 4 5 @GET 6 @Produces({"application/json", "application/xml"}) 7 public WebResourceListgetMyResources() { ... } 8 9 @GET @Path("/list") 10 @Produces({"application/json", "application/xml"}) 11 public WebResourceListgetListOfPrinters() { ... } 12 13 @GET @Path("/jMakiTable") 14 @Produces("application/json") 15 public PrinterTableModelgetTable() { ... } …..
  • 16. URI building 1 UriBuilder.fromUri("http://localhost/"). 2 path("{a}"). 3 queryParam("name", "{value}"). 4 build("segment", "value"); "http://localhost/segment?name=value":
  • 17. Exception 처리 1 @Path("items/{itemid}/") 2 public Item getItem(@PathParam("itemid") String itemid) { 3 Item i = getItems().get(itemid); 4 if (i == null) 5 throw new NotFoundException("Item, " + itemid + ", is not found"); 6 7 return i; 8 } 1 public class NotFoundException extends WebApplicationException { 2 /** * Create a HTTP 404 (Not Found) exception. */ 6 public NotFoundException() { 7 super(Responses.notFound().build()); 8 } 9 public NotFoundException(String message) { 15 super(Response.status(Responses.NOT_FOUND). 16 entity(message).type("text/plain").build()); 17 } 18 } 404 Error
  • 18. 304 Response 1 public SparklinesResource( 2 @QueryParam("d") IntegerList data, 3 @DefaultValue("0,100") @QueryParam("limits") Interval limits, 4 @Context Request request, 5 @Context UriInfoui) { 6 if (data == null) 7 throw new WebApplicationException(400); 8 9 this.data = data; 10 11 this.limits = limits; 12 13 if (!limits.contains(data)) 14 throw new WebApplicationException(400); 15 16 this.tag = computeEntityTag(ui.getRequestUri()); 17 if (request.getMethod().equals("GET")) { 18 Response.ResponseBuilderrb = request.evaluatePreconditions(tag); 19 if (rb != null) 20 throw new WebApplicationException(rb.build()); 21 } 22 } Request의 Etag확인
  • 19. Security 1 @Path("basket") 2 public ShoppingBasketResource get(@Context SecurityContextsc) { 3 if (sc.isUserInRole("PreferredCustomer") { 4 return new PreferredCustomerShoppingBaskestResource(); 5 } else { 6 return new ShoppingBasketResource(); 7 } 8 }
  • 20. Rules of Injection 1 @Path("id: +") 2 public class InjectedResource { 3 // Injection onto field 4 @DefaultValue("q") @QueryParam("p") 5 private String p; 6 7 // Injection onto constructor parameter 8 public InjectedResource(@PathParam("id") int id) { ... } 9 10 // Injection onto resource method parameter 11 @GET 12 public String get(@Context UriInfoui) { ... } 13 14 // Injection onto sub-resource resource method parameter 15 @Path("sub-id") 16 @GET 17 public String get(@PathParam("sub-id") String id) { ... } 18 19 // Injection onto sub-resource locator method parameter 20 @Path("sub-id") 21 public SubResourcegetSubResource(@PathParam("sub-id") String id) { ... } 22 23 // Injection using bean setter method 24 @HeaderParam("X-header") 25 public void setHeader(String header) { ... } 26 }
  • 21. API Client/WebResource Building Request Receiving Response