2016-03-13 105 views
0

最近我正在学习基于spring java的配置。我试图用WebConfig替换web.xml WebApplicationInitializerSpring WebApplicationInitializer

每当我要求的网址:http://localhost:8080/spring-demo/greeting.html我得到404说明请求的资源不可用。 以下是我的项目详情。

WebConfig.java

package com.soumya.spring; 

import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = "com.soumya.spring") 
public class WebConfig { 

} 

WebAppInitializer.java

​​

控制器

package com.soumya.spring.controller; 

import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMapping; 

@Controller 
public class HelloController { 

    @RequestMapping(value = "/greeting") 
    public String greeting(Model model) { 
     model.addAttribute("greeting", "Hello World!"); 
     return "greeting.jsp"; 
    } 

} 

项目结构图片

Project Structure

+0

看看你的配置,我会说使用正确的URL是http:// localhost:8080/spring-demo/greeting 删除最后的.html –

+0

你使用的是什么版本的servlet api?它必须比(包括)3.0.0更新。记录什么?通常您可以在启动时看到请求映射。 – hotzst

+0

@soumya,你可以请你发布你的日志文件? –

回答

0

带注释的初始化示例。

public class Initializer implements WebApplicationInitializer { 
    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     // Creates context object 
     AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); 

     // Registers annotated configurations class 
     ctx.register(Configurations.class); 

     // Sets ContextLoaderListener to servletContext 
     servletContext.addListener(new ContextLoaderListener(ctx)); 

     // Passes servlet context to context instance 
     ctx.setServletContext(servletContext); 

     //Registers dispatch servlet and passes context instance 
     ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); 

     //Maps URL pattern 
     servlet.addMapping("/"); 

     //Sets creation priority 
     servlet.setLoadOnStartup(1); 

     //Registers security filters 
     FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); 

     // Sets dispatcher types a security filters to be applied 
     EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD); 
     security.addMappingForUrlPatterns(dispatcherTypes, true, "/*"); 
    } 
} 
0

如果你正在使用Spring MVC的最新版本,请在下面

from context.setConfigLocation("com.soumya.spring.WebConfig"); 

到context.register(WebConfig.class)取代configlocation。它应该工作。

相关问题