2015-03-06 2 views
1

Итак, у меня есть веб-приложение Spring Maven с несколькими веб-службами RESTful. Для тестирования этот проект весной (4.1.4.RELEASE). Я использую последний инструмент STS (Spring-Eclipse), и я использую Tomcat 8 для сервера.Веб-сервис RESTful не найден при развертывании приложения в eclipse

Мой UserController разработан следующим образом:

@Controller 
@RequestMapping("/users") 
public class UserController { 
    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 

    @Autowired 
    private IUserService service; 

    @RequestMapping(value = "", method = RequestMethod.GET, headers = "Accept=application/json") 
    public @ResponseBody 
    ArrayList<UserEntity> getUserList() 
    { 
     System.out.println("UserController: getUserList: START"); 
     ArrayList<UserEntity> userEntityList = (ArrayList)  service.getAllUsers(); 
     return userEntityList; 
    } 

    @RequestMapping(value = "/", method = RequestMethod.GET, headers = "Accept=application/json") 
    public @ResponseBody 
ArrayList<UserEntity> getAllUsers() 
    { 
     System.out.println("UserController: getAllUsers: START"); 
     ArrayList<UserEntity> userEntityList = (ArrayList)  service.getAllUsers(); 
     return userEntityList; 
    } 

У меня есть тест, который работает, когда я построить приложение с Maven, и это прекрасно работает:

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(locations = 

{ «Путь к классам:/весна /angular-context.xml», "файл: ЦСИ/главная/веб-приложение/WEB-INF/SpringMVC-servlet.xml"}) @Transactional BaseControllerTests общественного класса расширяет TestCase {

@Test 
public void testMockGetUserList1() throws Exception 
{ 
    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("https://stackoverflow.com/users/"); 
     this.mockMvc.perform(requestBuilder).andDo(print()).andExpect(status().isOk()); 
    } 

@Test 
public void testMockGetUserList2() throws Exception 
{ 
    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/users"); 
     this.mockMvc.perform(requestBuilder).andDo(print()).andExpect(status().isOk()); 
} 
} 

Файл веб-XML выглядит следующим образом:

<web-app> 

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:/spring/angular-context.xml</param-value> 
</context-param> 
<context-param> 
    <param-name>log4jConfigLocation</param-name> 
    <param-value>classpath:/logging/log4j-config.xml</param-value> 
</context-param> 

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<!-- Servlets --> 
<servlet> 
    <servlet-name>springmvc</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

<servlet> 
    <servlet-name>jUnitHostImpl</servlet-name> 
    <servlet-class>com.google.gwt.junit.server.JUnitHostImpl</servlet-class> 
</servlet> 

<servlet-mapping> 
    <servlet-name>springmvc</servlet-name> 
    <url-pattern>/rest/*</url-pattern> 
</servlet-mapping> 

<servlet-mapping> 
    <servlet-name>jUnitHostImpl</servlet-name> 
    <url-pattern>/SoccerApp/junithost/*</url-pattern> 
</servlet-mapping> 

<!-- Default page to serve --> 
<welcome-file-list> 
    <welcome-file>index.html</welcome-file> 
</welcome-file-list> 

</web-app> 

И файл углового context.xml выглядит следующим образом:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:lang="http://www.springframework.org/schema/lang" 
xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" 
xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd 
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 

<context:annotation-config /> 
<context:component-scan base-package="com.tomholmes.angularjs.phonebook" /> 

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> 

<bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
    <property name="driverClassName"> 
     <value>com.mysql.jdbc.Driver</value> 
    </property> 
    <property name="url"> 
     <value>jdbc:mysql://localhost:3306/phonebook</value> 
    </property> 
    <property name="username"> 
     <value>myusername</value> 
    </property> 
    <property name="password"> 
     <value>mypassword</value> 
    </property> 

</bean> 

<!-- JNDI DataSource for Java EE environments --> 
<!-- <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/MyDatabase"/> --> 


<!-- Hibernate SessionFactory --> 

<bean id="sessionFactory" 
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 

    <property name="packagesToScan" value="com.tomholmes.angularjs.phonebook.domain" /> 

    <property name="hibernateProperties"> 
     <props> 
      <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
      <prop key="hibernate.show_sql">true</prop> 
      <prop key="hibernate.cglib.use_reflection_optimizer">true</prop> 
     </props> 
    </property> 
    <property name="dataSource" ref="dataSource" /> 
</bean> 


<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> 
    <property name="host" value="mail.tomholmes.net" /> 
    <property name="port" value="587" /> 

    <property name="username" value="myusername" /> 
    <property name="password" value="mypassword" /> 

    <property name="javaMailProperties"> 
     <props> 
      <prop key="mail.smtp.auth">true</prop> 
      <prop key="mail.smtp.starttls.enable">true</prop> 
     </props> 
    </property> 
</bean> 

<!-- 
<bean id="sendMailService" class="com.tomholmes.angularjs.phonebook.shared.util.SendEmailService"> 
    <property name="mailSender" ref="mailSender" /> 
</bean> 
--> 

<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <property name = "sessionFactory" ref = "sessionFactory" /> 
</bean> 

<!-- enable the configuration of transactional behavior based on annotations --> 
<tx:annotation-driven transaction-manager="transactionManager"/> 

</beans> 

Таким образом, этот проект компилируется под мавена просто хорошо. В eclipse (STS) с движком Tomcat 8 он работает нормально, и я могу перейти в свое приложение: http://localhost:8080/angularjs-phone-book/ , и я могу видеть index.html просто отлично, поэтому я знаю, что приложение там.

Если я иду:

http://localhost:8080/angularjs-phone-book/users 
http://localhost:8080/angularjs-phone-book/users/ 
http://localhost:8080/angularjs-phone-book/rest/users 
http://localhost:8080/angularjs-phone-book/rest/users/ 

Ничто не работает, и я получаю ошибку 404, что этот веб-сервис не найден. Но, как я уже сказал, я знаю, что тест работает, но я не вижу, какой именно URL должен быть, чтобы добраться туда.

Я попытался развернуть WAR на Tomcat 8 напрямую, но это веб-приложение даже не начнется там, предположительно из-за проблем с журналом.

Если я могу предоставить дополнительную информацию, пожалуйста, дайте мне знать. Любая помощь в поиске этого была бы замечательной. В конечном счете, я хочу, чтобы пользовательский интерфейс AngularJS на интерфейсе привязывался к веб-сервисам, и мне нужно сначала работать с веб-сервисами.

Спасибо!

ответ

0

Возможно, вам не хватает ссылки на конфигурацию Spring из вашего web.xml. Единичный тест выполняется, потому что вы даете ссылку на XML прямо там, но не в web.xml, поэтому Spring не будет сканировать ваш контроллер для аннотаций.

Используйте <init-param> внутри <servlet>!

И, пожалуй, правильный URL-адрес будет последним, то есть с .../rest/users /, и .../rest/users также возможен с помощью браузера.

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