最近在使用thymeleaf时,遇到一个问题,比如要跳转的地址是localhost:8080/pro/a/b,跳转后发现变成了

localhost:8080/pro/path/a/b,这样地址中多了个path,显然是错误的。其实在跳转地址前加 / 和不加 / 是不一样的。

页面跳转地址前加 /,意味着跳转到项目的根目录,不加 / ,意味着从当前页地址跳转。

解决的办法也很简单,只要获取上下文路径就可以了。由于使用的thymeleaf下面jsp一笔带过。

下面是各种跳转的方式。

1.jsp

jsp获取上下文路径:下面只是jsp获取上下文路径的一种方式

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

 <c:set var="basePath"

 value="${pageContext.request.scheme}://${pageContext.request.serverName}: ${pageContext.request.serverPort}${pageContext.request.contextPath}" />

使用示例:<html><a href="${basePath}/jsp/index.jsp"></a></html>

 

2.thymeleaf

2.1.ajax

在thymeleaf中使用ajax提交,url:[[@{/index/ajaxtest}]]这样就可以。

$.ajax({
        async:true,
        url:"[[@{/findById/}]]"+id,
        type:"POST",
        success:function(data){
           alert("操作成功!");
        }
 })

2.2.form表单提交

<form class="form-group" th:action="@{/login}" method="post">
      <div class="form-group">
           <label>用户名</label>
           <input class="form-control" name="userName" type="text" placeholder="">
      </div>
      <div class="form-group">
           <label>密码</label>
           <input class="form-control" name="password" type="password" placeholder="">
      </div>
      <div class="text-right">
           <button class="btn btn-primary" type="submit">登录</button>
           <button class="btn btn-danger" data-dismiss="modal">取消</button>
      </div>
 </form>

2.3.a标签

<a th:href="@{'searchInfo/'+${info.id}}">查看</a>

这样使用thymeleaf会自动获取上下文参数。

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/wlv1314/p/12966454.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程