簡體   English   中英

Spring MVC Java配置

[英]Spring MVC Java config

我想從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));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM