首页 > 代码库 > 路径问题以及cookie详解
路径问题以及cookie详解
1.路径问题:
注意 .代表执行程序的文件夹路径,在tomcat中也就是bin目录,所以要用this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");得到绝对路径;
代码练习:
package com.http.path; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PathDemo extends HttpServlet { public PathDemo() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); //给服务器使用的: / 表示在当前web应用的根目录(webRoot下) //request.getRequestDispatcher("/target.html").forward(request, response); //给浏览器使用的: / 表示在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 = new Properties(); properties.load(new FileInputStream(new File(path))); String user = properties.getProperty("user"); String passwd = properties.getProperty("passwd"); System.out.println("user = " + user + "\npasswd = " + passwd); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); 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 void init() throws ServletException { // Put your code here } }
路径问题以及cookie详解
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。