Java 如何从httpservletrequest获取多端口

Java 如何从httpservletrequest获取多端口,java,web-services,spring,apache,tomcat,Java,Web Services,Spring,Apache,Tomcat,我正在尝试从JavaSpring控制器调用webservice。下面是代码 private void storeImages(MultipartHttpServletRequest multipartRequest) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost( "http://localhost:

我正在尝试从JavaSpring控制器调用webservice。下面是代码

private void storeImages(MultipartHttpServletRequest multipartRequest) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(
                    "http://localhost:8080/dream/storeimages.htm");
    MultipartFile multipartFile1 = multipartRequest.getFile("file1");
    MultipartEntity multipartEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntity.addPart("file1",
                    new ByteArrayBody(multipartFile1.getBytes(),
                                    multipartFile1.getContentType(),
                                    multipartFile1.getOriginalFilename()));
    postRequest.setEntity(multipartEntity);
    HttpResponse response = httpClient.execute(postRequest);
    if (response.getStatusLine().getStatusCode() != 201) {
        throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusLine().getStatusCode());
    }
}
以上只是部分代码。我正在尝试确定如何在服务器端检索此文件。在服务器端,我有以下Spring控制器代码

@RequestMapping(value = "/storeimages.htm", method = RequestMethod.POST)
public ModelAndView postItem(HttpServletRequest request,
                HttpServletResponse response) {
    logger.info("Inside /secure/additem/postitem.htm");
    try {
        // How to get the MultipartEntity object here. More specifically i
        // want to get back the Byte array from it
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new ModelAndView("success");
}
我执行了这段代码,控制权转到服务器端。但是我一直在研究如何从multipartentity对象中获取字节数组

编辑要求:
这是要求。用户从网站上传图像(完成并工作)表单提交后,控件转到Spring控制器(完成并工作)。在Spring控制器中,我使用Multipart获取表单内容。(这已经完成并且正在工作)现在我想调用一个webservices,它将图像字节数组发送到图像服务器。(这需要完成)在图像服务器上,我想接收这个webservice请求从HTTPServlerRequest获取所有字段,存储图像并返回(这需要完成)

在我的项目中,我们曾经使用from com.oreilly.servlets来处理
HttpServletRequests
对应于
multipart
请求,如下所示:

// Should be able to handle multipart requests upto 1GB size.
MultipartParser parser = new MultipartParser(aReq, 1024 * 1024 * 1024);
// If the content type is not multipart/form-data, this will be null.
if (parser != null) {
    Part part;
    while ((part = parser.readNextPart()) != null) {
        if (part instanceof FilePart) {
            // This is an attachment or an uploaded file.
        }
        else if (part instanceof ParamPart) {
            // This is request parameter from the query string
        }
    }
}
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

希望这有帮助。

您可以使用Springs Mutlipart支持,而不是手动完成所有这些操作

控制器可以这样工作(本例使用命令对象存储额外的用户输入--(这是一个工作项目的示例))

要启用Spring多部分支持,您需要配置一些东西:

web.xml(在CharacterEncodingFilter之后和HttpMethodFilter之前添加org.springframework.web.multipart.support.MultipartFilter)


多部件滤波器
org.springframework.web.multipart.support.MultipartFilter
多部件滤波器
/*
在应用程序核心(不是MVCServlet)的Spring配置中添加以下内容

<!-- allows for integration of file upload functionality, used by an filter configured in the web.xml -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="filterMultipartResolver" name="filterMultipartResolver">
     <property name="maxUploadSize" value="100000000"/>
</bean>

然后还需要commons fileupload库,因为Spring MultipartFile只是一种Addapter

<dependency>
     <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.1</version>
</dependency>

文件上传

终于解决了。这是对我有用的东西

客户端

private void storeImages(HashMap<String, MultipartFile> imageList) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://localhost:8080/dream/storeimages.htm");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        Set set = imageList.entrySet(); 
        Iterator i = set.iterator(); 
        while(i.hasNext()) { 
            Map.Entry me = (Map.Entry)i.next(); 
            String fileName = (String)me.getKey();
            MultipartFile multipartFile = (MultipartFile)me.getValue();
            multipartEntity.addPart(fileName, new ByteArrayBody(multipartFile.getBytes(), 
                    multipartFile.getContentType(), multipartFile.getOriginalFilename()));
        } 
        postRequest.setEntity(multipartEntity);
        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        while ((output = br.readLine()) != null) {
            logger.info("Webservices output - " + output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private void-storeImages(HashMap-imageList){
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPostRequest=新的HttpPost(“http://localhost:8080/dream/storeimages.htm");
MultipartEntity MultipartEntity=新的MultipartEntity(HttpMultipartMode.BROWSER_兼容);
Set=imageList.entrySet();
迭代器i=set.Iterator();
而(i.hasNext()){
Map.Entry me=(Map.Entry)i.next();
字符串文件名=(字符串)me.getKey();
MultipartFile MultipartFile=(MultipartFile)me.getValue();
multipartEntity.addPart(文件名,新的ByteArrayBody(multipartFile.getBytes(),
multipartFile.getContentType(),multipartFile.getOriginalFilename());
} 
postRequest.setEntity(多方实体);
HttpResponse response=httpClient.execute(postRequest);
如果(response.getStatusLine().getStatusCode()!=200){
抛出新的RuntimeException(“失败:HTTP错误代码:”
+response.getStatusLine().getStatusCode());
}
BufferedReader br=新的BufferedReader(新的InputStreamReader((response.getEntity().getContent()));
字符串输出;
而((output=br.readLine())!=null){
info(“Webservices输出-”+输出);
}
httpClient.getConnectionManager().shutdown();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
服务器端

@RequestMapping(value = "/storeimages.htm", method = RequestMethod.POST)
public void storeimages(HttpServletRequest request, HttpServletResponse response)
{
    logger.info("Inside /secure/additem/postitem.htm");
    try
    {
        //List<Part> formData = new ArrayList(request.getParts());
        //Part part = formData.get(0);
        //Part part = request.getPart("file1");
        //String parameterName = part.getName();
        //logger.info("STORC IMAGES - " + parameterName);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        Set set = multipartRequest.getFileMap().entrySet(); 
        Iterator i = set.iterator(); 
        while(i.hasNext()) { 
            Map.Entry me = (Map.Entry)i.next(); 
            String fileName = (String)me.getKey();
            MultipartFile multipartFile = (MultipartFile)me.getValue();
            logger.info("Original fileName - " + multipartFile.getOriginalFilename());
            logger.info("fileName - " + fileName);
            writeToDisk(fileName, multipartFile);
        } 
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

public void writeToDisk(String filename, MultipartFile multipartFile)
{
    try
    {
        String fullFileName = Configuration.getProperty("ImageDirectory") + filename;
        FileOutputStream fos = new FileOutputStream(fullFileName);
        fos.write(multipartFile.getBytes());
        fos.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
@RequestMapping(value=“/storeimages.htm”,method=RequestMethod.POST)
公共void存储映像(HttpServletRequest请求、HttpServletResponse响应)
{
logger.info(“Inside/secure/additem/positem.htm”);
尝试
{
//List formData=newarraylist(request.getParts());
//Part Part=formData.get(0);
//Part Part=request.getPart(“file1”);
//字符串参数name=part.getName();
//logger.info(“STORC图像-”+参数名);
MultipartTTpServletRequest multipartRequest=(MultipartTTpServletRequest)请求;
Set=multipartRequest.getFileMap().entrySet();
迭代器i=set.Iterator();
而(i.hasNext()){
Map.Entry me=(Map.Entry)i.next();
字符串文件名=(字符串)me.getKey();
MultipartFile MultipartFile=(MultipartFile)me.getValue();
logger.info(“原始文件名-”+multipartFile.getOriginalFilename());
logger.info(“文件名-”+文件名);
writeToDisk(文件名,多部分文件);
} 
}
捕获(例外情况除外)
{
例如printStackTrace();
}
}
public void writeToDisk(字符串文件名,MultipartFile MultipartFile)
{
尝试
{
字符串fullFileName=Configuration.getProperty(“ImageDirectory”)+文件名;
FileOutputStream fos=新的FileOutputStream(fullFileName);
写入(multipartFile.getBytes());
fos.close();
}
捕获(例外情况除外)
{
例如printStackTrace();
}
}

处理控制器的spring文件。您需要在app-config.xml中指出以下内容:

// Should be able to handle multipart requests upto 1GB size.
MultipartParser parser = new MultipartParser(aReq, 1024 * 1024 * 1024);
// If the content type is not multipart/form-data, this will be null.
if (parser != null) {
    Part part;
    while ((part = parser.readNextPart()) != null) {
        if (part instanceof FilePart) {
            // This is an attachment or an uploaded file.
        }
        else if (part instanceof ParamPart) {
            // This is request parameter from the query string
        }
    }
}
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
这是红色多部分的

private File getFile(MultipartFile file) {

    try {
        File fichero = new File(file.getOriginalFilename());
        fichero.createNewFile();
        FileOutputStream fos = new FileOutputStream(fichero);
        fos.write(file.getBytes());
        fos.close();
        return fichero;
    } catch (Exception e) {
        return null;
    }

}

我希望这会有所帮助。

您的目标是什么Servlet版本?由于servlet 3.0 HttpServletRequest有一个方法,可以随后用于获取InputStream。如何检查我是否使用servlet 3.0。我正在使用Tomcat7。我试过写这篇文章,但似乎不起作用。列表大小为0。List formData=newarraylist(request.getParts());Part Part=formData.get(0);字符串参数name=part.getName();logger.info(“STORC图像-”+参数名)@user1241438ÖTomcat 7是我网站上的Servlet 3.0容器
private File getFile(MultipartFile file) {

    try {
        File fichero = new File(file.getOriginalFilename());
        fichero.createNewFile();
        FileOutputStream fos = new FileOutputStream(fichero);
        fos.write(file.getBytes());
        fos.close();
        return fichero;
    } catch (Exception e) {
        return null;
    }

}