您好,欢迎访问代理记账网站
移动应用 微信公众号 联系我们

咨询热线 -

电话 15988168888

联系客服
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

Javaweb--JavaWeb--tomcat之HttpServlet使用详解,HttpServletRequest与HttpServletResponse

目录

    • 一、通过HttpServletRequest对象 获取请求的信息
      • 1.代码获取请求信息
      • 2.获取post请求的表单数据
    • 二、通过HttpServletRequest对象实现请求转发
    • 三、通过HttpServletResponse对象实现服务器响应
    • 四、通过HttpServletResponse对象实现请求重定向
    • 五、本文配置的web.xml

一、通过HttpServletRequest对象 获取请求的信息

通过doGet或doPost方法的第一个参数(HttpServletRequest对象)获取请求信息

1.代码获取请求信息

package com.my.servlet;

import java.io.IOException;
import java.util.Enumeration;

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

public class SrcHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGetting");
        System.out.println("req.getRequestURI---"+req.getRequestURI());
        System.out.println("req.getRequestURL---"+req.getRequestURL());
        System.out.println("req.getRemoteHost---"+req.getRemoteHost());
        System.out.println("req.getRemoteAddr---"+req.getRemoteAddr());
        System.out.println("req.getMethod---"+req.getMethod());
        System.out.println("=====================遍历获取请求头的内容=====================");
        System.out.println("req.getHeader---"+req.getHeader("User-Agent"));
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String s = headerNames.nextElement();
            String value = req.getHeader(s);
            System.out.println(s+"----"+value);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPosting,获取表单数据");
        req.setCharacterEncoding("utf-8"); // 设置编码格式,防止中文乱码
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String s = parameterNames.nextElement();
            String value = req.getParameter(s);
            System.out.println(s+"----"+value);
        }
    }
}

浏览器访问http://localhost:8080/default/shs后返回:

doGetting
req.getRequestURI---/default/shs
req.getRequestURL---http://localhost:8080/default/shs
req.getRemoteHost---0:0:0:0:0:0:0:1
req.getRemoteAddr---0:0:0:0:0:0:0:1
req.getMethod---GET
=====================遍历获取请求头的内容=====================
req.getHeader---Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36
host----127.0.0.1:8080
connection----keep-alive
pragma----no-cache
cache-control----no-cache
sec-ch-ua----" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"
sec-ch-ua-mobile----?1
upgrade-insecure-requests----1
user-agent----Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36
accept----text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
sec-fetch-site----none
sec-fetch-mode----navigate
sec-fetch-user----?1
sec-fetch-dest----document
accept-encoding----gzip, deflate, br
accept-language----zh-CN,zh;q=0.9

2.获取post请求的表单数据

使用html如下:放在web目录下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8080/default/shs" method="post">
    <input type="text" name="userName"/><br/>
    <input type="password" name="password"/><br/>
    <input type="submit" value="getBtn" />
</form>
</body>
</html>

浏览器访问http://localhost:8080/default/myHtml.html,点击[getBtn]按钮
在这里插入图片描述
控制台返回:

doPosting,获取表单数据
userName----yunweixiaocai
password----ywxc1234

二、通过HttpServletRequest对象实现请求转发

  • 使用请求对象的.getRequestDispatcher()方法获取 请求转发实例
  • 使用实例的forward()方法执行转发

SrcHttpServlet .java:

package com.my.servlet;

import java.io.IOException;

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

public class SrcHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("SrcHttpServlet do get");
        String userName = req.getParameter("UserName"); // 获取请求参数(URL中的参数)
        System.out.println("SrcHttpServlet "+userName);

        req.setAttribute("stats","pass"); // 设置全局参数供目标servlet获取使用

        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/dhs"); // 请求转发实例,目标servlet为/dhs(DestHttpServlet)
        requestDispatcher.forward(req, resp); // 执行转发,携带原来的req与resp
    }
}

DestHttpServlet .java

package com.my.servlet;

import java.io.IOException;

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

public class DestHttpServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("DestHttpServlet do get");
        String userName = request.getParameter("UserName"); // 获取初始参数(url中的参数)
        System.out.println("DestHttpServlet "+userName);

        Object stats = request.getAttribute("stats"); // 获取转发者设置的全局参数
        System.out.println("DestHttpServlet "+stats);

        System.out.println("DestHttpServlet do other things...");
    }
}

浏览器访问:http://localhost:8080/default/shs?UserName=yunweixiaocai,加粗部分为携带的参数
控制台返回:

SrcHttpServlet do get
SrcHttpServlet yunweixiaocai
DestHttpServlet do get
DestHttpServlet yunweixiaocai
DestHttpServlet pass
DestHttpServlet do other things...

浏览器只有一个请求,不感知跳转
在这里插入图片描述

三、通过HttpServletResponse对象实现服务器响应

HttpServletResponse有两个响应流可以直接通过对象获取

  • PrintWriter流可实现文本响应:resp.getWriter();
  • ServletOutputStream流可实现文件传输: resp.getOutputStream();
    .

tips:一个响应里,两个流只能使用一个

package com.my.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

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

public class SrcHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 两种响应流只能使用一个,不然会报错

        // 一、实现文本响应,先设置编码再获取流
        //1.设置字符编码,方式一:分步设置
        //resp.setCharacterEncoding("utf-8");// 设置服务器编码为utf-8
        //resp.setHeader("Content-Type","text/html; charset=utf-8"); // 设置浏览器字符编码为utf-8
        //方式二:一步到位
        //resp.setContentType("text/html; charset=utf-8");

        /*PrintWriter writer = resp.getWriter();
        writer.write("This is response content. 这是响应内容");*/



        // 二、实现文件下载,先设值内容格式,再获取流
        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-Disposition", "attachment; filename=test.avi");

        ServletOutputStream outputStream = resp.getOutputStream();
        File file = new File("d:\\test.avi");
        FileInputStream fis = new FileInputStream(file);

        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fis.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
    }
}

四、通过HttpServletResponse对象实现请求重定向

请求重定向是指,访问一个servlet时跳转到另一个servlet,实现两次请求(第二次请求自动实现)

SrcHttpServlet中:

package com.my.servlet;

import java.io.IOException;

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

public class SrcHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*resp.setStatus(302);
        resp.setHeader("Location","http://localhost:8080/default/dhs");*/

        // 或者
        resp.sendRedirect("/default/dhs");

    }
}

DestHttpServlet中:

package com.my.servlet;

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

public class DestHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("srcHttpServlet's content");
    }
}

浏览器输入SrcHttpServlet映射的url:http://localhost:8080/default/shs后自动跳转到DestHttpServlet映射的url:http://localhost:8080/default/dhs:
在这里插入图片描述

五、本文配置的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>srcHttpServlet</servlet-name>
        <servlet-class>com.my.servlet.SrcHttpServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>destHttpServlet</servlet-name>
        <servlet-class>com.my.servlet.DestHttpServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>srcHttpServlet</servlet-name>
        <url-pattern>/shs</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>destHttpServlet</servlet-name>
        <url-pattern>/dhs</url-pattern>
    </servlet-mapping>

</web-app>


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进