从request对象中获取路径的问题:例如: 项目名为:tmall_web 请求的servlet名为:loginServlet
示例代码如下:
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("========== LoginServlet ==============="); PrintWriter out = response.getWriter(); response.setContentType("text/html;charset=utf-8"); out.print("***************************************"); out.print("项目名:tmall_web || servlet名:loginServlet"); out.print("***************************************"); //获取的是项目名称: /tmall_web String path = request.getContextPath(); //获取项目请求根路径: http://localhost:8080/tmall_web/ String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; //获得客户端的ip地址: 0:0:0:0:0:0:0:1 String remoteAddress=request.getRemoteAddr(); //获取servlet的请求路径: /loginServlet String servletPath=request.getServletPath(); //获取项目的真实根目录,硬盘的位置: D: 911linpeng_work mall_webweb //假如部署tomcat:获取到的是项目在tomcat的根路径:例如:C:UsersAdministratorDesktopapache-tomcat-8.5.20webappsROOT String realPath=request.getRealPath("/"); //获取到用户名:null String remoteUser=request.getRemoteUser(); //获取项目的资源目录: /tmall_web/loginServlet String requestURI=request.getRequestURI(); //获取浏览器的请求url: localhost:8080/tmall_web/loginServlet String requestURL=request.getRequestURL().toString(); out.println("path:"+path+"<br>"); out.println("basePath:"+basePath+"<br>"); out.println("remoteAddr:"+remoteAddress+"<br>"); out.println("servletPath:"+servletPath+"<br>"); out.println("realPath:"+realPath+"<br>"); out.println("remoteUser:"+remoteUser+"<br>"); out.println("requestURI:"+requestURI+"<br>"); out.println("requestURI:"+requestURL+"<br>"); }
以上为个人总结,如有错误的地方,望大家指正,谢谢!