ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-为什么我收到此错误,未找到带有URI的HTTP请求的映射

2019-11-08 12:04:10  阅读:141  来源: 互联网

标签:spring-boot spring java


我试图将我的spring mvc项目转换为spring boot.我根据春季启动转换了所有必需的文件.控制台上没有错误.但是,当我在浏览器中运行我的Web应用程序时,出现此错误.

在名称为’dispatcherServlet’的DispatcherServlet中找不到带有URI [/onlineshopping/WEB-INF/views/page.jsp]的HTTP请求的映射

我尝试运行任何URL都会收到相同的错误,为什么?

OnlineshoppingApplication.java

    package net.kzn.onlineshopping;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@SpringBootApplication
@EnableWebSecurity
@ImportResource({ "classpath:/**/spring-security.xml" })
@ComponentScan(basePackages = { "net.kzn.onlineshopping.*", "net.kzn.shoppingbackend.*" })

public class OnlineshoppingApplication {

    public static void main(String[] args) {
        SpringApplication.run(OnlineshoppingApplication.class, args);
    }
}

控制台日志文件链接

https://www.dropbox.com/s/6pk0bq2xn1jzmqr/error.txt?dl=0

AppConfig.java

    package net.kzn.onlineshopping.config;

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.context.support.ResourceBundleThemeSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.theme.CookieThemeResolver;
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.webflow.config.AbstractFlowConfiguration;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.executor.FlowExecutor;
import org.springframework.webflow.mvc.builder.MvcViewFactoryCreator;
import org.springframework.webflow.mvc.servlet.FlowHandlerMapping;

@Configuration
@EnableWebMvc
@ComponentScan("net.kzn.onlineshopping")
public class AppConfig extends AbstractFlowConfiguration implements WebMvcConfigurer {

       @Autowired
        private AppConfig AppConfig;


    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    /** View resolver for JSP */
    @Bean
    public ViewResolver getViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    /** Multipart file uploading configuratioin */
    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(100000);
        return multipartResolver;
    }


    /** Static resource locations including themes*/
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/assets/");
    }

    /** BEGIN theme configuration */
    @Bean
    public ResourceBundleThemeSource themeSource(){
        ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
        themeSource.setDefaultEncoding("UTF-8");
        themeSource.setBasenamePrefix("themes.");
        return themeSource;
    }

    @Bean
    public CookieThemeResolver themeResolver(){
        CookieThemeResolver resolver = new CookieThemeResolver();
        resolver.setDefaultThemeName("default");
        resolver.setCookieName("example-theme-cookie");
        return resolver;
    }

    @Bean
    public ThemeChangeInterceptor themeChangeInterceptor(){
        ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor();
        interceptor.setParamName("theme");
        return interceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(themeChangeInterceptor());
    }
    /** END theme configuration */

    @Bean
    public FlowDefinitionRegistry flowRegistry() {
        return getFlowDefinitionRegistryBuilder()
                .setBasePath("/WEB-INF/views/flows")
                .addFlowLocationPattern("/**/*-flow.xml")
                .build();
        }

    @Bean
    public FlowExecutor flowExecutor() {
        return getFlowExecutorBuilder(flowRegistry()).build();
    }

    @Bean
    public FlowBuilderServices flowBuilderServices() {
        return getFlowBuilderServicesBuilder().setViewFactoryCreator(mvcViewFactoryCreator()).setDevelopmentMode(true).build();
    }

    @Bean
    public FlowHandlerMapping flowHandlerMapping() {
        FlowHandlerMapping handlerMapping = new FlowHandlerMapping();
        handlerMapping.setOrder(-1);
        handlerMapping.setFlowRegistry(this.AppConfig.flowRegistry());
        return handlerMapping;
    }

    @Bean
    public MvcViewFactoryCreator mvcViewFactoryCreator() {
        MvcViewFactoryCreator factoryCreator = new MvcViewFactoryCreator();
        factoryCreator.setViewResolvers(Collections.singletonList(this.AppConfig.getViewResolver()));
        factoryCreator.setUseSpringBeanBinding(true);
        return factoryCreator;
    }

}

WebAppInitializer.java

    package net.kzn.onlineshopping.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);
        context.setServletContext(container);

        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

application.properties

    server.port=8081
logging.path=/home/vidyesh/Downloads
server.servlet.context-path=/onlineshopping

pom.xml

        <?xml version="1.0" encoding="UTF-8"?>
    <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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>net.kzn</groupId>
        <artifactId>shoppingbackend</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>

        <name>shoppingbackend</name>
        <description>Demo project for Spring Boot</description>

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.17.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>

        <dependencies>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-rest-hal-browser</artifactId>
            </dependency>

            <!-- https://mvnrepository.com/artifact/org.springframework.webflow/spring-webflow -->
            <dependency>
                <groupId>org.springframework.webflow</groupId>
                <artifactId>spring-webflow</artifactId>
                <version>2.5.1.RELEASE</version>
            </dependency>
            <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.2.2</version>
            </dependency>


            <!-- Hibernate Dependency -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.2.7.Final</version>
            </dependency>

            <!-- database connection pooling -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-dbcp2</artifactId>
                <version>2.1.1</version>
                <exclusions>
                    <exclusion>
                        <groupId>commons-logging</groupId>
                        <artifactId>commons-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <scope>runtime</scope>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>

          <resources>
            <resource>
              <directory>src/main/webapp</directory>
            </resource>
          </resources>
        </build>
    </project>

PageController.java

        package net.kzn.onlineshopping.controller;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;

    import net.kzn.onlineshopping.exception.ProductNotFoundException;
    import net.kzn.shoppingbackend.dao.CategoryDAO;
    import net.kzn.shoppingbackend.dao.ProductDAO;
    import net.kzn.shoppingbackend.dto.Category;
    import net.kzn.shoppingbackend.dto.Product;

    @Controller
    public class PageController {

        private static final Logger logger = LoggerFactory.getLogger(PageController.class);

        @Autowired
        private CategoryDAO categoryDAO;

        @Autowired
        private ProductDAO productDAO;

        @RequestMapping(value = { "/", "/home", "/index" })
        public ModelAndView index(@RequestParam(name = "logout", required = false) String logout) {
            ModelAndView mv = new ModelAndView("page");
            mv.addObject("title", "Home");

            logger.info("Inside PageController index method - INFO");
            logger.debug("Inside PageController index method - DEBUG");

            // passing the list of categories
            mv.addObject("categories", categoryDAO.list());

            if (logout != null) {
                mv.addObject("message", "You have successfully logged out!");
            }

            mv.addObject("userClickHome", true);
            return mv;
        }

        @RequestMapping(value = "/about")
        public ModelAndView about() {
            ModelAndView mv = new ModelAndView("page");
            mv.addObject("title", "About Us");
            mv.addObject("userClickAbout", true);
            return mv;
        }

        @RequestMapping(value = "/contact")
        public ModelAndView contact() {
            ModelAndView mv = new ModelAndView("page");
            mv.addObject("title", "Contact Us");
            mv.addObject("userClickContact", true);
            return mv;
        }

        /*
         * Methods to load all the products and based on category
         */

        @RequestMapping(value = "/show/all/products")
        public ModelAndView showAllProducts() {
            ModelAndView mv = new ModelAndView("page");
            mv.addObject("title", "All Products");

            // passing the list of categories
            mv.addObject("categories", categoryDAO.list());

            mv.addObject("userClickAllProducts", true);
            return mv;
        }

        @RequestMapping(value = "/show/category/{id}/products")
        public ModelAndView showCategoryProducts(@PathVariable("id") int id) {
            ModelAndView mv = new ModelAndView("page");

            // categoryDAO to fetch a single category
            Category category = null;

            category = categoryDAO.get(id);

            mv.addObject("title", category.getName());

            // passing the list of categories
            mv.addObject("categories", categoryDAO.list());

            // passing the single category object
            mv.addObject("category", category);

            mv.addObject("userClickCategoryProducts", true);
            return mv;
        }

        /*
         * Viewing a single product
         */

        @RequestMapping(value = "/show/{id}/product")
        public ModelAndView showSingleProduct(@PathVariable int id) throws ProductNotFoundException {

            ModelAndView mv = new ModelAndView("page");

            Product product = productDAO.get(id);

            if (product == null)
                throw new ProductNotFoundException();

            // update the view count
            product.setViews(product.getViews() + 1);
            productDAO.update(product);
            // ---------------------------

            mv.addObject("title", product.getName());
            mv.addObject("product", product);

            mv.addObject("userClickShowProduct", true);

            return mv;

        }

        @RequestMapping(value = "/membership")
        public ModelAndView register() {
            ModelAndView mv = new ModelAndView("page");

            logger.info("Page Controller membership called!");

            return mv;
        }

        @RequestMapping(value = "/login")
        public ModelAndView login(@RequestParam(name = "error", required = false) String error,
                @RequestParam(name = "logout", required = false) String logout) {
            ModelAndView mv = new ModelAndView("login");
            mv.addObject("title", "Login");
            if (error != null) {
                mv.addObject("message", "Username and Password is invalid!");
            }
            if (logout != null) {
                mv.addObject("logout", "You have logged out successfully!");
            }
            return mv;
        }

        @RequestMapping(value = "/logout")
        public String logout(HttpServletRequest request, HttpServletResponse response) {
            // Invalidates HTTP Session, then unbinds any objects bound to it.
            // Removes the authentication from securitycontext
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null) {
                new SecurityContextLogoutHandler().logout(request, response, auth);
            }

            return "redirect:/login?logout";
        }

        @RequestMapping(value = "/access-denied")
        public ModelAndView accessDenied() {
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("errorTitle", "Aha! Caught You.");
            mv.addObject("errorDescription", "You are not authorized to view this page!");
            mv.addObject("title", "403 Access Denied");
            return mv;
        }

        @RequestMapping(value = "/view/category/{id}/products")
        public ModelAndView viewProducts(@PathVariable("id") int id) {
            ModelAndView mv = new ModelAndView("page");
            // categoryDAO to fetch a single category
            Category category = null;

            category = categoryDAO.get(id);

            mv.addObject("title", category.getName());

            // passing the list of categories
            mv.addObject("viewproducts", productDAO.listActiveProductsByCategory(id));

            mv.addObject("userClickViewProducts", true);
            return mv;
        }


        @RequestMapping(value = "/search")
        public ModelAndView Search(@RequestParam(value = "searchTerm", required = false) String pSearchTerm,
                HttpServletRequest request, HttpServletResponse response) {
            ModelAndView mv = new ModelAndView("search");

            mv.addObject("searchTerm", pSearchTerm);
            mv.addObject("searchResult", productDAO.searchProductsByParam(pSearchTerm));

            mv.addObject("userClickSearch", true);

            return mv;
        }

    }

文件结构
enter image description here
enter image description here
enter image description here

请告诉我我在做什么错?

解决方法:

添加此配置后我的问题解决了

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

添加此配置后,白页错误停止,但jsp页代码开始显示为html,因此添加了这两个依赖关系.

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>

此链接有帮助

JSP file not rendering in Spring Boot web application

标签:spring-boot,spring,java
来源: https://codeday.me/bug/20191108/2007701.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有