2015-12-15 4 views
0

Я видел другие похожие сообщения здесь, в stackoverflow - в основном плакат попадает в ссылку, отличную от того, что разрешает метод обслуживания в RESTController. Я убедился (объяснено ниже), что я не делаю этой ошибки, но все еще не работает для меня.Весна mvc4 http 404 не найдена ошибка

Я пишу контроллер REST на основе Spring MVC4 для контейнера Servlet 2.5 (weblogic 10.3.6), и я был предложил следовать этому sample web.xml для моего веб-приложения проекта

Я следовал этой web.xml, но я не уверен, что делает ContextAttribute со значением (как показано ниже) в этой части ..

<servlet> 
    <servlet-name>appServlet</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextAttribute</param-name> 
     <param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

Когда я я запускаю мой webapp и ударяю его с клиентом REST, я все время получаю http 404, не найденную ошибку. Полная ошибка размещена здесь http://paste.ubuntu.com/13966788/

Вот фрагмент кода ошибки

08:44:34.368 [main] DEBUG o.s.web.client.RestTemplate - GET request for "http://localhost:7001/demo-0.0.1-SNAPSHOT/customers/2" resulted in 404 (Not Found); inv 
    oking error handlerTests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.402 sec <<< FAILURE! - in demo.DemoApplicationTests 
contextLoaded(demo.DemoApplicationTests) Time elapsed: 0.042 sec <<< ERROR! 
org.springframework.web.client.HttpClientErrorException: 404 Not Found 
     at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) 
     at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641) 
     at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597) 
     at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) 
     at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:289) 
     at demo.DemoApplicationTests.contextLoaded(DemoApplicationTests.java:45) 

я не уверен, что должен быть мой корневой контекст, развернут WebApp в консоли WebLogic показывает значение «демо-0.0.1 -SNAPSHOT '

и мой метод @RequestMapping моего REST-контроллера/клиенты/{id}.

@RestController 
public class CustomerRestController { 
    @Autowired 
    private CustomerRepository customerRepository; 
@RequestMapping("/customers/{id}") 
CustomerProtos.Customer customer(@PathVariable Integer id) { 
    return this.customerRepository.findById(id); 
} 

Так я предполагаю, что мой URL путь должен выглядеть

localhost:7001/demo-0.0.1-SNAPSHOT/customers/2 

, но когда я попал этот URL (как в браузере и весной на основе тестового клиента) я получаю HTTP 404 не найдена ошибка.

Вот моя весна тестовый клиент ..

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration 
public class DemoApplicationTests { 

@Configuration 
public static class RestClientConfiguration { 

    @Bean 
    RestTemplate restTemplate(ProtobufHttpMessageConverter hmc) { 
     return new RestTemplate(Arrays.asList(hmc)); 
    } 

    @Bean 
    ProtobufHttpMessageConverter protobufHttpMessageConverter() { 
     return new ProtobufHttpMessageConverter(); 
    } 
} 
@Autowired 
private RestTemplate restTemplate; 
@Test 
public void contextLoaded() { 

    ResponseEntity<CustomerProtos.Customer> customer = restTemplate.getForEntity(
      "http://localhost:7001/demo-0.0.1-SNAPSHOT/customers/2", CustomerProtos.Customer.class); 

    System.out.println("customer retrieved: " + customer.toString()); 
} 

Интересно, если ContextAttribute делает что-то здесь. Есть идеи ?

Единственная вещь, которую я делаю здесь, вместо httpMessageConverter, я регистрирую ProtoBufHttpMessageConverter Spring MVC4. Но не следует делать разницу в этом случае.

Мой код является общим (на GitHub) здесь https://goo.gl/cVNEPT

ответ

1

Есть ли у вас servletMapping определяется как в web.xml?

<servlet-mapping> 
    <servlet-name>appServlet</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 

Кроме того, у общественности для метода

@RequestMapping("/customers/{id}") 
public CustomerProtos.Customer customer(@PathVariable Integer id) 

вы видите путь запроса отображения регистрируемого в журнале?

+0

Я немного изменил ситуацию. Получил web.xml из простого веб-приложения (вместо проекта загрузки весны) выглядит так: https://jsfiddle.net/7t03hx3t/ также сделал мой метод отдыха общедоступным, видимо, я могу попасть в веб-службу Теперь. Я получаю еще одну проблему, связанную с 406 неприемлемым , как показано здесь - https://jsfiddle.net/3h1Lg75h/ Но я отправлю отдельный вопрос по этой проблеме. Спасибо за вашу помощь. –

Смежные вопросы