tomcat映射web路径

来源:互联网 发布:药品集中采购系统sql 编辑:程序博客网 时间:2024/06/06 17:19
tomcat映射web工程:将web工程映射到tomcat中,即为web工程设置虚拟目录,这样就不需要再将项目部署到tomcat的webapps目录下就可以访问.


应用场景:在一些系统中,我们经常需要为客户端提供一些文件资源,例如:文档,图片等供客户端下载.
然而,当我们有遍历web工程上资源路径的需求时,web工程却不支持遍历(出于安全考虑,如果可以遍历,说明web工程有漏洞,可以网上查找相关资料),
这时,我们就可以通过tomcat映射web工程的方式实现,将项目部署到tomcat后,从webapps目录下拷贝到某个绝对路径下,然后通过配置文件进行关联.


实现方式:通过配置文件实现,将配置文件放到%TOMCAT_HOME%\conf\Catalina\localhost目录下,
配置详解:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/tomcat-mapping" docBase="D:\\test\\tomcat-mapping" reloadbale="true"></Context>
path属性设置上下文目录,即项目名称.
docBase属性设置项目的虚拟目录,即映射路径,一般设置成绝对路径.
reloadable属性设置资源文件修改时重新加载源文件.
tomcat启动时会自动读取该映射文件,并自动部署工程.


另外,配置文件的名称必须和项目的名称一样.


启动tomcat后,这时当我们访问http://localhost:8080/tomcat-mapping路径下的资源时,其实是访问D:\\test\\tomcat-mapping路径下的资源.


本实例简单实现了下载服务器上的资源文件和jsp页面测试.

package com.ilucky.util.tomcat.mapping;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.methods.GetMethod;/** * 下载服务器上的资源文件. * @author IluckySi * @since 20141110 */public class HttpClientTest {public static void main(String[] args) {HttpClient client = new HttpClient();GetMethod getMethod = new GetMethod("http://localhost:8080/tomcat-mapping/resource/ilucky.zip");InputStream is = null;FileOutputStream fos = null;BufferedOutputStream bos = null;try {client.executeMethod(getMethod);is = getMethod.getResponseBodyAsStream();fos = new FileOutputStream(new File("E:\\ilucky.zip"));bos = new BufferedOutputStream(fos);byte[] byteArray = new byte[1024];int length = 0;while ((length = is.read(byteArray)) != -1) {bos.write(byteArray, 0, length);}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {getMethod.releaseConnection();try {if (is != null) {is.close();is = null;}if (bos != null) {bos.close();bos = null;}if (fos != null) {fos.close();fos = null;}} catch (Exception e) {e.printStackTrace();}}}}


0 0