main函数加载jetty,及java请求url

本文介绍了一个简单的Servlet示例,通过POST方法接收客户端发送的数据,并原样返回。使用Jetty服务器进行部署,展示了从客户端发送数据到服务器处理再到响应的完整过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建立servlet处理请求
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    InputStream s=request.getInputStream();
    String a="";
    BufferedReader reader=new BufferedReader(new InputStreamReader(s));
    String str;
    while ((str = reader.readLine()) != null){
        System.out.println(str);
        a=str;
    }
    reader.close();
    response.getWriter().write(a);
}
客户端代码
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    String host="http://localhost:8080/test/hello";
    HttpURLConnection conn;
    try {
        URL url=new URL(host);
        conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        String hello=URLEncoder.encode("hello", "utf-8");
        out.writeBytes(hello);
        out.flush();
        out.close(); 
        InputStream in=conn.getInputStream();
        BufferedReader reader=new BufferedReader(new InputStreamReader(in));
        String str;
        while ((str = reader.readLine()) != null){
            System.out.println(str);
        }
        reader.close();
        conn.disconnect();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

加载jetty及webxml设置端口
public static void main(String[] args) {
// TODO Auto-generated method stub
Server server=new Server(8080);
WebAppContext context = new WebAppContext();
context.setDescriptor(“E:/work/test/src/main/webapp/WEB-INF/web.xml”);
context.setResourceBase(“E:/work/test/src/main/webapp”);
context.setContextPath(“/test”);
context.setParentLoaderPriority(true);
server.setHandler(context);
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值