1. Path PROBLEM:
Note the folder path that represents the execution program, which is the bin directory in Tomcat, so use This.getservletcontext (). Getrealpath ("/web-inf/classes/db.properties"); Get the absolute path;
Code Exercise:
PackageCom.http.path;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjava.util.Properties;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classPathdemoextendsHttpServlet { PublicPathdemo () {Super(); } Public voiddestroy () {Super. Destroy ();//Just puts "destroy" string in log//Put Your code here } Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcharacterencoding ("Utf-8"); Request.setcharacterencoding ("Utf-8"); //used by the server:/represents the root directory of the current web App (Webroot)//request.getrequestdispatcher ("/target.html"). Forward (request, response); //for the browser:/indicates the root directory of the WebApps//response.sendredirect ("/myweb/target.html");String Path= This. Getservletcontext (). Getrealpath ("/web-inf/classes/db.properties"); //This.getservletcontext (). getResourceAsStream ("/web-inf/classes/db.properties");System.out.println (path); Properties Properties=NewProperties (); Properties.load (NewFileInputStream (NewFile (path)); String User= Properties.getproperty ("User"); String passwd= Properties.getproperty ("passwd"); System.out.println ("user =" + user + "\NPASSWD =" +passwd); } Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Text/html"); PrintWriter out=Response.getwriter (); Out.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > "); Out.println ("<HTML>"); Out.println ("); Out.println ("<BODY>"); Out.print ("This is"); Out.print ( This. GetClass ()); Out.println (", using the POST method"); Out.println ("</BODY>"); Out.println ("</HTML>"); Out.flush (); Out.close (); } Public voidInit ()throwsservletexception {//Put Your code here }}
Path issues and Cookie explanations