简体   繁体   English

Java配置中的Spring MVC在访问jsp时获取404

[英]Spring MVC in java config get a 404 when access jsp

I created a simple spring mvc demo in java config, but I got a 404 when I try to access a home.jsp . 我在java config中创建了一个简单的spring mvc演示,但是当我尝试访问home.jsp时却得到了404。 Below is the code: 下面是代码:

在此处输入图片说明

build.gradle

ext {
    // spring
    springVersion = '5.0.7.RELEASE'
    // servlet+jsp
    servletVersion = '3.1.0'
    jspApiVersion = '2.3.1'
    // test
    junitVersion = '4.12'
    // log
    slf4jVersion = "1.7.25"
    logbackVersion = "1.2.3"
    logbackExtVersion = "0.1.4"
}

group = 'com.springmvc'
version = '1.0.0'

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'idea'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    maven {
        url = 'http://maven.aliyun.com/nexus/content/groups/public/'
    }
}

idea {
    module {
        downloadJavadoc = true
        // download source
        downloadSources = true
    }
}

dependencies {
    providedCompile(
        "javax.servlet:javax.servlet-api:${servletVersion}",
        "javax.servlet.jsp:javax.servlet.jsp-api:${jspApiVersion}"
    )
    compile(
        // spring
        "org.springframework:spring-core:${springVersion}",
        "org.springframework:spring-webmvc:${springVersion}",
        // log
        "org.slf4j:slf4j-api:${slf4jVersion}",
        "ch.qos.logback:logback-core:${logbackVersion}",
        "ch.qos.logback:logback-classic:${logbackVersion}",
        "org.logback-extensions:logback-ext-spring:${logbackExtVersion}"
    )
    testCompile("junit:junit:${junitVersion}")
}

WebAppInitializer.java

package com.springmvc.config;

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

public class WebAppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * Specify {@code @Configuration} and/or {@code @Component} classes for the
     * {@linkplain #createRootApplicationContext() root application context}.
     *
     * @return the configuration for the root application context, or {@code null}
     * if creation and registration of a root context is not desired
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

    /**
     * Specify {@code @Configuration} and/or {@code @Component} classes for the
     * {@linkplain #createServletApplicationContext() Servlet application context}.
     *
     * @return the configuration for the Servlet application context, or
     * {@code null} if all configuration is specified through root config classes.
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    /**
     * Specify the servlet mapping(s) for the {@code DispatcherServlet} &mdash;
     * for example {@code "/"}, {@code "/app"}, etc.
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

RootConfig.java

package com.springmvc.config;

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

@Configuration
@ComponentScan(
    basePackages = "com.springmvc",
    excludeFilters = {
        @ComponentScan.Filter(
            type = FilterType.ANNOTATION,
            value = EnableWebMvc.class),
        @ComponentScan.Filter(
            type = FilterType.ANNOTATION,
            value = Controller.class
        )
    })
public class RootConfig {
}

WebConfig.java

package com.springmvc.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@ComponentScan("com.springmvc.web")
public class WebConfig implements WebMvcConfigurer {

    /**
     * Configure simple automated controllers pre-configured with the response
     * status code and/or a view to render the response body. This is useful in
     * cases where there is no need for custom controller logic -- e.g. render a
     * home page, perform simple site URL redirects, return a 404 status with
     * HTML content, a 204 with no content, and more.
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("home");
    }

    /**
     * Configure view resolvers to translate String-based view names returned from
     * controllers into concrete {@link View}
     * implementations to perform rendering with.
     *
     * @since 4.1
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/views/", ".jsp");
    }
}

and the simple jsp: 和简单的jsp:

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>SpringMvcDemo</title>
</head>
<body>
    Hello Spring MVC 5!
</body>
</html>

here are some logs: 这是一些日志:

23:16:18.038 [http-nio-7070-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/]
23:16:18.042 [http-nio-7070-exec-2] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /
23:16:18.042 [http-nio-7070-exec-2] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Did not find handler method for [/]
23:16:18.043 [http-nio-7070-exec-2] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapping [/] to HandlerExecutionChain with handler [org.springframework.web.servlet.mvc.ParameterizableViewController@784f4a1a] and 1 interceptor
23:16:18.044 [http-nio-7070-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/] is: -1
23:16:18.051 [http-nio-7070-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.InternalResourceView: name 'home'; URL [/views/home.jsp]] in DispatcherServlet with name 'dispatcher'
23:16:18.052 [http-nio-7070-exec-2] DEBUG org.springframework.web.servlet.view.InternalResourceView - Forwarding to resource [/views/home.jsp] in InternalResourceView 'home'
23:16:18.053 [http-nio-7070-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request

I thought everything was done, and I start the tomcat, typed: 我以为一切都做完了,然后我启动了tomcat,输入:

http://localhost:7070/

BUT then, I got a 404 :( 后来,我得到了404 :( 在此处输入图片说明

(I had also tried http://localhost:7070/SpringMvcDemo , but it didn't help..) (我也尝试过http://localhost:7070/SpringMvcDemo ,但是没有帮助。)

I couldn't figure out why..so please anyone who can tell me why this happen? 我不知道为什么。所以请有人告诉我为什么会这样吗?

Create a UrlBasedViewResolver bean in your WebConfig class. WebConfig类中创建一个UrlBasedViewResolver bean。

@Bean
    public UrlBasedViewResolver setupViewResolver() {

        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

You can extend your WebConfig from WebMvcConfigurerAdapter . 您可以从WebMvcConfigurerAdapter扩展WebConfig WebMvcConfigurerAdapter is implementation of WebMvcConfigurer interface WebMvcConfigurerAdapter是WebMvcConfigurer接口的实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM