Servlet接收Post请求以及回复请求

本文主要介绍了Servlet如何接受HttpCilent发送过来的请求以及对请求进行回复

Servlet需要用到Servlet-api.jar包

package com.firstdata.project;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.ListIterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Test {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String origRequestMsg = null;
        byte[] reqBuf = null;
        try {
            InputStream is = req.getInputStream();
            reqBuf = readInputBytes(is);
            origRequestMsg = new String(reqBuf, "GBK");
            System.out.println(origRequestMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 出来完收到信息之后可以就可以回复请求了

        try {
            OutputStream os = res.getOutputStream();
            String resMsgOut = "this is response message";
            os.write(resMsgOut.getBytes("GBK"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * reads input stream passed and populates bytes
     * 
     * @param is
     * InputStream
     * @return byte[]
     * @throws IOException
     */
    private byte[] readInputBytes(InputStream is) throws IOException {
        ArrayList<ByteCountObj> inputByteList = new ArrayList<ByteCountObj>();
        byte[] inBuf = new byte[2000];
        int coutRead = is.read(inBuf);
        while (coutRead != -1) {
            ByteCountObj obj = new ByteCountObj(inBuf, coutRead);
            inputByteList.add(obj);
            inBuf = new byte[2000];
            coutRead = is.read(inBuf);
        }

        coutRead = 0;
        ListIterator<ByteCountObj> it = inputByteList.listIterator();
        while (it.hasNext()) {
            ByteCountObj ob = it.next();
            coutRead += ob.getByteCount();
        }

        ByteBuffer byteBuf = ByteBuffer.allocate(coutRead);
        it = inputByteList.listIterator();
        while (it.hasNext()) {
            ByteCountObj ob = it.next();
            coutRead = ob.getByteCount();
            inBuf = ob.getByteBuf();
            byteBuf.put(inBuf, 0, coutRead);
        }
        if (byteBuf.hasArray()) {
            return byteBuf.array();
        } else {
            return null;
        }
    }

    /**
     * 用来储存获取到的byte[]以及字节流的长度
     * 
     * @author
     * 
     */
    public class ByteCountObj {

        private byte[] byteBuf;

        private int byteCount;

        public byte[] getByteBuf() {
            return byteBuf;
        }

        public int getByteCount() {
            return byteCount;
        }

        public ByteCountObj(byte[] byteBuf, int byteCount) {
            this.byteBuf = byteBuf;
            this.byteCount = byteCount;
        }
    }
}


Servlet中,处理HTTP POST请求中的`MultipartFile`通常涉及到文件上传功能。`MultipartFile`是Spring MVC提供的一个模型属性,用于存储上传的文件。以下是使用Spring MVC处理POST请求接收文件的基本步骤: 1. 首先,你需要在Servlet的Web配置中启用Multipart resolver,例如添加到`web.xml`或`application.properties`中: ```xml <!-- web.xml --> <filter> <filter-name>multipartFilter</filter-name> <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class> </filter> ... <filter-mapping> <filter-name>multipartFilter</filter-name> <url-pattern>/upload/*</url-pattern> </filter-mapping> // application.properties spring.servlet.multipart.enabled=true ``` 2. 接收请求时,在Servlet或Controller中,使用`@RequestParam`从请求中获取`MultipartFile`: ```java import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file, Model model) { // 检查文件是否有效 if (file.isEmpty()) { return "error"; } // 将文件名保存到Model或者其他地方 model.addAttribute("fileName", file.getOriginalFilename()); try { // 将文件保存到服务器某个位置 saveUploadedFile(file); } catch (Exception e) { // 处理文件保存错误 return "error"; } return "success"; // 返回成功页面 } private void saveUploadedFile(MultipartFile file) throws IOException { // 将file的内容写入磁盘或其他持久化存储 file.transferTo(new File("path/to/save/" + file.getOriginalFilename())); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值