基于Java的Spring DispatcherServlet配置

时间:2018-02-26 16:39:08

标签: java spring tomcat

我有一项任务是让我的JAR应用程序成为Spring MVC应用程序。我安装了Tomcat 9.0.5并继续配置spring。对于我的示例测试应用程序,我决定使用DispatcherServlet的100%Java配置,而不是按照此处的说明使用web.xml:https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#mvc-servlet但我无法使其正常工作。

我使用IntelliJ创建了一个项目。它下载了spring jar并创建了一个类似的目录结构:

tomcattest
|-.idea
|-lib
|-out
|-src
|-web
||-index.jsp
|-tomcattest.iml

我在Tomcat下运行这个空应用程序,并且已经加载了index.jsp。

然后我创建了MyWebApplicationInitializer

package pl.mesayah.tomcattest;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {


    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{AppConfig.class};
    }

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

AppConfig

package pl.mesayah.tomcattest;

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

@Configuration
@ComponentScan("pl.mesayah.tomcattest")
@EnableAspectJAutoProxy
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {

}

示例@RestController

package pl.mesayah.tomcattest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test")
    public String test() {
        return "test";
    }
}

但我无法使其发挥作用。在部署到Tomcat后,我仍然可以看到index.jsp页面,但转到http://localhost:8080/test会出现404错误页面和它的Tomcat 404,而不是Spring。所以我认为DispatcherServlet根本不起作用,但我不知道该怎么做。我正在关注上面链接中的官方Spring文档。

请告诉我我的代码中缺少的内容。

0 个答案:

没有答案