【问题标题】:<a href> not hitting get method in Spring boot<a href> 在 Spring Boot 中没有点击 get 方法
【发布时间】:2018-11-12 04:59:38
【问题描述】:

HTML

<div ng-model="currentUser" id="userContainer">{{currentUser.email}}
    <div class="dropdown-content">
        <a href="/logout">Logout</a>
    </div>
</div>

控制器

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public void logout(HttpServletResponse response, HttpServletRequest request) throws Exception {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            cookie.setValue("");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }

    response.sendRedirect("/index.html");

}

我正在运行一个 Spring Boot 应用程序,并将注销控制器定义为 GET 方法。 单击 Logout Div 时,url 变为http://******.ngrok.io/logout 但它从未命中 Controller 方法,但是当我使用 http://******.ngrok.io/logout URL 重新加载浏览器时,控制器会被命中并让我退出应用程序。

【问题讨论】:

    标签: java html spring spring-boot


    【解决方案1】:

    你需要用完整的上下文路径定义href

    在 JSP 中它的

    <a href="${contextPath}/logout">Logout</a>
    

    百里香

    <a href="@{/logout}">Logout</a>
    

    【讨论】:

      【解决方案2】:

      但原因可能是 API 可能没有被调用,您可以尝试在注销按钮的 href 中附加上下文路径。

      作为

      Contextpath = "你的 Springboot 应用运行的路径"

      <a href"${Contxtpath}/logout"/>
      

      【讨论】:

      • 这不起作用:因为它将 URL 更改为 `http://****.ngrok.io/html/$%7BContextpath%7D/logout'。
      【解决方案3】:

      由于我在项目中使用了 Angular js,因此我更改为 ng-click 事件并在 Javascript 中定义了一个绑定函数。这现在工作正常。

      HTML:

      <div ng-model="currentUser" id="userContainer">{{currentUser.email}}
          <div class="dropdown-content">
              <a data-ng-click="logout()">Logout</a>
          </div>
      </div>
      

      JAvascript:

      $scope.logout = function(){
          $http.get("/logout").then(logoutCallBack, logoutErrorCallback);
      }
      
      function logoutCallBack(){
          $window.location.href = "/index.html";
      };
      function logoutErrorCallback(){};
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-02
        • 2019-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-17
        • 2023-03-30
        相关资源
        最近更新 更多