Jetty + SpringMVC:设置 configureDefaultServletHandling 时出错,因为找不到默认的 servlet 名称

Jetty + SpringMVC: Error when set configureDefaultServletHandling because cannot find the default servlet name

我创建了一个没有 web.xml 和 spring-servlet.xml 配置文件的简单应用程序。我只是在 Java 代码中配置。 这是项目结构:

Project structure

这是我的主class:

public class TripMapServer {

private static final int DEFAULT_PORT = 8080;
private static final String CONTEXT_PATH = "/";
private static final String MAPPING_URL = "/";
private static final String CONFIG_LOCATION = "com.biendltb.config";
private static final String DEFAULT_PROFILE = "dev";

public static void main(String[] args) throws Exception {
    new TripMapServer().startJetty(getPortFromArgs(args));
}

private static int getPortFromArgs(String[] args) {
    if (args.length > 0) {
        try {
            return Integer.valueOf(args[0]);
        } catch (NumberFormatException ignore) {
        }
    }
    return DEFAULT_PORT;
}

private void startJetty(int port) throws Exception {
    Server server = new Server(port);
    server.setHandler(getServletContextHandler(getContext()));
    server.start();
    server.join();
}

private static ServletContextHandler getServletContextHandler(WebApplicationContext context) throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setErrorHandler(null);
    contextHandler.setContextPath(CONTEXT_PATH);
    contextHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), MAPPING_URL);
    contextHandler.addEventListener(new ContextLoaderListener(context));
    contextHandler.setResourceBase(new ClassPathResource("webapp").getURI().toString());
    return contextHandler;
}

private static WebApplicationContext getContext() {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.setConfigLocation(CONFIG_LOCATION);
    context.getEnvironment().setDefaultProfiles(DEFAULT_PROFILE);
    return context;
 }
}

我创建了另一个名为 WebConfig.java 的 class 来设置 spring-servlet 的配置:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.biendltb.controller"})
public class WebConfig extends WebMvcConfigurerAdapter{ 

private static final Charset UTF8 = Charset.forName("UTF-8");

@Autowired
public Environment env;

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(stringConverter());
}

private StringHttpMessageConverter stringConverter() {
    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
    stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
    return stringConverter;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/src/main/resources/").setCachePeriod(Integer.MAX_VALUE);
    registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(Integer.MAX_VALUE);
    registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(Integer.MAX_VALUE);
    registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(Integer.MAX_VALUE);
}

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

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/src/main/resources/pages/");
    resolver.setSuffix(".jsp");
    return resolver;
 }
}

添加configureDefaultServletHandling函数时发生错误。

[org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: Unable to locate the default servlet for serving static content. Please set the 'defaultServletName' property explicitly.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: Unable to locate the default servlet for serving static content. Please set the 'defaultServletName' property explicitly.

找不到servlet 的默认名称。通常,servlet 的默认名称将是 "default".

我想也许我应该设置 servlet 名称来解决这个问题。

你有解决这个问题的办法吗?

抱歉代码格式显示不正确。感谢您的支持。非常感谢。

我已经找到如何通过 java 代码为 Spring servlet 设置名称:

contextHandler.addServlet(new ServletHolder("default", new DispatcherServlet(context)), MAPPING_URL);

但是我又遇到了一个问题,那就是:

java.lang.NoClassDefFoundError: Could not initialize class org.springframework.web.util.NestedServletException

我尝试 google,许多人遇到 NoClassDefFoundError 但没有人遇到问题 org.springframework.web.util.NestedServletException .

我再次检查以确保添加了所有依赖项。

也许我应该 post 关于那个问题的另一个问题 :(