Java网络开发(Tomcat)—— web的 请求request (post和get请求)和 响应response
在Java的Servlet技术中,我们可以通过HttpServletRequest对象获取到客户端发送的请求信息,通过HttpServletResponse对象设置响应信息。
- GET请求
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String value = request.getParameter("key");
// 处理请求并设置响应
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Received GET request with key: " + value + "</h1>");
}
- POST请求
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取请求体中的数据
ServletInputStream inputStream = request.getInputStream();
String line;
StringBuilder content = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = reader.readLine()) != null) {
content.append(line);
}
String value = content.toString();
// 处理请求并设置响应
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Received POST request with key: " + value + "</h1>");
}
以上代码都是在Servlet的doGet和doPost方法中编写的,这是处理HTTP GET和POST请求的基本方式。在实际开发中,我们还会涉及到更复杂的情况,比如参数绑定、文件上传、异常处理等,但基本的请求处理和响应设置就是这样。
评论已关闭