【Java】【web】获取访问项目路径
2017-04-09 本文已影响146人
JerichoPH
- 获取访问根地址
String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
- 获取访问项目跟目录
String basePath = request.getServletContext().getRealPath("/");
- 获取当前class文件目录
String currentClassPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
- 获取当前访问脚本目录
String currentFilePath = request.getServletPath();
// 或使用
String currentFilePath = request.getRequestURI();
- 获取当前访问全地址
String currentRequestUrl = request.getRequestURL();
- base标签
在base标签中的url属性值会当前页面中所有的url前面插入- index.jsp
<%@ 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>
- IndexServlet.java
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); } }