spring4 java替代web.xml配置 20C

SpringWebAppInitializer.java

public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    // 指定配置类,即javaConfig
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

RootConfig.java

 @Configuration
@ComponentScan(basePackages = { "cn.simfg.note.web" }, excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfig {

}

WebConfig.java

 @Configuration
//启用注解驱动的spring mvc
@EnableWebMvc
@ComponentScan(basePackages = {"cn.simfg.note.web.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();

        internalResourceViewResolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
        internalResourceViewResolver.setPrefix("/WEB-INF/views/");
        internalResourceViewResolver.setSuffix(".jsp");
        internalResourceViewResolver.setExposeContextBeansAsAttributes(true);

        return internalResourceViewResolver;
    }

    // 处理静态资源的时候,将请求转发到Servlet容器中默认的Servlet上

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
        super.configureDefaultServletHandling(configurer);
    }

}

HomeController.java

 @Controller
public class HomeController {

    @RequestMapping(value = "home", method = GET)
    public String home() {
        System.out.println("aaa");
        return "home";
    }
}

请求localhost:8080/spring/home返回404,其中localhost:8080/spring/是项目根路径,home.jsp也是存在的,在控制器那一块打断电,请求是无效

1个回答

这些类的代码都没有问题,可能有问题的是它们的所在的包和jsp的存放位置与你配置中的是否一致。
cn.simfg.note.web.controller包对应对了吗?jsp放到这个目录了吗?/WEB-INF/views

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!