路径问题以及cookie详解

Posted handsomecui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了路径问题以及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详解的主要内容,如果未能解决你的问题,请参考以下文章

javascript 操作cookies详解

js代码片段: utils/lcoalStorage/cookie

怎么设置cookie,怎么设置cookie以及删除cookie和cookie详解

cookie使用

Curl命令详解

Python中verbaim标签使用详解