为什么这个Angular路由会导致404“Not Found”页面?

时间:2022-10-10 08:01:51

In this example, clicking any of the 3 anchor links instantly routes to a 404 "Not Found" page. -I.e., instead of inserting html text into the <div ng-view></div>

在此示例中,单击3个锚链接中的任何一个即时路由到404“未找到”页面。 -I.e.,而不是将html文本插入

What is incorrect (or missing) that would enable this code to work properly? (syntax, path, etc.)

什么是不正确的(或丢失的),以使此代码正常工作? (语法,路径等)

(I'm confounded!)

Thanks for your help!

谢谢你的帮助!

(I'm new to AngularJS, and its clear that I lack experience to pick out the issue)

(我是AngularJS的新手,很明显我缺乏挑选问题的经验)

the initial html page displays like this...

最初的html页面显示如下......

为什么这个Angular路由会导致404“Not Found”页面?

...this is the result of clicking "testA" (note the URL change)

...这是点击“testA”的结果(注意URL更改)

为什么这个Angular路由会导致404“Not Found”页面?

index.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html lang="en" ng-app="mainApp">
        <head>
            <title>mywebapp</title>
            <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <base href="/"> 

            <script type="text/javascript" src="${pageContext.request.contextPath}/webjars/bootstrap/3.3.1/js/bootstrap.js"></script>  
            <script type="text/javascript" src="${pageContext.request.contextPath}/webjars/angularjs/1.3.13/angular.js"></script>    
            <script type="text/javascript" src="${pageContext.request.contextPath}/webjars/angularjs/1.3.13/angular-route.js"></script>   

            <script type="text/javascript">
                var mainApp = angular.module('mainApp', ['ngRoute']);

                mainApp.config(function ($routeProvider) {

                    alert('mywebapp - $routeProvider=' + JSON.stringify($routeProvider));

                    $routeProvider    
                        .when('/', {
                            templateUrl : 'resources/pages/home.html',
                            controller  : 'MainController'
                        })                
                        .when('/testA', {
                            templateUrl : 'resources/pages/testA.html',
                            controller  : 'TestAController'
                        })
                        .when('/testB', {
                            templateUrl : 'resources/pages/testB.html',
                            controller  : 'TestBController'
                        })
                        .when('/testC', {
                            templateUrl : 'resources/pages/testC.html',
                            controller  : 'TestCController'
                        });
                });

                mainApp.controller('MainController', function ($scope) {
                    alert('MainController...');
                    $scope.message = 'HOME page.';
                });

                mainApp.controller('TestAController', function ($scope) {
                    alert('TestAController...');
                    $scope.message = 'TestA page.';
                });

                mainApp.controller('TestBController', function ($scope) {
                    alert('TestBController...');
                    $scope.message = 'TestB page.';
                });

                mainApp.controller('TestCController', function ($scope) {
                    alert('TestCController...');
                    $scope.message = 'TestC page.';
                });
            </script>
        </head>

        <body ng-controller="MainController">
            <input type="hidden" id="contextPath" value="${pageContext.request.contextPath}" />    
            <div>
                <h4>select a page destination...</h4>
                <div>
                    <ul>
                        <li><a href="#/testA">TestA</a></li>
                        <li><a href="#/testB">TestB</a></li>
                        <li><a href="#/testC">TestC</a></li>                  
                    </ul>
                </div>
                <div id="main">
                    <div ng-view></div>
                </div>     
            </div>              
        </body>
    </html>


BELOW IS MORE DETAILED INFORMATION IF YOU LIKE...(THX)


home.html (fragment)

    <div class="jumbotron text-center">
        <h1>HOME Page</h1>
        <p>{{ message }}</p>
    </div>      

testA.html (fragment)

    <div class="jumbotron text-center">
        <h1>TestA Page</h1>
        <p>{{ message }}</p>
    </div>  

testB.html (fragment)

    <div class="jumbotron text-center">
        <h1>TestB Page</h1>
        <p>{{ message }}</p>
    </div>  

testC.html (fragment)

    <div class="jumbotron text-center">
        <h1>TestC Page</h1>
        <p>{{ message }}</p>
    </div>

applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:p="http://www.springframework.org/schema/p"
                 xmlns:aop="http://www.springframework.org/schema/aop"
                 xmlns:context="http://www.springframework.org/schema/context"
                 xmlns:jdbc="http://www.springframework.org/schema/jdbc"
                 xmlns:jee="http://www.springframework.org/schema/jee"
                 xmlns:task="http://www.springframework.org/schema/task"
                 xmlns:tx="http://www.springframework.org/schema/tx"
                 xmlns:ws="http://jax-ws.dev.java.net/spring/core"
                 xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
                 xmlns:mvc="http://www.springframework.org/schema/mvc" 
                 xmlns:util="http://www.springframework.org/schema/util"
                 xmlns:sec="http://www.springframework.org/schema/security"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee              http://java.sun.com/xml/ns/javaee/beans_1_0.xsd
                                    http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop.xsd   
                                    http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans.xsd     
                                    http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context.xsd    
                                    http://www.springframework.org/schema/jdbc      http://www.springframework.org/schema/jdbc/spring-jdbc.xsd     
                                    http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee.xsd     
                                    http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd
                                    http://www.springframework.org/schema/task      http://www.springframework.org/schema/task/spring-task.xsd                                
                                    http://www.springframework.org/schema/util      http://www.springframework.org/schema/util/spring-util.xsd                                
                                    http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security.xsd                                                                                                                                                                                                                                                                                                                                                                             
                                    http://jax-ws.dev.java.net/spring/core          http://jax-ws.dev.java.net/spring/core.xsd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
                                    http://jax-ws.dev.java.net/spring/servlet       http://jax-ws.dev.java.net/spring/servlet.xsd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
                                    http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

        <beans:bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <beans:property name="prefix" value="/WEB-INF/app" />
            <beans:property name="suffix" value=".jsp" />
        </beans:bean>

        <context:component-scan base-package="aaa.bbb.ccc.**" />    

        <mvc:annotation-driven content-negotiation-manager="contentManager"/>
        <beans:bean id="contentManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
            <beans:property name="favorPathExtension" value="true"/>
            <beans:property name="ignoreAcceptHeader" value="true" />
            <beans:property name="defaultContentType" value="text/html" />
            <beans:property name="useJaf" value="false"/>
            <beans:property name="mediaTypes">
                <beans:map>
                    <beans:entry key="html" value="text/html" />
                    <beans:entry key="json" value="application/json" />
                    <beans:entry key="xml" value="application/xml" />
                </beans:map>
            </beans:property>
        </beans:bean>

        <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
        <mvc:resources mapping="/static/**" location="/static/" />
        <mvc:resources mapping="/webjars/**" location="/webjars/" />
        <mvc:resources mapping="/resources/**" location="/resources/" />    

    </beans:beans>

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

        <filter>
            <filter-name>charEncodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>

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

        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>

        <listener>
            <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
        </listener>    

        <listener>
            <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
        </listener>    

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

        <servlet>
            <servlet-name>appServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>
                    WEB-INF/spring/applicationContext.xml           
                </param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>

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

    </web-app>

pom.xml

    <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/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>aaa.bbb.ccc</groupId>
        <artifactId>mywebapp</artifactId>
        <version>1</version>
        <packaging>war</packaging>
        <name>mywebapp</name>
        <url>http://maven.apache.org</url>

        <properties>
            <org.springframework.version>3.2.8.RELEASE</org.springframework.version>        
            <org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version>            
            <java.version>1.7</java.version>
            <junit.version>4.11</junit.version>
            <servlet-api.version>3.1.0</servlet-api.version>
            <jsp-api.version>2.1</jsp-api.version>
            <javax.servlet.jsp.version>2.3.1</javax.servlet.jsp.version>            
            <jstl.version>1.2</jstl.version>
            <jackson-databind.version>2.3.4</jackson-databind.version>
            <jackson.mapper.version>1.9.13</jackson.mapper.version>        
            <javax.inject.version>1</javax.inject.version>
            <org.slf4j.version>1.7.7</org.slf4j.version>        
            <log4j.version>1.2.17</log4j.version>
            <commons-codec.version>1.9</commons-codec.version>
            <datatables.version>1.10.4</datatables.version>
            <angularjs.version>1.3.13</angularjs.version>                   

        </properties>

        <dependencies>

            <!-- Unit Testing -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>

            <!-- Servlet 3.1   -->      
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>${servlet-api.version}</version>
                <scope>provided</scope>
            </dependency>

            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>javax.servlet.jsp-api</artifactId>
                <version>${javax.servlet.jsp.version}</version>
            </dependency>

            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>${jstl.version}</version>
            </dependency>   

            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>    

            <!-- Spring Security -->       
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>${org.springframework.security.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>${org.springframework.security.version}</version>
            </dependency>    

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>${org.springframework.security.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-aspects</artifactId>
                <version>${org.springframework.security.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-taglibs</artifactId>
                <version>${org.springframework.security.version}</version>
            </dependency>

            <!-- JSON jackson for spring         -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson-databind.version}</version>
            </dependency>

            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>${jackson.mapper.version}</version>
            </dependency>

            <!-- @Inject -->
            <dependency>
                <groupId>javax.inject</groupId>
                <artifactId>javax.inject</artifactId>
                <version>${javax.inject.version}</version>
            </dependency>

            <!-- Logging -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${org.slf4j.version}</version>
            </dependency>

            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>${org.slf4j.version}</version>
                <scope>runtime</scope>
            </dependency>

            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${org.slf4j.version}</version>
                <scope>runtime</scope>
            </dependency>

            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>        

            <dependency>
                <groupId>log4j</groupId>
                <artifactId>apache-log4j-extras</artifactId>
                <version>${log4j.version}</version>
                <scope>runtime</scope>
            </dependency>

            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>${commons-codec.version}</version>
            </dependency>

            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>bootstrap</artifactId>
                <version>3.3.1</version>
            </dependency>

            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>datatables</artifactId>
                <version>${datatables.version}</version>
            </dependency>   

            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>angularjs</artifactId>
                <version>${angularjs.version}</version>
            </dependency>                      

        </dependencies>

        <build>
            <finalName>${project.name}-${project.version}</finalName>
            <plugins>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                    </configuration>
                </plugin>    

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.3</version>
                </plugin> 

            </plugins>
        </build>

    </project>

project structure...

为什么这个Angular路由会导致404“Not Found”页面?

3 个解决方案

#1


2  

it appears that the "culprit" is the frikkin <base> tag. -When removed, all works as expected. (whew!...-although, a bit embarrassing)

似乎“罪魁祸首”是frikkin 标签。 - 删除后,所有工作都按预期工作。 (哇!......-虽然有点尴尬)

i.e.,

    <head>
        <title>mywebapp</title>
        <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <base href="/">  (**WORKS AFTER REMOVING THIS LINE**)

#2


0  

I see that all your requests are being passed to Spring MVC:

我看到你的所有请求都被传递给了Spring MVC:

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

Your next configuration seems that /resources/** is being resolved to /resources... which it seems correct but innecesary:

您的下一个配置似乎/ resources / **正在解析为/ resources ...这似乎是正确的但是不合适的:

<mvc:resources mapping="/resources/**" location="/resources/" /> 

However... this tag tells Spring to add a prefix+suffix which maybe is causing your problem:

但是......这个标签告诉Spring添加一个前缀+后缀,这可能会导致你的问题:

<beans:bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/app" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

I recommend you to map only .htm requests to Spring MVC and leave the rest request to be resolved by the server (as static resources).

我建议您只将.htm请求映射到Spring MVC,并让其余请求由服务器解析(作为静态资源)。

Try the next changes:

尝试下一个更改:

1) change the servlet mapping to *.htm (this foces that ONLY urls like index.htm will be processed by Spring MVC):

1)将servlet映射更改为* .htm(这个仅仅是像index.htm这样的URL将由Spring MVC处理):

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

2) include index.htm (with no "l") as welcome page (so /# will be mapped to /index.htm#/, so... the welcome page will be processed as jsp):

2)包括index.htm(没有“l”)作为欢迎页面(所以/#将映射到/index.htm#/,所以......欢迎页面将被处理为jsp):

<welcome-file-list>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>

#3


0  

try removing hashtags from your routes

尝试从您的路线中删除主题标签

<body ng-controller="MainController">
        <input type="hidden" id="contextPath" value="${pageContext.request.contextPath}" />    
        <div>
            <h4>select a page destination...</h4>
            <div>
                <ul>
                    <li><a href="/testA">TestA</a></li>
                    <li><a href="/testB">TestB</a></li>
                    <li><a href="/testC">TestC</a></li>                  
                </ul>
            </div>
            <div id="main">
                <div ng-view></div>
            </div>     
        </div>              
    </body>

try using this way to instance your routes

尝试使用这种方式来实例化您的路线

angular.module('yourApp').config(function ($stateProvider) {
  $stateProvider.state('route', {
    url: '/route/in/url/you/want/to/use', //after your proyect url 
    templateUrl: 'resources/app/statistics/statistics.html', //html for this 

//route
    controller: 'statisticsController', //controller for this route
    controllerAS: 'statisticsController' //the way you gona call this 

//controller(this replace scope in html only for this controller)

  })
});

#1


2  

it appears that the "culprit" is the frikkin <base> tag. -When removed, all works as expected. (whew!...-although, a bit embarrassing)

似乎“罪魁祸首”是frikkin 标签。 - 删除后,所有工作都按预期工作。 (哇!......-虽然有点尴尬)

i.e.,

    <head>
        <title>mywebapp</title>
        <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <base href="/">  (**WORKS AFTER REMOVING THIS LINE**)

#2


0  

I see that all your requests are being passed to Spring MVC:

我看到你的所有请求都被传递给了Spring MVC:

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

Your next configuration seems that /resources/** is being resolved to /resources... which it seems correct but innecesary:

您的下一个配置似乎/ resources / **正在解析为/ resources ...这似乎是正确的但是不合适的:

<mvc:resources mapping="/resources/**" location="/resources/" /> 

However... this tag tells Spring to add a prefix+suffix which maybe is causing your problem:

但是......这个标签告诉Spring添加一个前缀+后缀,这可能会导致你的问题:

<beans:bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/app" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

I recommend you to map only .htm requests to Spring MVC and leave the rest request to be resolved by the server (as static resources).

我建议您只将.htm请求映射到Spring MVC,并让其余请求由服务器解析(作为静态资源)。

Try the next changes:

尝试下一个更改:

1) change the servlet mapping to *.htm (this foces that ONLY urls like index.htm will be processed by Spring MVC):

1)将servlet映射更改为* .htm(这个仅仅是像index.htm这样的URL将由Spring MVC处理):

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

2) include index.htm (with no "l") as welcome page (so /# will be mapped to /index.htm#/, so... the welcome page will be processed as jsp):

2)包括index.htm(没有“l”)作为欢迎页面(所以/#将映射到/index.htm#/,所以......欢迎页面将被处理为jsp):

<welcome-file-list>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>

#3


0  

try removing hashtags from your routes

尝试从您的路线中删除主题标签

<body ng-controller="MainController">
        <input type="hidden" id="contextPath" value="${pageContext.request.contextPath}" />    
        <div>
            <h4>select a page destination...</h4>
            <div>
                <ul>
                    <li><a href="/testA">TestA</a></li>
                    <li><a href="/testB">TestB</a></li>
                    <li><a href="/testC">TestC</a></li>                  
                </ul>
            </div>
            <div id="main">
                <div ng-view></div>
            </div>     
        </div>              
    </body>

try using this way to instance your routes

尝试使用这种方式来实例化您的路线

angular.module('yourApp').config(function ($stateProvider) {
  $stateProvider.state('route', {
    url: '/route/in/url/you/want/to/use', //after your proyect url 
    templateUrl: 'resources/app/statistics/statistics.html', //html for this 

//route
    controller: 'statisticsController', //controller for this route
    controllerAS: 'statisticsController' //the way you gona call this 

//controller(this replace scope in html only for this controller)

  })
});