Spring Boot CSS呈现问题

时间:2018-11-22 14:44:38

标签: java spring spring-boot

我正在尝试将spring mvc项目转换为spring boot。我根据春季启动转换了所有必需的文件。控制台上没有错误。但是,当我在浏览器中运行Web应用程序时,我的应用程序运行成功,但是没有CSS加载。我尝试了堆栈溢出的所有解决方案,但没有帮助。请帮助我解决这个问题。

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

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.DefaultServletHandlerConfigurer;
    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.theme.CookieThemeResolver;
    import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    import org.springframework.web.servlet.view.JstlView;
    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.setViewClass(JstlView.class);
                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(ResourceHandlerRegistry registry) {
                    registry.addResourceHandler("/resources/**")
                    .addResourceLocations("/assets/")
                            .setCachePeriod(31556926);
            }

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

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

web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>

<!-- configuring front-controller -->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!-- For throwing Exception -->
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>

    <multipart-config>
        <max-file-size>2097152</max-file-size>
        <max-request-size>4194304</max-request-size>
        <file-size-threshold>1048576</file-size-threshold>
    </multipart-config>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- Spring security configuration -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring-security.xml
    </param-value>
</context-param>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

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

    }

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>onlineshopping</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.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>net.kzn</groupId>
            <artifactId>shoppingbackend</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</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-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>

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

        <!-- JSTL -->

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>5.0.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

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

    </dependencies>

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

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


</project>

页面,jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<spring:url var="css" value="/resources/css" />
<spring:url var="js" value="/resources/js" />
<spring:url var="images" value="/resources/images" />

<c:set var="contextRoot" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Online Shopping Website Using Spring MVC and Hibernate">
<meta name="author" content="Khozema Nullwala">
<meta name="_csrf" content="${_csrf.token}">
<meta name="_csrf_header" content="${_csrf.headerName}">

<title>Online Shopping - ${title}</title>

<script>
    window.menu = '${title}';

    window.contextRoot = '${contextRoot}'

</script>

<!-- Bootstrap core CSS -->
<link href="${css}/bootstrap.min.css" rel="stylesheet">

<%-- <!-- Bootstrap cyborg theme -->
 <link href="${css}/bootstrap-flatly-theme.css" rel="stylesheet">
 --%>

<link rel="stylesheet"
    href="https://use.fontawesome.com/releases/v5.4.1/css/all.css"
    integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz"
    crossorigin="anonymous">

<link href="https://fonts.googleapis.com/css?family=Tajawal:300&amp;subset=arabic" rel="stylesheet">

<!-- Bootstrap dataTables -->
<link href="${css}/dataTables.bootstrap4.css" rel="stylesheet">

<!-- Custom styles for this template -->
<link href="${css}/myapp.css" rel="stylesheet">
<link href="${css}/myapp2.css" rel="stylesheet">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

    <div class="se-pre-con"></div>
    <div class="wrapper" style="background-color: #e8eaed">

        <!-- Navigation -->
        <%@include file="./shared/navbar.jsp"%>

        <!-- Page Content -->

        <div class="content">

            <!-- Loading the home content -->
            <c:if test="${userClickHome == true }">
                <%@include file="home.jsp"%>
            </c:if>

            <!-- Load only when user clicks about -->
            <c:if test="${userClickAbout == true }">
                <%@include file="about.jsp"%>
            </c:if>

            <!-- Load only when user clicks contact -->
            <c:if test="${userClickContact == true }">
                <%@include file="contact.jsp"%>
            </c:if>

            <!-- Load only when user clicks contact -->
            <c:if test="${userClickAllProducts == true or userClickCategoryProducts == true }">
                <%@include file="listProducts.jsp"%>
            </c:if> 


            <!-- Load only when user clicks show product -->
            <c:if test="${userClickShowProduct == true}">
                <%@include file="singleProduct.jsp"%>
            </c:if>                             

            <!-- Load only when user clicks manage product -->
            <c:if test="${userClickManageProduct == true}">
                <%@include file="manageProduct.jsp"%>
            </c:if> 

            <!-- Load only when user clicks manage product -->
            <c:if test="${userClickShowCart == true}">
                <%@include file="cart.jsp"%>
            </c:if> 

            <!-- Load only when user clicks manage product -->
            <c:if test="${userClickViewProducts == true}">
                <%@include file="viewProducts.jsp"%>
            </c:if>

            <!-- Load only when user clicks manage product -->
            <c:if test="${userClickSearch == true}">
                <%@include file="search.jsp"%>
            </c:if> 
        </div>


        <!-- Footer comes here -->
        <%@include file="./shared/footer.jsp"%>

        <!-- jQuery -->
        <script src="${js}/jquery.js"></script>

        <script src="${js}/jquery.validate.js"></script>

        <!-- Bootstrap Core JavaScript -->
        <script src="${js}/bootstrap.min.js"></script>

        <!-- DataTable Plugin -->
        <script src="${js}/jquery.dataTables.js"></script>

        <!-- DataTable Bootstrap Script -->
        <script src="${js}/dataTables.bootstrap4.js"></script>

        <!-- DataTable Bootstrap Script -->
        <script src="${js}/bootbox.min.js"></script>

        <!-- Self coded javascript -->
        <script src="${js}/myapp.js"></script>
        <script src="${js}/myapp2.js"></script>

    </div>

</body>

</html>

application.properties

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

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("/");
    }
}

文件结构

enter image description here enter image description here

请告诉我我在做什么错了。

1 个答案:

答案 0 :(得分:1)

好吧, 首先,也许您对某些个人理由使用了一些依赖关系,但是我尝试了尽可能地格式化您的代码。 PS:我没有尝试使用此代码,但是您可以做到这一点,并告诉我们是否可以:

Pom

您可以设置

<?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>onlineshopping</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>onlineshopping</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.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>net.kzn</groupId>
            <artifactId>shoppingbackend</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

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

        <!-- This is a web application -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        <!-- Tomcat embedded container-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>

        <!-- JSTL for JSP -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
            </dependency>

        <!-- Need this to compile JSP -->
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <scope>provided</scope>
            </dependency>

        <!-- Need this to compile JSP, tomcat-embed-jasper version is not working, no idea why -->
            <dependency>
                <groupId>org.eclipse.jdt.core.compiler</groupId>
                <artifactId>ecj</artifactId>
                <version>4.6.1</version>
                <scope>provided</scope>
            </dependency>

        <!-- Optional, test for static content, bootstrap CSS-->
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>bootstrap</artifactId>
                <version>3.3.7</version>
            </dependency>
    </dependencies>

    <build>
            <plugins>
                <!-- Package as an executable jar/war -->
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
    </build>
</project>

主类:

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(OnlineshoppingApplication.class);
    }

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

在您的page.jsp

<head> 
    ....
    <c:url value="/css/example.css" var="exampleCsss" />
    <link href="${exampleCss}" rel="stylesheet" />
</head>

在aplication.properties中,添加:

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

还有您的js文件,请尝试在关闭body标签之前将其放入。

如果可以的话,也尝试具有这样的结构:

enter image description here