对于一个任务,我正在练习Java的Spring MVC以创建一个Web应用程序。我已经在IDE Intellij Ultimate 2016.2.5中构建了整个项目。由于路由无效,弹簧路由获取404错误
我为此创建了一个Maven项目,为此导入了正确的和问题的依赖关系并构建它。
IDE将构建以下的目录结构:
├───src
│ └───bas
│ └───animalkingdom
│ ├───config
│ ├───controllers
├───test
│ └───bas
│ └───animalkingdom
└───web
├───META-INF
├───resources
└───WEB-INF
└───pages
的config
包是我的配置类,从WebMvcConfigurerAdapter延伸:
包bas.animalkingdom.config;
import ...
@Configuration
@ComponentScan("bas.animalkingdom")
@EnableWebMvc
public class Config extends WebMvcConfigurerAdapter {
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
我以为@ComponentScan
必须指向所有源文件所在的主要源代码目录。
有人告诉我,我还需要一个从WebApplicationInitializer
延伸的类。我从我的学校得到这一个
package bas.animalkingdom.config;
import ...
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(Config.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
这一个也在config
包。
Config类在IDE中的项目结构设置中设置为Spring Application Context
。
在根目录下是web
文件夹。在文件夹WEB-INF
是一个空的web.xml
文件,我被告知我不需要,因为设置将通过配置类加载。它看起来像这样:
<web-app id="WebApp_ID" version="2.4"
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">
</web-app>
在web
文件夹的根目录下有一个index.jsp
文件。
在bas.animalkingdom.controllers
包是我的控制器。为了测试用途变更,我只创建了一个:
package bas.animalkingdom.controllers;
import ...
@Controller("AnimalC")
public class AnimalController {
@RequestMapping(value = "/animals", method = RequestMethod.GET)
public String getAnimals(ModelMap modelMap) {
Animal animal = new AfricanElephant(new Male(), "Body Covering", "Ename", " acolor", 123, 321);
modelMap.put("animal", animal);
return "animals";
}
}
有了这个控制器我的预期,我可以去localhost/animals
URL,并且它会加载了animals.jsp
文件位于我web\WEB-INF\pages\
包。
我的代码没有编译错误。
当我运行我的TomCat服务器,并打开我的浏览器去与相应的主机本地主机,index.jsp文件只是加载没有问题。该文件位于web\
包中。
当我转到localhost:(port)/animals
时,我刚刚收到一个404页面,并显示无法找到该页面的消息。
这是什么造成的?我已经定义了控制器设置该路线的权利?
另外,查找其他Spring MVC教程时,它们都使用不同的包装,这是否也适用?
对于初学者删除您'web.xml'你不需要它,它目前防止'WebInitializer'从做其工作。 –
你不需要在控制器中返回'pages/animals'吗? –
@OlarAndrei为什么呢? – Bas