我正試圖訪問我機器上的http://localhost:8080/EventTracker/greeting。但是,我收到了404錯誤。我正在關注Spring MVC4教程的PluralSight簡介,並且好像我的代碼與視頻中的代碼相匹配。我正在使用兩個Java文件WebConfig和WebAppInitializer來配置我的應用程序。我錯過了什麼?我認爲我已經逐行復制,但仍然無法正常工作。HTTP狀態404 -/EventTracker/greeting
HelloController.java
@Controller
public class HelloController {
@RequestMapping(value="/greeting")
public String sayHello(Model model) {
model.addAttribute("greeting", "Hello World");
return "hello.jsp";
}
}
WebAppInitializer.java
public class WebAppInitializer implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.html");
}
private WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.pluralsight.WebConfig");
return context;
}
}
WebConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.pluralsight")
public class WebConfig {
}
的hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>${greeting}</h1>
</body>
</html>
EDITED 9/15 4:25 PM PST 當使用http://localhost:8080/EventTracker/greeting.html,我仍然得到同樣的錯誤,錯誤的存在:
16:24:41.925 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'DispatcherServlet' processing GET request for [/EventTracker/greeting.html]
16:24:41.931 [http-nio-8080-exec-3] WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/EventTracker/greeting.html] in DispatcherServlet with name 'DispatcherServlet'
16:24:41.931 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
你能發佈你的DispatcherServlet.xml代碼嗎?看起來您的錯誤與您的應用沒有在您的DispatcherServlet文件中找到正確的映射有關。 – jeffkempf
我沒有任何用於配置的xml文件。所有配置都由java文件完成 – LinhSaysHi
如果您決定使用xml文件,我發佈了一個答案,可以幫助您解決404錯誤。我不確定只使用java文件。 – jeffkempf