Get complete URl string in ava
- HttpServletRequest httpRequest=(HttpServletRequest)request;
- String strBackUrl = "http://" + request.getServerName() //Server address
- + ":"
- + request.getServerPort() //Port number
- + httpRequest.getContextPath() //Project name
- + httpRequest.getServletPath() //Request a page or other address
- + "?" + (httpRequest.getQueryString()); //参数
-
The relative paths called in the jsp and class files are different. In jsp, the root directory is WebRoot In class files, the root directory is WebRoot/WEB-INF/classes Of course, you can also use System.getProperty( "user.dir" ) to get the absolute path of your project. (But I heard that it is not available under linux, not tested)
-
Another: How to get the path in detail in Jsp, Servlet, Java!
-
1. Get the path in .jsp:
-
Take the project named TEST as an example:
-
( 1 ) Get the full path of the current page containing the project name: request.getRequestURI()
-
Result: /TEST/test.jsp
-
( 2 ) Get the project name: request.getContextPath()
-
Result: /TEST
-
( 3 ) Get the full name of the directory where the current page is located: request.getServletPath()
-
Result: If the page is in the jsp directory /TEST/jsp/test.jsp
-
( 4 ) Get the full path of the server where the page is located: application.getRealPath( "page.jsp" )
-
Result: D:\resin\webapps\TEST\test.jsp
-
(5)得到页面所在服务器的绝对路径:absPath=newjava.io.File(application.getRealPath(request.getRequestURI())).getParent();
-
结果:D:\resin\webapps\TEST
-
2.在类中取得路径:
-
(1)类的绝对路径:Class.class.getClass().getResource("/").getPath()
-
结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/
-
(2)得到工程的路径:System.getProperty("user.dir")
-
结果:D:\TEST
-
3.在Servlet中取得路径:
-
(1)得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包名。
-
结果:E:\Tomcat\webapps\TEST
-
(2)得到IE地址栏地址:request.getRequestURL()
-
结果:http://localhost:8080/TEST/test
-
(3)得到相对地址:request.getRequestURI()
-
结果:/TEST/test
struts2设置了struts.multipart.saveDir后会在根目录建立文件夹,这样会涉及linux下的权限问题,
最好不要设置,使用struts默认
需要使用路径时,用下面的方法取得项目根目录的绝对路径(Tools为方法类)
public static String getRootPath() {
String classPath = Tools.class.getClassLoader().getResource("/").getPath();
String rootPath = "";
//windows下
if("\\".equals(File.separator)){
rootPath = classPath.substring(1,classPath.indexOf("/WEB-INF/classes"));
rootPath = rootPath.replace("/", "\\");
}
//linux下
if("/".equals(File.separator)){
rootPath = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
rootPath = rootPath.replace("\\", "/");
}
return rootPath;
}