4

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 enter image description here enter image description here enter image description here

Please tell me what am i doing wrong here?

vidy
  • 1,572
  • 6
  • 24
  • 43
  • Hello. Do you have the same error for all URL you defined or only for `http://localhost:8081` ? – Mickael Nov 22 '18 at 10:26
  • Same error showing for any url. localhost :8081 showing blank page.. if i enter url localhost:8081/onlineshopping/abo ut or any url then shownig same error – vidy Nov 22 '18 at 10:54
  • In the log you can try to look at the controllers that are initialized and at the paths that are processed by your controllers. Spring has detailed logs. – Anatoly Samoylenko Nov 22 '18 at 11:00
  • 1
    Did you try something like this : `http://localhost:8081/onlineshopping/home` ? Because you have the following configuration `server.servlet.context-path=/onlineshopping` – Mickael Nov 22 '18 at 11:10
  • Yeah I tried that but having same error – vidy Nov 22 '18 at 11:20
  • Ok then. Could you please provide the startup logs ? – Mickael Nov 22 '18 at 11:24
  • does http://localhost:8081/actuator or http://localhost:8081/onlineshopping/actuator give you the spring actuator page? – pcoates Nov 22 '18 at 11:27
  • yes localhost:8081/onlineshopping/actuator give actuator page. not localhost:8081/actuator. – vidy Nov 22 '18 at 11:45
  • @Mickael I added console log file link please check. – vidy Nov 22 '18 at 12:05
  • 1
    Im not sure . I suspect may be this will help :https://stackoverflow.com/questions/30406186/spring-boot-java-config-no-mapping-found-for-http-request-with-uri-in – soorapadman Nov 22 '18 at 12:09
  • 1
    @manfromnowhere that link help i added tomcat-embed-jasper dependancy and configureDefaultServletHandling() and now web pages are showing. thanks. – vidy Nov 22 '18 at 12:24
  • @manfromnowhere but my css not rendering why? – vidy Nov 22 '18 at 14:11

2 Answers2

3

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

vidy
  • 1,572
  • 6
  • 24
  • 43
2

Your view resolver doesn't seem to have a viewclass for handling jsps. Try setting the viewclass in you AppConfig.java

/** View resolver for JSP */
@Bean
public ViewResolver getViewResolver(){
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setViewClass(JstlView.class);
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}
pcoates
  • 2,102
  • 1
  • 9
  • 20