Java-Request

Posted 东血

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java-Request相关的知识,希望对你有一定的参考价值。

1.Request

1.1 request对象和response对象的原理(了解)

  1. request对象和response对象是由服务器创建的,我们来使用他们即可
  2. request对象是用来回去请求信息,得到页面的请求,response对象是来设置响应消息,可以往页面传输写入数据

1.2 request对象继承体系结构(了解)

ServletRequest --接口
|继承
HttpServletRequest --接口
|实现
org.apache.catalina.connector.RequestFacade 类(Tomcat)

代码如下

package cn.itcast.web.servlet;

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({"/d4","/dd4","/ddd4","/demo4"})
//@WebServlet("/user/demo4")
//@WebServlet("*.do")
//*是指通配符
public class ServletDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("demo4.....");
        System.out.println(req);
    }
}

2.request获取请求消息

2.1 获取请求行数据

  • GET/day14/demo1?name=zhangsan HTTP/1.1
  • 方法:
  1. 获取请求方式:GET
    • String getMethod()
  2. (*)获取虚拟目录:/day14
    • String getContextPath()
  3. 获取Servlet路径:/demo1
    *String getServletPath()
  4. 获取get方式请求参数:name=zhangsan
    • String getQueryString()
  5. (*)获取请求url:/day14/demo1
  6. 获取协议及版本:HTTP/1.1
    • String getPortocol()
  7. 获取客户机的IP地址
    • String getRemoteAddr()

代码如下

package cn.itcast.web.request;

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;

/**
* 演示request对象获取请求行数据
*/
@WebServlet("/requestDemo1")
public class RequestDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
        1.获取请求方式:GET
        * String getMethod()
        2.(*)获取虚拟目录:/day14
        * String getContextPath()
        3.获取Servlet路径:/demo1
        *String getServletPath()
        4.获取get方式请求参数:name=zhangsan
        * String getQueryString()
        5.(*)获取请求url:/day14/demo1
        * String getRequestURI()   /day14/demo1l
        * StringBuffer getRequestURL()  :http://localhost/day14/demo1
        6.获取协议及版本:HTTP/1.1
        * String getPortocol()
        7.获取客户机的IP地址
        * String getRemoteAddr()
        */
        //1.获取请求方式:GET
        String method=request.getMethod();
        System.out.println(method);
        //2.(*)获取虚拟目录:/day14
        String contextPath=request.getContextPath();
        System.out.println(contextPath);
        //3.获取Servlet路径:/demo1
        String servletPath=request.getServletPath();
        System.out.println(servletPath);
        //4.获取get方式请求参数:name=zhangsan
        String queryString =request.getQueryString();
        System.out.println(queryString);
        // 5.(*)获取请求url:/day14/demo1
        String requestURI =request.getRequestURI();
        StringBuffer requestURL=request.getRequestURL();
        System.out.println(requestURI);
        System.out.println(requestURL);
        // 6.获取协议及版本:HTTP/1.1
        String protocol=request.getProtocol();
        System.out.println(protocol);
        // 7.获取客户机的IP地址
        String remoteAddr=request.getRemoteAddr();
        System.out.println(remoteAddr);
    }
}

2.2 获取请求头数据

  • 方法
    • (*)String getHeader(String name):通过请求头的名称获取请求头的值

代码如下

package cn.itcast.web.request;

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.util.Enumeration;

@WebServlet("/RequestDemo2")
public class RequestDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //演示请求头数据
        //1.获取所有请求头名称
        Enumeration<String> headerNames=request.getHeaderNames();
        //2.遍历
        while(headerNames.hasMoreElements()){
            String name=headerNames.nextElement();
            //根据名称获取请求头的值
            String value=request.getHeader(name);
            System.out.println(name+"---"+value);
        }
    }
}
  • Enumeration getHeaderName():获取所有的请求头名称

代码如下

package cn.itcast.web.request;

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("/RequestDemo3")
public class RequestDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //演示请求头数据
//        String agent=request.getHeader("user-agent");
//        //判断agent的浏览器版本
//        if(agent.contains("Chorme")){
//            //谷歌
//            System.out.println("谷歌来了.....");
//        }else if(agent.contains("Firefox")){
//            //火狐
//            System.out.println("火狐来了.....");
//        }
        //演示请求头数据 referer
        String referer = request.getHeader("referer");
        System.out.println(referer);
        //防盗链
        if (referer != null) {
            if (referer.contains("/04_Request_war_exploded")) {
                //正常访问
                // System.out.println("播放电影");
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("播放电影....");
            } else {
                //    盗链
                // System.out.println("想看电影么,来......");
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("想看电影么,来......");
            }
        }
    }
}

2.3 获取请求体数据

  • 请求体:只有post请求方式,才有请求体,在请求体中封装了post请求的请求参数
  • 步骤
    1. 获取流对象
    • BufferedReader getReader():获取字符输入流 只能操作字符数据
    • ServletInputStream getInputStream():获取字节输入流 可以操作所有类型数据
    1. 再从流对象中拿数据

代码如下

-------------------------页面----------------------
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/04_Request_war_exploded/RequestDemo5" method="post">
    <input type="text" placeholder="请输入用户名" name="username"><br>
    <input type="text" placeholder="请输入密码" name="password"><br>
    <input type="submit" value="注册">
</form>
</body>
</html>
-------------------------java--------------------
package cn.itcast.web.request;

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.BufferedReader;
import java.io.IOException;

@WebServlet("/RequestDemo5")
public class RequestDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求消息体--请求参数
        // 1.获取字符流
        BufferedReader br = request.getReader();
        // 2.读取数据
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

3.request其他功能

3.1 获取请求参数通用方式 不论get还是post请求方式都可以使用下列方法来获取请求参数

  1. String getParameter(String name):根据参数名称获取参数值 username=zs&password=123
  2. String[] getParameterValues(String name):根据参数名称获取参数值的数组 hobby=xx&hobby=game
  3. Enumeration getParameterNames():获取所有请求的参数名称
  4. Map<String,String[]> getParameterMap():获取所有参数的Map集合
  • 中文乱码问题
    • get方式 Tomcat8 已经将get乱码方式问题解决了
    • post方式 会乱码
      • 解决:在获取请求参数前,设置流的编码:request.setCharacterEncoding("utf-8");

代码如下

-----------------------------index.jsp------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/04_Request_war_exploded/RequestDemo6" method="get">
    <input type="text" placeholder="请输入用户名" name="username"><br>
    <input type="text" placeholder="请输入密码" name="password"><br>
    <input type="checkbox" name="hobby" value="game">游戏
    <input type="checkbox" name="hobby" value="study">学习
    <br>
    <input type="submit" value="注册">
</form>
</body>
</html>
-------------------------------java---------------------------------
package cn.itcast.web.request;

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.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet("/RequestDemo6")
public class RequestDemo6 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    post 获取请求参数
        //    根据参数名称获取参数值
        String username = request.getParameter("username");
        // System.out.println("post");
        // System.out.println(username);
        //根据参数名称获取参数值的数组
        String[] hobbies = request.getParameterValues("hobby");
        // for (String hobby : hobbies) {
        //     System.out.println(hobby);
        // }
        // 获取所有请求的参数值名称
        Enumeration<String> parameterNames = request.getParameterNames();
        // while (parameterNames.hasMoreElements()) {
        //     String name = parameterNames.nextElement();
        //     System.out.println(name);
        //     String value = request.getParameter(name);
        //     System.out.println(value);
        //     System.out.println("-----------------------------------------");
        // }
        // 获取所有参数的map集合
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 遍历
        Set<String> keyset = parameterMap.keySet();
        for (String name : keyset) {
            //获取键获取值
            String[] values = parameterMap.get(name);
            System.out.println(name);
            for (String value : values) {
                System.out.println(value);
            }
            System.out.println("---------------------------------------");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    get 获取请求参数
        // String username = request.getParameter("username");
        // System.out.println("get");
        // System.out.println(username);
        this.doPost(request, response);
    }
}

3.2 请求转发:一种在服务器内部资源跳转的方式

  1. 步骤
    1. 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatchar(String path)
    2. 使用RequestDispatcher对象来进行转发:forward(ServletRequest request,ServletResponse response)
    • 例如: request.getRequestDispatcher("/RequestDemo9").forward(request, response);
  2. 特点:
    1. 浏览器地址栏路径没有发生变化
    2. 只能转发到服务器内部资源中
    3. 转发是一次请求

3.3 共享数据

  • 域对象:一个有作用范围的对象,可以在范围内共享数据
  • request域:代表一次请求的范围,一般用于请求转发的多个资源共享中共享数据
  • 方法
    1. void setAttribute(String name,Object obj):存储数据
    • 存储数据到request域中:request.setAttribute("msg", "hello");
    1. Object getAttitude(String name):通过键获取值
    • 获取数据:Object msg = request.getAttribute("msg");
    1. void removeAttribute(String name):通过键移除键值对

转发和共享代码如下

---------------------存储转发---------------------------
package cn.itcast.web.request;

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("/RequestDemo8")
public class RequestDemo8 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo8888被访问了.....");
        //存储数据到request域中
        request.setAttribute("msg", "hello");
        //转发到demo9资源
        // RequestDispatcher requestDispatcher = request.getRequestDispatcher("/RequestDemo9");
        // requestDispatcher.forward(request, response);
        request.getRequestDispatcher("/RequestDemo9").forward(request, response);
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    get 获取请求参数
        // String username = request.getParameter("username");
        // System.out.println("get");
        // System.out.println(username);
        this.doPost(request, response);
    }
}
---------------------提取显示---------------------------
package cn.itcast.web.request;

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("/RequestDemo9")
public class RequestDemo9 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    获取数据
        Object msg = request.getAttribute("msg");
        System.out.println(msg);
        System.out.println("demo9999被访问了.....");

    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    get 获取请求参数
        // String username = request.getParameter("username");
        // System.out.println("get");
        // System.out.println(username);
        this.doPost(request, response);
    }
}

案例

  • 用户登录案例需求
    1. 编写login.html登录页面
      username&password两个输入框
    2. 使用Druid数据库连接池技术,操作mysql,day14数据库中user表
    3. 使用jdbcTemplate技术封装JDBC
    4. 登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
    5. 登录失败跳转到FailServlet展示:登录失败,用户名或密码错误

分析

  • 输入框内容用request的String getParameter(String name):根据参数名称获取参数值
  • 然后数据库里面的账号密码用集合包揽起来,之后比对与request中的数据,最后存储自己的用户昵称,然后转发到页面中

3.4 获取ServletContext

  • ServletContext getServletContext()

代码如下

package cn.itcast.web.request;

import javax.servlet.ServletContext;
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("/RequestDemo10")
public class RequestDemo10 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    获取数据
        ServletContext servletContext = request.getServletContext();
        System.out.println(servletContext);
        System.out.println("demo1010被访问了.....");

    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    get 获取请求参数
        // String username = request.getParameter("username");
        // System.out.println("get");
        // System.out.println(username);
        this.doPost(request, response);
    }
}
  1. 概念:代表整个web应用,可以和程序的容器(服务器)来通信
  2. 功能
    1. 获取MINE类型
      • MIME类型:在互联网通信过程中定义的一种文件数据类型
        • 格式 大类型/小类型 text/html image/jepg
      • 获取:String getMimeType(String file)
    2. 域对象:共享数据
      1. setAttribute(String name,Object value)
      2. getAttribute(String name)
      3. removeAttribute(String name)
      • ServletContext对象范围:所有用户所有请求的数据
    3. 获取文件的真实(服务器)路径
      1. 方法:String getRealPath(String path)
  3. 获取:
    1. 通过request对象获取
      request.getServletContext()
    2. 通过HttpServlet获取
      this.getServletContext();

4.BeanUtils工具类

  • 要求:类必须被public修饰,必须提供空参的构造器,成员变量必须使用private修饰,提供公共setter和getter
  • 功能:封装数据
  • 概念:成员变量,属性:setter和getter方法截取后的产物 例如:getUsername()->Username->username
  • 方法:
    • setProperty()
    • getProperty()
    • populate(Object obj,Map map):将map集合的键值对信息,封装到对应的JavaBean对象中

代码演示

Map<String,String[]> map=req.getParameterMap()或者是一个map集合就可以
User user=new User()
BeanUtils.populate(user,map)//进行转换








以上是关于Java-Request的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板

VSCode自定义代码片段6——CSS选择器