Java中常见几个路径问题

来源:互联网 发布:阿里云代备案系统 编辑:程序博客网 时间:2024/04/29 16:52

java、servlet、jsp等等,有许多路径问题,简单总结了几个:

一:getClassLoader()的到类加载器,在bin目录下

一般在DOM4j或JDOM中用到:其中exam.xml文件需要放在项目的bin目录下

SAXBuilder builder = new SAXBuilder();
 String  filepath=xmutils.class.getClassLoader().getResource("exam.xml").getPath();
//  filepath=filepath.replace("%20", " ");这句是空格变成%20,一般路径尽量不要加空格
  Document doc = builder.build(new File(filepath));

二:在EL或JSTL表达式中:

${pageContext.request.contextPath }//获得当前项目名字,这个获得的路径前面自带 /

三:在servlet或jsp中request.getContextPath()获得当前项目名字,这个获得的路径前面自带 /:

假如web.xml配置的servlet是:

<servlet-mapping>
    <servlet-name>ListCartServlet</servlet-name>
    <url-pattern>/servlet/listcartServlet</url-pattern>
  </servlet-mapping>

那么在重定向时可以这样获得当前应用的路径:

request.getContextPath()这个获得的路径前面自带 /

response.sendRedirect(request.getContextPath()+"/servlet/listcartServlet"); 

四:

request.getRequestURI(); //          得到的URI是:   / 当前应用的名字 / web.xml中<url-pattern>

 request.getRequestURL(); //     得到的URL是: http://localhost:8080/HelloServlet/servlet/requestDemo1

 

五:getServletContext()得到项目下webroot/

String path=this.getServletContext().getRealPath("/download/新图片.jpg"); 

  String filename=path.substring(path.lastIndexOf("\\")+1);      //获得新图片.jpg

InputStream in=null;
  OutputStream out=null;
  //如果下载文件是中文文件,则文件名需要经过url编码
  response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
  try {
   in=new FileInputStream(path);
   int len=0;
   byte buffer[]=new byte[1024];
   out=response.getOutputStream();
   while((len=in.read(buffer))>0){
    out.write(buffer,0,len);
   }
  }finally{
   if(in!=null){
    try{
     
     in.close();
    }catch(Exception e){
     e.printStackTrace();
    }    
   }

六:getServletContext()得到项目下webroot/

例如:

InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");//getServletContext()得到项目下webroot/
  Properties props=new Properties();
  props.load(in);
  System.out.println(props.getProperty("url"));

原创粉丝点击