2014-01-31 66 views
1

就像我對Spring所做的一樣,我從來沒有對Spring MVC做過任何事情,並且想要試驗一下,看看它和Grails和Rails更好的對比。我有一個簡單的應用程序,只有一個JSP和一個控制器端點,但我一直無法獲得Spring MVC來解析我的JSP路徑。InternalResourceViewResolver未解決

這裏是的web.xmlWEB-INF

<servlet> 
    <servlet-name>dispatcher</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <load-on-startup>1</load-on-startup> 
</servlet>  
<servlet-mapping> 
    <servlet-name>dispatcher</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 

這裏是調度-servlet.xml中在WEB-INF:

<beans...>  
    <context:component-scan base-package="com.springapp"/> 
    <context:property-placeholder location="classpath*:my.properties"/> 
    <mvc:resources mapping="/webjars/**" location="/webjars/"/> 

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> 
     <property name="prefix" value="/WEB-INF/jsp/"/> 
     <property name="suffix" value=".jsp"/> 
    </bean> 

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> 
     <property name="messageConverters"> 
      <list> 
       <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> 
      </list> 
     </property> 
    </bean> 
</beans> 

而我的一個控制器在com.springapp包中:

@Controller 
@RequestMapping("/") 
public class MyController { 

    @RequestMapping(method = RequestMethod.GET) 
    public String printWelcome(ModelMap model, HttpServletRequest request) { 
     return "hello"; 
    } 
} 

同時,有一個文件叫做hello.jsp in WEB-INF/jsp

當我在我的應用程序中導航到「/」時,我得到一個404,當我想我會得到hello.jsp

我也有一個集成測試,通過一個404失敗確認了同樣的問題:

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration("file:src/main/webapp/WEB-INF/dispatcher-servlet.xml") 
public class AppIT { 
    private MockMvc mockMvc; 

    @SuppressWarnings("SpringJavaAutowiringInspection") 
    @Autowired 
    protected WebApplicationContext wac; 

    @Before 
    public void setup() { 
     this.mockMvc = webAppContextSetup(this.wac).build(); 
    } 

    @Test 
    public void testMVC() throws Exception { 
     mockMvc.perform(get("/")) 
       .andExpect(status().isOk()) 
       .andExpect(view().name("hello")); 
    } 
} 

我相信我缺少明顯的東西,所以我很想在Spring MVC的專家告訴我是什麼是。

回答

2

您必須將<mvc:annotation-driven/>添加到您的彈簧配置中,這會告知Spring MVC拾取註釋,例如@RequestMapping

有關annotation-driven的更多信息,請參閱documentation

+0

你這次得到了我! –

+0

@SotiriosDelimanolis哈哈,你讓我最後35次! –

+0

有趣的是,這可以讓我的手動請求通過,但我的測試仍然失敗。當然,仍然是積極的。有什麼想法嗎?我的測試形式是否不正確? – Vidya