【发布时间】:2015-04-15 09:28:07
【问题描述】:
我正在尝试在没有 xml 配置的情况下运行基本的 spring-4 web-mvc 应用程序。我查看了 spring 文档和示例,但它对我不起作用。 我的控制器:
package com.nikolay.exam.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HomeController {
@RequestMapping(value = "/home", method = RequestMethod.GET)
@ResponseBody
public String home() {
return "Hello world!";
}
}
应用配置:
package com.nikolay.exam.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
}
网络配置:
package com.nikolay.exam.config;
import com.nikolay.exam.controller.HomeController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public HomeController homeController() {
return new HomeController();
}
}
和WebInitializer:
package com.nikolay.exam.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.setConfigLocation("com.nikolay.exam.config");
servletContext.addListener(new ContextLoaderListener(root));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(root));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
但是当我在 tomcat 上运行我的应用程序时,我收到一个错误:
2015 年 2 月 14 日 11:35:29.825 警告 [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound 未找到带有 URI [/home/] 的 HTTP 请求的映射DispatcherServlet 名称为 'dispatcher' 2015 年 2 月 14 日 11:35:32.766 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory 部署 Web 应用程序目录 /home/nikolay/apache-tomcat-8.0.9/webapps/manager 14-Feb-2015 11:35:32.904 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory 部署 Web 应用程序目录 /home/nikolay/apache-tomcat-8.0.9/webapps/manager已在 136 毫秒内完成 2015 年 2 月 14 日 11:35:34.888 警告 [http-nio-8080-exec-3] org.springframework.web.servlet.PageNotFound.noHandlerFound 在 DispatcherServlet 中找不到带有 URI [/home/] 的 HTTP 请求的映射,名称为'调度员'
【问题讨论】:
标签: java spring-mvc spring-java-config tomcat8