首页 > 代码库 > 路径问题以及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详解