You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义AbstractAnnotationConfigDispatcherServletInitializer无法注册问题咨询

Hey there! Let's break down and fix your Spring MVC setup issues with embedded Tomcat step by step.

First: Why AbstractAnnotationConfigDispatcherServletInitializer isn't working

The AbstractAnnotationConfigDispatcherServletInitializer is built for traditional WAR deployments, where the Servlet container (like Tomcat) automatically scans for ServletContainerInitializer implementations on startup. But when you're using an embedded Tomcat instance, you're manually bootstrapping the server yourself—so that auto-scanning doesn't kick in automatically. We need to register the DispatcherServlet explicitly instead.

Step 1: Set up your core Spring configuration

Create a @Configuration class that enables Spring MVC and configures the JSP view resolver to target your desired directory:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.yourpackage") // Replace with your actual project package
public class WebConfig implements WebMvcConfigurer {

    // Configure view resolver to look in /WEB-INF/views with .jsp suffix
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class); // Include if using JSTL tags
        return resolver;
    }
}

Step 2: Bootstrap embedded Tomcat and register DispatcherServlet

Instead of relying on the initializer, we'll manually create a Tomcat instance, wire up our Spring context, and register the DispatcherServlet. Create a main launcher class:

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import java.io.File;

public class EmbeddedTomcatLauncher {

    public static void main(String[] args) throws LifecycleException {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080); // Set your preferred port

        // Create a temp directory for Tomcat's working files
        File baseDir = new File(System.getProperty("java.io.tmpdir"));
        tomcat.setBaseDir(baseDir.getAbsolutePath());

        // Initialize Spring's web application context
        AnnotationConfigWebApplicationContext springContext = new AnnotationConfigWebApplicationContext();
        springContext.register(WebConfig.class);

        // Create and register DispatcherServlet with the Spring context
        DispatcherServlet dispatcherServlet = new DispatcherServlet(springContext);
        Context tomcatContext = tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath()); // Root context path

        // Attach the servlet to Tomcat and map all requests to it
        Tomcat.addServlet(tomcatContext, "dispatcherServlet", dispatcherServlet);
        tomcatContext.addServletMappingDecoded("/*", "dispatcherServlet");

        // Start the server
        tomcat.start();
        tomcat.getServer().await();
    }
}

Step 3: Add a sample controller and JSP view

Create a simple controller to test the setup:

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

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello from Spring MVC + Embedded Tomcat!");
        return "home"; // Maps to /WEB-INF/views/home.jsp
    }
}

Then create src/main/webapp/WEB-INF/views/home.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>

Step 4: Add required dependencies (Maven example)

Ensure your pom.xml includes these dependencies for embedded Tomcat, Spring MVC, and JSP support:

<dependencies>
    <!-- Spring MVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>6.0.11</version> <!-- Use the latest compatible version -->
    </dependency>

    <!-- Embedded Tomcat Core -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-core</artifactId>
        <version>10.1.12</version> <!-- Match Spring version compatibility -->
    </dependency>
    <!-- Embedded Tomcat JSP Support -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <version>10.1.12</version>
    </dependency>
    <!-- JSTL for JSP tag support -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

Step 5: Test your application

Run the EmbeddedTomcatLauncher main class, then navigate to http://localhost:8080 in your browser. You should see your JSP page with the test message displayed.

Extra customization tips

  • To change the application context path: Modify the first parameter of tomcat.addWebapp() (e.g., "/my-app" instead of "")
  • To add custom Spring beans: Define them in WebConfig with @Bean or use @Component annotations in your scanned package
  • To configure static assets (CSS/JS/images): Override addResourceHandlers in WebConfig to map resource paths to your static directory

内容的提问来源于stack exchange,提问作者Javier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:20:21