我是Spring MVC的初学者,并尝试执行教程中给出的演示spring程序
https://www.youtube.com/watch?v=dDWNTR0-rns&list=PLBgMUB7xGcO31B2gBmy1igpZn6LK78-CJ&index=9
在运行程序时,我收到HTTP 404错误,并且描述为“源服务器未找到目标资源的当前表示或不愿意透露该资源的存在”。有人可以帮我解决这个问题。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FirstSpringMVCAnnotations</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-dispatcher-servlet.xml
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package = "com.demo.controller"/>
<mvc:annotation-driven/>
<bean id = "viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp"/>
</bean>
</beans>
PathVariableDemoController
package com.demo.controller;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
@Controller
@RequestMapping("/greeting")
public class PathVariableDemoController {
@RequestMapping("/hello/{username}/{countryname}")
public ModelAndView helloWorld(@PathVariable("username") String username, @PathVariable("countryname") String countryname) {
System.out.println("Inside PathVariableDemoController...");
ModelAndView modelView = new ModelAndView("Greetings");
String msg = "Hello " + username + " You are from " + countryname;
modelView.addObject("greetingsMessage", msg);
System.out.println("End PathVariableDemoController helloWorld()...");
return modelView;
}
}
Greetings.jsp
<html>
<body>
<h1>Message is: ${greetingsMessage}</h1>
</body>
</html>
项目结构:
错误屏幕截图:
答案 0 :(得分:0)
上面Controller中ModelAndView的导入是portlet包。
import org.springframework.web.portlet.ModelAndView;
如下所述在Controller类中更改ModelAndView的导入可解决此问题。
import org.springframework.web.servlet.ModelAndView;