AngularJS remove # and have error when refresh pag

2020-06-18 00:56发布

I have AngularJS webapp and start it with Tomcat 7. Using $locationProvider.html5Mode(true) I remove hash '#' from url

localhost:8080/App/#/login -> localhost:8080/App/login

But now, when I refresh localhost:8080/App/login I have 404 error. How to configure Tomcat7 for localhost:8080/App/login refresh?

app.config:

$urlRouterProvider.otherwise("/login/");

$stateProvider
        .state('home', {
            abstract: true,
            templateUrl: 'dist/view/home.html',
            controller: 'HomeCtrl'
        });

$locationProvider.html5Mode(true);

index.html:

<head>
    <meta charset="utf-8">
    <script>
        document.write('<base href="' + document.location + '" />');
    </script>
</head>

7条回答
疯言疯语
2楼-- · 2020-06-18 01:49

Erik Honn gives a good explanation of the logic. Here's how I solved it using Jersey and Tomcat 7 with Tucky's urlrewritefilter https://github.com/paultuckey/urlrewritefilter

  1. Add dependency using Maven or download jar.

    <dependency>
        <groupId>org.tuckey</groupId>
        <artifactId>urlrewritefilter</artifactId>
        <version>4.0.3</version>
    </dependency>
    
  2. Add filter mappings to the web.xml file located in WEB-INF directory. This should be within the web-app tag.

    <filter>
      <filter-name>UrlRewriteFilter</filter-name>
      <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>UrlRewriteFilter</filter-name>
      <url-pattern>/*</url-pattern>
      <dispatcher>REQUEST</dispatcher>
      <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    
  3. Create a file in WEB-INF called urlrewrite.xml and add rerouting to index.html

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN"
    "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
    
    <!--
    
    Configuration file for UrlRewriteFilter
    http://www.tuckey.org/urlrewrite/
    
    -->
    <urlrewrite>
    
    <rule>
    <from>^/titles$</from>
    <to>index.html</to>
    </rule>
    
    <rule>
    <from>^/authors$</from>
    <to>index.html</to>
    </rule>
    
    <rule>
    <from>^/courses$</from>
    <to>index.html</to>
    </rule>
    
    <rule>
    <from>^/account$</from>
    <to>index.html</to>
    </rule> 
    
    </urlrewrite>
    

Don't forget to relaunch so that the xml is configured. It would be great if someone knew a way to bundle the routes to all go to index.html rather than having to set individual rules.

查看更多
登录 后发表回答