当前位置: 首页 > 面试题库 >

Spring MVC Java配置

孟晨朗
2023-03-14
问题内容

我想从spring webapp设置一个简单的响应主体。我的问题很简单,就是出现网络错误。

我的POM.xml是:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>pt.dummy</groupId>
    <artifactId>dummy</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>dummy Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring-framework.version>3.2.3.RELEASE</spring-framework.version>
        <tomcat.servlet.version>7.0.42</tomcat.servlet.version>
        <log4j.version>1.7.5</log4j.version>
        <java.version>1.7</java.version>
        <junit.version>4.11</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>${tomcat.servlet.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-logging-juli</artifactId>
            <version>${tomcat.servlet.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>${tomcat.servlet.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.eclipse.jdt.core.compiler</groupId>
                    <artifactId>ecj</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-framework.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-framework.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>dummy</finalName>
        <testResources>
          <testResource>
            <!-- declared explicitly so Spring config files can be placed next to their corresponding JUnit test class 
                (see example with ValidatorTests) -->
            <directory>${project.basedir}/src/test/java</directory>
          </testResource>
          <testResource>
            <directory>${project.basedir}/src/test/resources</directory>
          </testResource>
        </testResources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

我的网络初始化器是:

package dummy.web.config;

import javax.servlet.Filter;

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

public class WebAppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

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

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

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

      @Override
      protected Filter[] getServletFilters() {

        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        return new Filter[] { characterEncodingFilter};
      }

}

核心配置:

package dummy.web.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class CoreConfig {

}

网络配置:

package dummy.web.config;

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

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"dummy.web.controller"})
public class WebConfig {

}

站点控制器:

package dummy.web.controller;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class SiteController {

//  private static final Logger LOG = LoggerFactory.getLogger(SiteController.class);

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public String getHome() {
//        LOG.debug("Home to ResponseBody");
        return "Response Body";
    }
}

谁能指出要进行此项工作所需添加的更改?


问题答案:

我相信是因为Tomcat。网络上的大多数教程都将spring mvc servlet直接放在应用程序上下文中。它从来没有为我工作。

在Tomcat7(甚至具有XML配置)上,您必须创建两个上下文:一个用于整个应用程序,一个用于spring web mvc。它与…有关

@RequestMapping("/")

服务器将“ /”映射分配给默认的内置servlet。您希望他(或他或她)做这件事。但是,您还需要Spring MVC来映射“ /”。

也许他们(建筑师)认为springmvc是特定的servlet,并且不应该映射根contex。相反,它应该在自己的映射下(例如“ / springmvc
/”)。然后,它期望我们有一个真正的调度程序,可以在springmvc和其他任何servlet之间进行调度。

出于某种神奇的原因,在Tomcat 7.0.29中,如果您试图劫持“ /”,则甚至无法“调度”。在最新版本上,映射“
/”起作用。但是为此,您需要一个单独的Web MVC上下文/根上下文。

我不使用AbstractAnnotationConfigDispatcherServletInitializer,而必须翻译下面的代码。这是从本教程(从XML到Javaconfig的迁移)改编而成的。spring
-app-migration-from-xml-to-java-based-
config

public class WebInit implements WebApplicationInitializer {

    private static final String DISPATCHER_SERVLET_NAME = "spring-mvc";
    private static final String DISPATCHER_SERVLET_MAPPING = "/";

    @Override
    public void onStartup(ServletContext servletContext)
            throws ServletException {

        //If you want to use the XML configuration, comment the following two lines out.
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
        appContext.register(CoreConfig.class);
        appContext.setDisplayName("removed customer name");

        //If you want to use the XML configuration, uncomment the following lines.
        //XmlWebApplicationContext rootContext = new XmlWebApplicationContext();
        //rootContext.setConfigLocation("classpath:mvc-servlet.xml");

        AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
        mvcContext.register(ServletConfig.class);

        ServletRegistration.Dynamic springmvc =
                servletContext.addServlet(DISPATCHER_SERVLET_NAME,
                          new DispatcherServlet(mvcContext));
        springmvc.setLoadOnStartup(1);
        springmvc.addMapping(DISPATCHER_SERVLET_MAPPING);

        EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);

        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", characterEncodingFilter);
        characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");

        FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
        security.addMappingForUrlPatterns(dispatcherTypes, true, "/*");

        servletContext.addListener(new ContextLoaderListener(appContext));
    }


 类似资料:
  • exVim 的配色由三部分组成: 你自己的Vim配色, exVim 插件的语法高亮和插件的配色. 你可以按照以下步骤来定制你的配色: 安装你的配色 exVim 提供了三种方法安装你的自定义配色 方法1. 在 ex-colorscheme 中安装(推荐) 首选的方法是在 ex-colorschemes 中安装自己的配色, 这种方法仅仅需要你把自己的配色文件放到 vimfiles/bundle/ex-

  • 目录: 在配置项目yml文件中: 问题: null 客户端YML: 有没有人知道我怎样才能在这两种情况下只带一个配置文件?

  • 丰富的过滤器插件的存在是 logstash 威力如此强大的重要因素。名为过滤器,其实提供的不单单是过滤的功能。在本章我们就会重点介绍几个插件,它们扩展了进入过滤器的原始数据,进行复杂的逻辑处理,甚至可以无中生有的添加新的 logstash 事件到后续的流程中去!

  • Codec 是 logstash 从 1.3.0 版开始新引入的概念(Codec 来自 Coder/decoder 两个单词的首字母缩写)。 在此之前,logstash 只支持纯文本形式输入,然后以过滤器处理它。但现在,我们可以在输入 期处理不同类型的数据,这全是因为有了 codec 设置。 所以,这里需要纠正之前的一个概念。Logstash 不只是一个input | filter | outpu

  • 在 “Hello World” 示例中,我们已经见到并介绍了 logstash 的运行流程和配置的基础语法。从这章开始,我们就要逐一介绍 logstash 流程中比较常用的一些插件,并在介绍中针对其主要适用的场景,推荐的配置,作一些说明。 限于篇幅,接下来内容中,配置示例不一定能贴完整。请记住一个原则:Logstash 配置一定要有一个 input 和一个 output。在演示过程中,如果没有写明

  • 根据文档--不管应用程序名称如何,如果模式与*/development(即localhost:8888/user/development或localhost:8888/demo/development)匹配,配置服务器应该匹配配置文件模式并获取适当的属性。例如:http://localhost:8888/demo/development我应该从ssh://git@xxxgithub.com/dev