Request获取请求数据

Request获取请求行数据

同时支持GET请求和POST请求

  1. 获取请求方法:
String method = req.getMethod();
  1. 获取虚拟目录

    String contextPath = req.getContextPath(); 
  2. 获取URL

    StringBuffer requestURL = req.getRequestURL();
  3. 获取URI

    String requestURI = req.getRequestURI();
  4. 获取请求参数

    String queryString = req.getQueryString();
  5. 获取post方法的请求体:

    BufferedReader br = req.getReader();
    String result = br.readLine();

获取Request请求参数的通用方法

  1. 获取所有参数的map集合

    Map<String, String[]> parameterMap = req.getParameterMap();
  2. 根据名称获取参数值(数组)

    String[] names = req.getParameterValues("username");
  3. 根据名称获得参数值(单个)

    String password = req.getParameter("password");

    所以以后只需要重写DoGet方法就可以了~

@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get....");

        //获取所有参数的map集合
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<String> keySet = parameterMap.keySet();

        for (String s : keySet) {
            System.out.print(s + ":");
            String[] values = parameterMap.get(s);
            for (String value : values) {
                System.out.print(value + " ");
            }
            System.out.println();
        }

        //根据名称获取参数值(数组)
        String[] names = req.getParameterValues("username");
        System.out.println(Arrays.toString(names));

        //根据名称获得参数值(单个)
        String password = req.getParameter("password");
        System.out.println("密码是: " + password);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

解决POST方法中文参数乱码

//由于POST方法获取参数的底层是使用字符流
request.setCharacterEncoding("UTF-8");//解决了

解决GET方法中文参数乱码

//tomcat编码的时候用的是ISO_8859_1
//所以先用ISO_8859_1解码, 再用UTF-8编码
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        //解决Get乱码
        username= new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        System.out.println(username);
    }

Request请求转发

Request请求转发

  1. Request转发请求

    request.getRequestDispatcher("/req5").forward(request, response);//请求转发到req5
  2. 转发时共享数据

    //这是Req4
    @WebServlet("/req4")
    public class RequestDemo4 extends HttpServlet {
     @Override
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
         System.out.println("我在req4...");
         String msg = "我草泥马";
         request.setAttribute("msg", msg);
         request.getRequestDispatcher("/req5").forward(request, response);
    
     }
    
     @Override
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         this.doGet(request, response);
     }
    }
    
//这是Req5
@WebServlet("/req5")
public class RequestDemo5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("我已到达req5...");
        Object msg = request.getAttribute("msg");
        System.out.println(msg);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

Response

Response重定向

Response重定向

  1. 设置状态码302
  2. 在请求头设置重定向的地址
//常规方法
        //重定向
            //1.设置状态码
        response.setStatus(302);
            //2.请求头设置新地址
        response.setHeader("location", "/web-demo/resp2");

还有重定向的快捷方法

//302重定向的快速方法
response.sendRedirect("/web-demo/resp2");

虚拟目录

什么时候要加虚拟目录?

  1. 给浏览器使用: 需要加虚拟目录
  2. 服务端使用: 不需要加虚拟目录(如Request请求转发)

    动态获取虚拟目录

在maven配置文件中指定虚拟路径
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/web-demo</path>
                </configuration>
            </plugin>
        </plugins>
    </build>
然后动态获取虚拟路径
String contextPath = request.getContextPath();
response.sendRedirect(contextPath + "/resp2");

Response响应字符数据

        //让浏览器使用html进行解析
        response.setHeader("content-type", "text/html");
        //设置响应数据
        PrintWriter writer = response.getWriter();//不用手动关闭(因为是reponse对象搞出来的, 到时候会一起关掉)
        writer.write("666<h1>UNK</h1>");

当然还有更便捷的方式! 顺便解决了发送中文数据时乱码

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();//不用手动关闭
        writer.write("666<h1>傻逼黄乘明</h1>");
    }

Response响应字节数据

有时候要发送图片视频等数据 所以字节流也很重要

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //读取文件
        FileInputStream fis = new FileInputStream("C:\\Users\\nvnej\\Desktop\\捣蛋猫.png");
        //获得Response的输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //从字符输入流拷贝数据到字符输出流
        byte[] buff = new byte[1024];
        int len;
        while ((len = fis.read(buff)) != -1){
            outputStream.write(buff, 0, len);
        }
        fis.close();
    }

当然还可以使用IOUtil工具类简化copy操作...

  1. 首先需要在maven配置文件中引入这个依赖

         <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>2.6</version>
         </dependency>
  2. 然后愉快的使用工具类(注意要导阿帕奇的)

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //读取文件
         FileInputStream fis = new FileInputStream("C:\\Users\\nvnej\\Desktop\\捣蛋猫.png");
         //获得Response的输出流
         ServletOutputStream outputStream = response.getOutputStream();
         //使用io类
         IOUtils.copy(fis, outputStream);
         //关流
         fis.close();
     }