Servlet的使用

1.Servlet的含义

Servlet 是一种实现动态页面的技术. 是一组 Tomcat 提供给程序猿的 API, 帮助程序猿简单高效的开发一个 web app。

Servlet 就是 Tomcat 这个 HTTP 服务器提供给 Java 的一组 API, 来完成构建动态页面这个任务。

2.Servlet 的生命周期。

生命周期即他每个阶段需要干的事情:

Servlet每个阶段的工作:

1.开始的时候,执行init;

2.每次收到请求,执行service;

3.销毁之前,执行destroy;

一个servlet程序,里面可以包含多个servlet,某个servlet的生死,不影响整个servlet的使用;

3.代码案例

3.1显示 HttpServletRequest 的常用属性

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/showRequest")
public class showRequest extends HttpServlet {
    @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //搞个StringBuilder,把这些api的结果,统一写回到响应中StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(req.getProtocol());
        stringBuilder.append(req.getMethod());
        stringBuilder.append(req.getRequestURI());
        stringBuilder.append(req.getContextPath());
        stringBuilder.append(req.getQueryString());
        resp.getWriter().write(stringBuilder.toString());
    }
}

3.2 获取GET请求中的query string 的内容

请求形如 /message?aa=10&bb=20

在Servlet 代码中获取到 aa 和 bb 的值, 并显示在页面上

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/message")
public class GetString extends HttpServlet {
    @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aa = req.getParameter("aa");
        String bb = req.getParameter("bb");
        resp.setContentType("text/html");
        resp.getWriter().write("aa = "+aa+" bb = "+bb);
    }
}

3.3获取 POST 请求中 body 的内容 

分别实现这两种 body 格式的处理:

  1. aa=10&bb=20
  2. { "aa": 10, "bb":20}

把 aa 和 bb 的值获取到, 展示到页面上.

第一种:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/message")
public class GetString extends HttpServlet {
        @Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String aa = req.getParameter("aa");
            String bb = req.getParameter("bb");
            resp.setContentType("text/html");
            resp.getWriter().write("aa = "+aa+" classId = "+bb);
        }
    }
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head>
<body>
<!--    <form action="postParameter" method="post">-->
<!--        <input type="text" name="studentId">-->
<!--        <input type="text" name="classId">-->
<!--        <input type="submit" value="提交">-->
<!--    </form>--><form action="message" method="post"><input type="text" name="aa"><input type="text" name="bb"><input type="submit" value="提交"></form><!-- 使用这个页面来构造ajax请求 --><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>// $.ajax({//     type: 'get',
            
        //     //url: 'method',//     //绝对路径//     url:'/Hello_Servlet2/method',//     success: function(body,status){//         console.log(body);//     }// });
       
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head>
<body>
<!--    <form action="postParameter" method="post">-->
<!--        <input type="text" name="studentId">-->
<!--        <input type="text" name="classId">-->
<!--        <input type="submit" value="提交">-->
<!--    </form>--><form action="message" method="post"><input type="text" name="aa"><input type="text" name="bb"><input type="submit" value="提交"></form><!-- 使用这个页面来构造ajax请求 --><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>// $.ajax({//     type: 'get',
            
        //     //url: 'method',//     //绝对路径//     url:'/Hello_Servlet2/method',//     success: function(body,status){//         console.log(body);//     }// });
       
    </script>
</body>
</html>

第二种:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@WebServlet("/message2")
public class PostJson extends HttpServlet {
    @Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);//通过这个方法来处理body为json格式的数据//直接吧req对象里 body 完整的读取出来//getInputStream//在流对象中读多少个字节,取决于Content-length
        int length = req.getContentLength();
        byte[] buffer = new byte[length];
        InputStream inputStream = req.getInputStream();
        inputStream.read(buffer);
        //把这个字节数组构造成String,打印出来String body = new String(buffer,0,length,"utf8");
        System.out.println("body = "+body);
        //设置返回值的格式类型html
        resp.setContentType("text/html");
        resp.getWriter().write(body);
    }
}

 使用postman构造post模拟请求:


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值