web development proper use absolute paths and relative paths

In web development, which often involves routing problem. How to use the absolute path and relative path is correct, is that every web developer must master things.

1. relative path

Relative path is to stand on my own point of view to find resources, worded as follows:

"./a.jsp"	//找同级目录
"../a.jsp"	//找上级目录
"./images/pic.jpg"	//找同级文件夹内的资源

2. Absolute path

Absolute path is the path to "/" at the beginning, that is from the root, of course, there is also the root of the pit, as detailed in the first 4:00

3. principle: try to use absolute paths, do not write the relative path

Because when more web development using forward and jump pages, with a relative path resources also with uml address of the page and change. About it is, if there is a page, his path is /a.jsp it refers to the same directory b.jsp of its resources, when a relative path written as ./b.jsp. A.jsp normal access time, resources indeed be loaded out, however, if by other means (such as a.jsp upper directory has a c.jsp, by forwarding to jump to a.jsp) to access a.jsp then ./b.jsp resources can not be loaded (404 not found), reason is that the browser will find b.jsp in the same directory c.jsp where, of course, can not find it ~~

4. Proper use absolute paths

The second point mentioned, the absolute path is "/" as the beginning, but the meaning of "/" indicates not the same

"/" == "http://localhost:8080/"		//浏览器眼里

"/" == "http://localhost:8080/myProject/"		//web应用眼里

4.1 so-called eye of the beholder, spicy Mody, who is the browser's eyes "lover" mean? That is, when "/" on behalf of "http: // localhost: 8080 /" it?

1.jsp里面都是(包括但不局限于以下两种)
	a.超链接:<a href = "/a.jsp">点我点我</a>
	
	b.form表单:<form action = "/a.jsp">

2.servlet里
	a.重定向的时候:response.sendRedirect("/a.jsp")

In order not an error, in front of the above path to add: request.getContextPath (), like becomes as follows:

	a.超链接:<a href = "request.getContextPath()/a.jsp">点我点我</a>
	
	b.form表单:<form action = "request.getContextPath()/a.jsp">

	c.重定向的时候:response.sendRedirect("request.getContextPath()/a.jsp")

4.2 as a web application, "beauty", scored grace, can be used directly. Including but not limited to the following three conditions:

1.servlet里的转发:request.getRequestDispatcher("/a.jsp")

2.web.xml里<servlet-mapping>中url映射
	<servlet-mapping>
		<servley-name>MyJSP</servley-name>
		<url-pattern>/a.jsp</url-pattern>
	</servlet-mapping>

3.自定义标签中

5. Summary

In web applications, do not attempt to use relative paths, when using an absolute path, see the case of use, a problem does not come out of resource loading, adding request.getContextPath () try, chances are you use exactly browser eyes of the "beauty."

Published 34 original articles · won praise 65 · views 3734

Guess you like

Origin blog.csdn.net/baidu_41860619/article/details/103568529