Web应用中路径问题

思考: 目标资源是给谁使用的。

      给服务器使用的:   /  表示在当前web应用的根目录(webRoot下)
      给浏览器使用的:   /  表示在webapps的根目录下
package gz.itcast.a_path;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** * web应用中路径问题 * @author APPle * */
public class PathDemo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //目标资源: target.html
        /** * 思考: 目标资源是给谁使用的。 * 给服务器使用的: / 表示在当前web应用的根目录(webRoot下) * 给浏览器使用的: / 表示在webapps的根目录下 */
        /** * 1.转发 */
        //request.getRequestDispatcher("/target.html").forward(request, response);


        /** * 2.请求重定向 */
        //response.sendRedirect("/day11/target.html");

        /** * 3.html页面的超连接href */
        response.getWriter().write("<html><body><a href='/day11/target.html'>超链接</a></body></html>");

        /** * 4.html页面中的form提交地址 */
        response.getWriter().write("<html><body><form action='/day11/target.html'><input type='submit'/></form></body></html>");
    }

}

读取web应用下的资源文件(例如properties)

ServletContext:
    getRealPath读取,返回资源文件的绝对路径
    getResourceAsStream() 得到资源文件,返回的是输入流
package gz.itcast.b_resource;

import java.io.IOException;
import java.io.InputStream;
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 ResourceDemo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /** * . 代表java命令运行目录。java运行命令在哪里?? 在tomcat/bin目录下 * 结论: 在web项目中, . 代表在tomcat/bin目录下开始,所以不能使用这种相对路径。 */


        //读取文件。在web项目下不要这样读取。因为.表示在tomcat/bin目录下
        /*File file = new File("./src/db.properties"); FileInputStream in = new FileInputStream(file);*/

        /** * 使用web应用下加载资源文件的方法 */
        /** * 1. getRealPath读取,返回资源文件的绝对路径 */
        /*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() 得到资源文件,返回的是输入流 */
        InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");


        Properties prop = new Properties();
        //读取资源文件
        prop.load(in);

        String user = prop.getProperty("user");
        String password = prop.getProperty("password");
        System.out.println("user="+user);
        System.out.println("password="+password);

    }

}

你可能感兴趣的:(Path,Web应用)