In development we inevitably encounter many situations where we need to write URL addresses, which often makes us feel headache. The following author recommends a simple approach. URL addresses are divided into absolute paths and relative paths. Relative paths are also divided into relative resource paths and relative root paths. It is clear that the absolute path is to be disabled in development. As for the relative resource path and the relative root path with which problem, the author recommends using relative root path, relative resource path can cause confusion easily. I recommend that you use a relative root path in web development, that is, "/" to write the URL address. So we just need to figure out who the "/" stands for. Can be simply understood as "/" is for whom, on behalf of WHO. For the server, on behalf of the Web project, for the browser to represent WebApps.
PackageCom.yyz.response;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;//How to address URLs in Web projects Public classResponsedemoextendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//ServletContext, for the server, "/" on behalf of the Web project This. Getservletcontext (). Getrealpath ("/download/1.gif"); //forward, for the server, "/" on behalf of the Web project. This. Getservletcontext (). Getrequestdispatcher ("/register.html"); //SENDREDIRCT, for the browser, "/" stands for WebApps. Response.sendredirect ("/test/register.html");/*** in register.html to access Responsedemo.java, the wording of hyperlinks, to the browser, "/" for WebApps * <a href= "/test/servlet/responsedemo" > </a>*/ } Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {}}
For your understanding, the following is a diagram of the package Explorer under MyEclipse:
There is also an easy place to wonder, whether to use "/" or "\ \". Read the resources on the hard disk with "\ \" to process the URL resource with "/". All resources in the server are Web resources, all with a "/". But when we read a file on the hard disk with "\ \", as
FileInputStream in = new FileInputStream ("C:\\AG\\SD")
How to address URLs in Web projects