码迷,mamicode.com
首页 > Web开发 > 详细

Web应用的路径问题

时间:2016-09-17 23:30:57      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

1.总结:只有转发不用写项目的路径,其他都要!

/**
 * 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的根目录下,必须要加上项目路径,即 /day09= this.getServletContext().getContextPath();
		 */
		/**
		 * 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>");
	}

}

  2.路径二: 假如db.properties在src目录下,或者与src平行的resource folder里面的db.propertites也是一样

/**
 * 读取web应用下的资源文件(例如properties)
 * @author APPle
 */
public class ResourceDemo extends HttpServlet {//读取web应用下的资源文件(例如properties)

	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读取,返回资源文件的绝对路径  假如db.properties在src目录下
		 */
		/*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);
		
	}

}

  

Web应用的路径问题

标签:

原文地址:http://www.cnblogs.com/bravolove/p/5879865.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!