Reputation: 30320
As much as I have done with Spring, I have never done anything with Spring MVC and wanted to experiment to see how it compares with things I know better like Grails and Rails. I have a trivial application with a single JSP and a single controller endpoint, but I have been unable to get Spring MVC to resolve my path to the JSP.
Here is web.xml in WEB-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>
Here is dispatcher-servlet.xml in 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>
And my one controller in the com.springapp
package:
@Controller
@RequestMapping("/")
public class MyController {
@RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model, HttpServletRequest request) {
return "hello";
}
}
Meanwhile, there is a file called hello.jsp in WEB-INF/jsp.
When I navigate to "/" in my application, I get a 404 when I figured I would get hello.jsp.
I also have an integration test that confirms the same problem by failing with a 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"));
}
}
I am sure I am missing something obvious, so I would love the Spring MVC experts to tell me what that is.
Upvotes: 1
Views: 1549
Reputation: 94499
You must add <mvc:annotation-driven/>
to your spring configuration, this tells Spring MVC to pickup annotations such as @RequestMapping
.
See the documentation for further information regarding annotation-driven
.
Upvotes: 2