这可能是关于这个 Spring MVC 错误的第 100 万个问题,但我仍然无法让它工作。
我正在尝试将一个简单的控制器方法映射到 /account,稍后我想添加 /account/{id},但我什至无法让 /account 工作。
这是我的 web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>My Spring MVC web application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
</web-app>
application-context.xml 的内容:
<mvc:annotation-driven />
<context:component-scan base-package="org.example" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
AccountController.java:
@Controller
public class AccountController {
@RequestMapping(value="/account", method = RequestMethod.GET)
public ModelAndView showAccount() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText", "Hello World!");
return mav;
}
}
src/main/webapps/views/account.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1>${someText}</h1>
当我在 Tomcat 中启动应用程序时,我看到日志中出现以下行:
[localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/account], methods=[GET], params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.example.springmvc.controller.AccountController.showAccount() throws java.lang.Exception
对我来说,这表明 url localhost:8080/account 已正确映射,并且至少应该提供一些输出。但是当我访问 localhost:8080/account 时,我收到 404 错误,并且日志显示:
No mapping found for HTTP request with URI [/views/account.jsp] in DispatcherServlet with name 'springDispatcherServlet'
No mapping found for HTTP request with URI [/favicon.ico] in DispatcherServlet with name 'springDispatcherServlet'
您的帮助将不胜感激。