2016-03-31 2 views
0

У меня есть мое обслуживание как;Как получить доступ к развернутой войне в дико v 10?

@Path("/fileservice/") 
public class FileService { 
@POST 
    @Path("/{path}/{filename}/{source}/{client}") 
    public Response getFilePath(
      @PathParam("path") String filePath, 
      @PathParam("filename") String fileName, 
      @PathParam("source") String fileSource, 
      @PathParam("client") String clientId) { 

....... 

} 

и активировать банки;

@ApplicationPath("rest") 
public class JaxRsActivator extends Application{ 

} 

У меня нет web.xml.

Когда я пытаюсь получить доступ к этой войне из браузера; i use;

http://localhost:8080/mywar/rest/fileservice 

Но я получаю;

6:09:28,215 ERROR [org.jboss.resteasy.resteasy_jaxrs.i18n] (default task-15) RESTEASY002010: Failed to execute: javax.ws.rs.NotFoundException: RESTEASY: Could not find resource for full path: http://localhost:8080/mywar/rest/fileservice 
     at org.jboss.resteasy.core.registry.SegmentNode.match(SegmentNode.java:114) 
     at org.jboss.resteasy.core.registry.RootNode.match(RootNode.java:43) 
     at org.jboss.resteasy.core.registry.RootClassNode.match(RootClassNode.java:48) 
     at 

org.jboss.resteasy.core.ResourceMethodRegistry.getResourceInvoker(ResourceMethodRegistry.java:445) 
     at org.jboss.resteasy.core.SynchronousDispatcher.getInvoker(SynchronousDispatcher.java:257) 
     at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:194) 
     at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:221) 
     at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56) 
     at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51) 
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) 
     at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) 
     at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62) 
     at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) 
     at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78) 
     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
     at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) 
     at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57) 
     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
     at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46) 
     at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64) 
     at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60) 
     at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77) 
     at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50) 
     at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43) 
     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
     at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61) 
     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
     at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) 
     at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284) 
     at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263) 
     at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81) 
     at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174) 
     at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202) 
     at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793) 
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
     at java.lang.Thread.run(Thread.java:745) 

Может ли кто-нибудь помочь мне в том, что я делаю неправильно?

+1

По определению ваш корневой контекст WAR указывает на * http: // localhost: 8080/mywar/*. Что вы делаете, используя * http: // localhost: 8080/mywar/rest/fileservice *, обращается к вашей службе REST через браузер, и я не думаю, что это то, что вы хотите. – aribeiro

+0

@aribeiro, если я называю http: // localhost: 8080/mywar, я получаю «запрещенное» сообщение. Итак, вы говорите, что я могу получить доступ к моему веб-приложению? – Ratha

+0

@aribeiro, если я пытаюсь получить доступ к моему сервису отдыха, например http: // localhost: 8080/mywar/rest/fileservice/ab/swd/sadwd/asas, я также не получаю исключения на консоли сервера, но браузер говорит: NotFound " – Ratha

ответ

1

Вы не можете получить доступ к этому ресурсу из веб-браузера, потому что он установлен как метод POST. Вам нужно будет использовать инструмент, который может отправлять запросы POST и предоставлять параметры /{path}/{filename}/{source}/{client}, которые вы определили.

+0

Я пробовал простой вызов GET http: // localhost: 8080/mywar/rest/fileservice/id и все еще не найден. Добавлен метод GET как; @GET \t @Path ("/ {id}") \t public String getUser (@PathParam ("id") String id) { – Ratha

0

В соответствии с JAX-RS documentation@PathParam следует использовать для запросов GET.

Для запросов POST следует либо использовать JSON, либо JAXB для полного сущности объекта или использовать @FormParam, когда намерение состоит в том, чтобы извлекать информацию, которая соответствует кодировке, заданной форматами HTML. This Ответ, Д.Шаули, может разъяснить вам больше на эту тему.

Принимая код, который вы размещены в качестве основы, следующий простой рабочий пример:

Базовый URI для всех REST услуг

@ApplicationPath("/rest") 
public class JaxRsActivator extends Application {} 

The Rest Service

@Path("/fileservice") 
public class FileService { 

    @GET 
    @Path("/{id}") 
    @Produces("text/html") 
    public Response getFileId(@PathParam("id") String fileId) { 
     System.out.println(fileId); 

     return Response.ok().entity(fileId).build(); 
    } 

    @POST 
    @Path("/file") 
    @Consumes(MediaType.APPLICATION_XML) 
    public Response createFile(MyFile myFile) { 
     System.out.println(myFile.id); 

     return Response.ok().build(); 
    } 
} 

Предприятие

@XmlRootElement(name="file") 
public class MyFile { 

    @XmlElement 
    public String id; 

    @XmlElement 
    public String name; 

    public MyFile() {} 
} 

Ваш WAR 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/xsd/maven-4.0.0.xsd"> 

    <modelVersion>4.0.0</modelVersion> 
    <groupId>war-group</groupId> 
    <artifactId>war-artifact</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>war</packaging> 

    <dependencies> 
     <dependency> 
      <groupId>javax</groupId> 
      <artifactId>javaee-api</artifactId> 
      <version>7.0</version> 
      <scope>provided</scope> 
     </dependency> 
    </dependencies> 
</project> 

Тогда для того, чтобы протестировать службу REST, вы можете создать простой клиент, который может выглядеть следующим образом:

public class FileServiceClient { 

    public static void main(String[] args) throws Exception { 
     callRestServiceGET(); 

     callRestServicePOST(); 
    } 

    protected static void callRestServiceGET() { 
     URI uri = null; 

     try { 
      uri = new URI("http://localhost:8080/war-artifact-0.0.1-SNAPSHOT/rest/fileservice/98765"); 
     } catch (URISyntaxException e) { 
      e.printStackTrace(); 
     } 

     Client client = ClientBuilder.newClient(); 

     Response response = client.target(uri).request().get(); 
     System.out.println("GET sended, response status: " + response.getStatus()); 
    } 

    protected static void callRestServicePOST() { 
     URI uri = null; 

     try { 
      uri = new URI("http://localhost:8080/war-artifact-0.0.1-SNAPSHOT/rest/fileservice/file"); 
     } catch (URISyntaxException e) { 
      e.printStackTrace(); 
     } 

     Client client = ClientBuilder.newClient(); 

     String xml = "<file><id>1234567</id><name>abc</name></file>"; 

     Response response = client.target(uri).request().post(Entity.xml(xml)); 
     System.out.println("POST sended, response status: " + response.getStatus()); 
    } 
} 
Смежные вопросы