web应用中路径问题
/**
目标资源:target.html
思考:目标资源是给谁用的
给服务器使用的:/表示在当前web应用的根目录
给浏览器使用的:/表示在webapps的根目录下
*/
代码片
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>");
}
}
转发和请求重定向的区别
/**
1)转发
a)地址栏不会改变
b)转发只能转到当前web应用内的资源
c)可以在转发过程中,可以把数据保存到request
2)请求重定向
a)地址栏会改变,变成重定向的地址
b)重定向可以跳转到当前web应用,也可以是其他web应用,也可以是外部域名网站
c)不能在重定向的过程,把数据保存到request中
//结论:如果要使用request域对象进行数据共享,只能用转发技术
*/
读取web应用下的资源文件
/**
读取文件。在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");
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+"password:"+password);