This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.contextprovider; | |
import javax.ws.rs.ext.ContextResolver; | |
import javax.ws.rs.ext.Provider; | |
@Provider | |
public class MyContextResolver implements ContextResolver<MyContext> { | |
private MyContext context=new MyContextImpl(); | |
@Override | |
public MyContext getContext(Class<?> type){ | |
if(type == String.class) | |
return context; | |
return null; | |
} | |
private static class MyContextImpl implements MyContext<String>{ | |
@Override | |
public String get(String key){ | |
return "a context value for key = "+key; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.contextprovider; | |
public interface MyContext<T> { | |
T get(String key); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.contextprovider; | |
import javax.ws.rs.GET; | |
import javax.ws.rs.Path; | |
import javax.ws.rs.PathParam; | |
import javax.ws.rs.core.Context; | |
import javax.ws.rs.core.MediaType; | |
import javax.ws.rs.ext.ContextResolver; | |
import javax.ws.rs.ext.Providers; | |
@Path("/") | |
public class MyResource { | |
@GET | |
@Path("{path}") | |
public String create(@PathParam("path")String path, | |
@Context Providers providers){ | |
ContextResolver<MyContext> cr=providers.getContextResolver(MyContext.class,MediaType.WILDCARD_TYPE); | |
MyContext<String> c=cr.getContext(String.class); | |
String r=c.get(path); | |
return "response: "+r; | |
} | |
} |
Kaynak sınıfımızda ise @GET metodu ile kullanıcıdan alınan parametre String path değişkeninde tutulmuş.Daha sonra @Context ek açıklamasıyla Providers interface'inden bir nesne türetilmiş.@Context ek açıklamasını daha ayrıntılı öğrenmek istiyorsanız buraya tıklayınız.Sonraki işlemlerde bildiğimiz klasik işlemler.Bir de WILCARD_TYPE var.WILCARD_TYPE içinde bilinmeyen bir sınıfın nesnelerini tutar.
Çıktımız ise bu şekilde
http://localhost:8080/ContextProvider/contextprovider
response: a context value for key = contextprovider
GÖRÜŞMEK ÜZERE...
Hiç yorum yok:
Yorum Gönder