为什么我收到此错误未找到带有 URI 的 HTTP 请求的映射 [英] why im getting this error No mapping found for HTTP request with URI

查看:57
本文介绍了为什么我收到此错误未找到带有 URI 的 HTTP 请求的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的 spring mvc 项目转换为 spring boot.我根据 spring boot 转换了所有必要的文件.控制台上没有错误.但是当我在浏览器中运行我的网络应用程序时,我收到了这个错误.

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

我尝试运行的任何 url 为什么都会出现相同的错误?

OnlineshoppingApplication.java

 包 net.kzn.onlineshopping;导入 org.springframework.boot.SpringApplication;导入 org.springframework.boot.autoconfigure.SpringBootApplication;导入 org.springframework.context.annotation.ComponentScan;导入 org.springframework.context.annotation.ImportResource;导入 org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;@SpringBootApplication@启用网络安全@ImportResource({ "classpath:/**/spring-security.xml" })@ComponentScan(basePackages = { "net.kzn.onlineshopping.*", "net.kzn.shoppingbackend.*" })公共类网上购物应用程序{公共静态无效主(字符串 [] args){SpringApplication.run(OnlineshoppingApplication.class, args);}}

控制台日志文件链接

请告诉我我在这里做错了什么?

解决方案

我添加这个配置后问题解决了

@Overridepublic void configureDefaultServletHandling(DefaultServletHandlerConfigurer 配置器) {配置器.启用();}

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

<依赖><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><范围>提供</范围>

<依赖><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><范围>提供</范围>

这个链接有帮助

未在 Spring Boot Web 应用程序中呈现的 JSP 文件

Im trying to convert my spring mvc project into spring boot. I converted all necessary files according to spring boot.There are no errors on console. But when i run my web app in browser im getting this error.

No mapping found for HTTP request with URI [/onlineshopping/WEB-INF/views/page.jsp] in DispatcherServlet with name 'dispatcherServlet'

any url i try to run im getting the same error why?

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);
    }
}

Console log file link

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;
        }

    }

file structure

Please tell me what am i doing wrong here?

解决方案

My problem solved after adding this configuration

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

after adding this configuration white page error stopped but jsp page code started showing as html so added these two dependancies.

<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>

this link helps

JSP file not rendering in Spring Boot web application

这篇关于为什么我收到此错误未找到带有 URI 的 HTTP 请求的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆