我试图用Spring MVC做一个简单的例子。每个代码对我来说似乎都没问题,但仍然有404错误。这是我的代码,请你帮我解释为什么我会收到此错误?
web.xml:
<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>Demo</display-name>
<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Demo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Demo</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Demo-servlet.xml</param-value>
</context-param>
Demo-servlet.xml(Dispatcher Servlet):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<mvc:annotation-driven />
<context:component-scan base-package="com.Demo" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
hello.jsp:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
</head>
<body>
<h1>Gradle - Spring MVC Hello World</h1>
<h2>Hello ${name}</h2>
</body>
</html>
HomeController.java:
package com.Demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/")
public class HomeController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("name", "Hello Spring MVC Framework!");
return "hello";
}
}
请帮我解决这个问题。 提前致谢
答案 0 :(得分:0)
将您的web.xml更改为:
<servlet-mapping>
<servlet-name>Demo</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
将您的控制器更改为:
@Controller
@RequestMapping("/demo")
public class HomeController
现在打开浏览器并使用以下命令调用Controller://demo.htm
在开发期间,如果启用Spring调试日志,则会很好。至少直到你掌握了框架。它们提供有价值的信息