源码(三) - RequestContext和ServletRequestContext

一.概述

1.一个servlet上传文件,构造参数为HttpServletRequest,可以通过此参数获取请求信息
  • 获取上传文件的编码类型:如UTF-8
  • 获取上传文件的内容类型:servlet上传文件以"multipart/"开始
  • 获取上传文件的大小
  • 获取上传文件的输入流

二.RequestContext

抽象访问文件上传所需的请求信息。


// 1.2.1
package org.apache.commons.fileupload;

import java.io.InputStream;
import java.io.IOException;

/**
 * 抽象访问文件上传所需的请求信息。 
 * 对于可以由FileUpload处理的每种类型的请求(如servlet和portlet),都应该实现这种互操作。
 *
 * @since FileUpload 1.1
 */
public interface RequestContext {

    /**
     * 返回请求的字符编码。
     * @return The character encoding for the request.
     */
    String getCharacterEncoding();

    /**
     * 获取请求的内容类型。
     * @return The content type of the request.
     */
    String getContentType();

    /**
     * 获取请求的内容长度。
     * @return The content length of the request.
     */
    int getContentLength();

    /**
     * 获取请求的输入流。
     * @return The input stream for the request.
     * @throws IOException if a problem occurs.
     */
    InputStream getInputStream() throws IOException;
}

三.ServletRequestContext


// 1.2.1
package org.apache.commons.fileupload.servlet;

import java.io.InputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.RequestContext;

/**
 * Provides access to the request information needed for a request made to an HTTP servlet.
 *
 * 提供对HTTP servlet请求所需的请求信息的访问。
 *
 * @since FileUpload 1.1
 *
 */
public class ServletRequestContext implements RequestContext {
    /**
     * The request for which the context is being provided.
	 * 提供上下文的请求。
     */
    private HttpServletRequest request;

    /**
     * Construct a context for this request.
     * @param request The request to which this context applies.
     */
    public ServletRequestContext(HttpServletRequest request) {
        this.request = request;
    }

    public String getCharacterEncoding() {
        return request.getCharacterEncoding();
    }

    public String getContentType() {
        return request.getContentType();
    }

    public int getContentLength() {
        return request.getContentLength();
    }

    /**
     * 从请求对象中获取上传文件的输入流
     *
     */
    public InputStream getInputStream() throws IOException {
        return request.getInputStream();
    }

    public String toString() {
        return "ContentLength=" + this.getContentLength() + ", ContentType=" + this.getContentType();
    }
}

3.一个实例截图











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值