1. Summary: Only forward the path without writing the project, all the others!
/** * path problem in web App * @author APPle * */public class Pathdemo extends HttpServlet {pub LIC void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8");//target resource: target.html/** * Think: Who is the target resource for? * For use with the server:/means the root directory of the current Web application (webroot) * For the browser:/indicates that in the root directory of WebApps, you must add the project path, that is,/day09= this.getservletcontext (). Getcont Extpath (); *//** * 1. Forwarding, server with */request.getrequestdispatcher ("/target.html"). Forward (request, response);/** * 2. Request redirect, browser with */ Response.sendredirect ("/day11/target.html");/** * 3.html page hyper-connect href browser with */response.getwriter (). Write ("
2. Path two: If Db.properties is in the SRC directory, Or the same as the Db.propertites in Resource folder, which is parallel to SRC
/** * Read resource files under Web application (for example, properties) * @author APPle */public class Resourcedemo extends HttpServlet {//Read resource files under Web Apps (for example prop erties) public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/** *. Run directory on behalf of Java command. Where is the Java Run command?? Under the Tomcat/bin directory * Conclusion: In a Web project,. Represents the start of the Tomcat/bin directory, so this relative path cannot be used. *///read the file. Do not read this under the Web project. Because. Represents the/*file file = new File ("./src/db.properties") in the Tomcat/bin directory; FileInputStream in = new FileInputStream (file) *//** * Use the Web app to load a resource file *//** * 1. Getrealpath read, returns the absolute path of the resource file if db.properties in the src directory *//*string path = This.getservletcontext (). Getrealpath ("/web-inf/ Classes/db.properties "); SYSTEM.OUT.PRINTLN (path); File File = new file (path); FileInputStream in = new FileInputStream (file); *//** * 2. getResourceAsStream () Gets the resource file and returns the input stream */inputstream in = This.getservletcontext (). getResourceAsStream ("/web-inf/ Classes/db.properties "); Properties prop = new properties ();//Read resource file Prop.load (in); String user = Prop.getproperty ("user"); String password = prop.getproperty ("password"); System.out.println ("user=" +user); System.out.println ("password=" +password);}
Path issues for Web Apps