String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
String basePath = request.getServletContext().getRealPath("/");
String currentClassPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String currentFilePath = request.getServletPath();
// 或使用
String currentFilePath = request.getRequestURI();
String currentRequestUrl = request.getRequestURL();
- base标签
在base标签中的url属性值会当前页面中所有的url前面插入
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";%>
<html>
<head>
<base href="<%=baseUrl%>">
<title>JDemo</title>
<script src="/resource/ui/js/jquery-1.11.0.min.js"></script>
</head>
<body>
<h1>JDemo</h1>
<a href="javascript:">ajax测试</a>
</body>
<script>
$.ajax({
url: "index",
type: "post",
data: {name: "张三", age: "23", url: "<%=baseUrl%>index"},
success: function (Res) {
console.log(Res);
}
});
</script>
</html>
package com.demo;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
@WebServlet(name = "IndexServlet")
public class IndexServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
Map<String, String[]> parameterMap = request.getParameterMap();
for (Map.Entry<String, String[]> m :
parameterMap.entrySet()) {
String name = m.getKey();
String[] values = m.getValue();
for (String value :
values) {
System.out.print(name + ":" + value);
}
System.out.println();
}
out.print("ok");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}