zoukankan      html  css  js  c++  java
  • HttpServletRequest参数获取,HttpServletRequest详解

    --------------------------HttpServletRequest参数获取,HttpServletRequest详解---------------------------------

    HttpServletRequest获取参数(重要)
    1 HttpServletRequest获取参数方法
    可以使用HttpServletRequest获取客户端的请求参数,相关方法如下:

    String getParameter(String name):通过指定名称获取参数值;
    String[] getParameterValues(String name):通过指定名称获取参数值数组,有可能一个名字对应多个值,例如表单中的多个复选框使用相同的name时;
    Enumeration getParameterNames():获取所有参数的名字;
    Map getParameterMap():获取所有参数对应的Map,其中key为参数名,value为参数值。
     

    2 传递参数的方式
    传递参数的方式:GET和POST。

    GET:

    地址栏中直接给出参数:http://localhost/param/ParamServlet?p1=v1&p2=v2;
    超链接中给出参数:<a href=” http://localhost/param/ParamServlet?p1=v1&p2=v2”>???</a>
    表单中给出参数:<form method=”GET” action=”ParamServlet”>…</form>
    Ajax暂不介绍
     

    POST:

    表单中给出参数:<form method=”POST” action=”ParamServlet”>…</form>
    Ajax暂不介绍


    3. 单值参数的接收
           单值参数包括单选,单值下拉框,文本,隐藏域

    无论是GET还是POST,获取参数的方法是相同的。

    String s1 = request.getParameter(“p1”);//返回v1

    String s2 = request.getParameter(“p2”);//返回v2

        <form action="ParamServlet" method="post">

        <input type="text" name="p1"/><br/>

        <input type="text" name="p2"/><br/>

        <input type="submit" value="提交"/><br/>

        </form>

        <a href="ParamServlet?p1=v1&p2=v2">Param</a>

           String s1 = request.getParameter("p1");

           String s2 = request.getParameter("p2");

           response.getWriter().print("p1 = " + s1 + "<br/>");

           response.getWriter().print("p2 = " + s2 + "<br/>");

           Enumeration names = request.getParameterNames();

           while(names.hasMoreElements()) {

               String name = (String)names.nextElement();

               String value = request.getParameter(name);

               System.out.println(name + " = " + value);

           }

    4 多值参数接收
           多值参数主要就是多选checkbox

    例如在注册表单中,如果让用户填写爱好,那么爱好可能就是多个。那么hobby参数就会对应多个值:

        <form action="ParamServlet" method="post">

           上网:<input type="checkbox" name="hobby" value="netplay" /><br/>

           踢球:<input type="checkbox" name="hobby" value="football" /><br/>

           看书:<input type="checkbox" name="hobby" value="read" /><br/>

           编程:<input type="checkbox" name="hobby" value="programme" /><br/>

        <input type="submit" value="提交"/><br/>

        </form>

           // 获取所有名为hoby的参数值

           String[] hobbies = request.getParameterValues("hobby");

           System.out.println(Arrays.toString(hobbies));

      request.getParameterMap()方法返回Map类型,对应所有参数。其中Map的key对应参数的名字;Map的value对应参数的值。

        <form action="ParamServlet" method="post">

           姓名:<input type="text" name="name"/><br/>

           年龄:<input type="text" name="age"/><br/>

           性别:<input type="text" name="sex"/><br/>

        <input type="submit" value="提交"/><br/>

        </form>

           Map<String,String[]> map = request.getParameterMap();

           Set<String> keys = map.keySet();

           for(String key : keys) {

               String[] value = map.get(key);

               System.out.println(key + " = " + value[0]);

           }

    sex = male

    name = zhangSan

    age = 23

    单值参数,也可以使用request.getParameterValues(String)获取,其实当参数的值是单个的时候,同样可以使用request.getParameterValues(String)方法来获取参数值,不过这个参数返回的值为String[],这时我们需要再去获取数组下标0的元素。

    String name = request.getParameterValues(“name”)[0];

    在知道name的情况下,获取单值和多值的代码示例:

    代码1.html

    <!DOCTYPE html>

    <html>

    <head>

    <meta charset="UTF-8">

    <title>Insert title here</title>

    </head>

    <body>

           <h1>request接收参数</h1>

           <a href="/request_demo2/hello?name=likunpeng&age=30">访问1.html</a>

           <hr/>

           <h1>表单方式来提交数据</h1>

           <form action="/request_demo2/hello" method="get">

                  姓名:<input name="name" type="text">

                         <br/>

                  年龄:<input name="age" type="text">

                         <br/>

                  性别:<input name="gender" type= "radio" value="1">男&nbsp;

                      <input name="gender" type="radio" value="0">女

                      <br/>

                  职位:<select name="job">

                                <option value="1">讲师</option>

                                <option value="2">架构师</option>

                         </select>

                         <br/>

                  简介:<br/>

                         <textarea name="introduce" rows="10" cols="30"></textarea>

                         <br/>

                  爱好:<input name="favor" type="checkbox" value="1">篮球&nbsp;

                      <input name="favor" type="checkbox" value="2">足球&nbsp;

                         <input name="favor" type="checkbox" value="3">游泳&nbsp;

                         <br/>

                         <input type="submit" value="提交">

           </form>

    </body>

    </html>

    HelloServlet代码:

    public class HelloServlet extends HttpServlet {
     

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

                  //根据请求中的key来获得值

                  //单值接收

                  String name = request.getParameter("name");

                  System.out.println(name);

                  String age = request.getParameter("age");

                  System.out.println(age);

                  String gender = request.getParameter("gender");

                  System.out.println(gender);

                  String job = request.getParameter("job");

                  System.out.println(job);

                  String introduce = request.getParameter("introduce");

                  System.out.println(introduce);

                 

                  //以下方式不适合接收多选,只能接收到多选中的第一个

                  //String favor = request.getParameter("favor");

                  //多值接收

                  String[] favors = request.getParameterValues("favor");

                  for (String favo : favors) {
                         System.out.print(favor+"、");

                  }

           }

           public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  doGet(request, response);

           }

    }

    结果图

    -------------------------------------------------------------------------------------------------------------

    在不知道name的情况下,通过request中的getParameterNames方法来获取文本域中的值:

    新建一个servlet

    public class HelloServlet1 extends HttpServlet {
           /**

            * getParameterNames用于获得表单中文本域的所有的name,适合动态表单

            */

           public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  //获得表单中所有的文本域的name

                  Enumeration<String> parameteNames = request.getParameterNames();

                  while(parameteNames.hasMoreElements()){
                         //获得每个文本域的name

                         String parameteName = parameteNames.nextElement();

                         //根据文本域的name来获取值

                         //因为无法判断文本域是否是单值或者双值,所以我们全部使用双值接收

                         String[] parameteValues = request.getParameterValues(parameteName);

                         //输出文本域的name

                         System.out.print(parameteName+":");

                         for (String parameteValue : parameteValues) {
                                //输出文本域的值

                                System.out.print(parameteValue+" ");

                         }

                         //换行

                         System.out.println();

                  }

           }

           public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  doGet(request, response);

           }

    }

    -------------------------------------------------------------------

    Request中getParameterMap使用介绍:

    Servlet代码示例:

    public class HelloServlet2 extends HttpServlet {
     

           public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  //获得表单中所有文本域的name和值,以Map方式来存取

                  Map map = request.getParameterMap();

                  //获得Map集合中所有的key,就是表单中文本域的集合

                  Set<String> keys = map.keySet();

                  for (String name : keys) {
                         //获得文本域的值

                         String[] values = (String[])map.get(name);

                         //打印文本域名字

                         System.out.print(name+":");

                         for (String value : values) {
                                //打印文本域中的值

                                System.out.print(value+" ");

                         }

                         //打印换行

                         System.out.println();

                  }

           }

    }


    5.Request的获得中文乱码处理
    设置eclipse所使用的编码:

    Request接收参数时有get和post两种请求方式,但是处理中文的编码却不一样,我们在做项目时会全站都采用统一的编码,最常用的就是UTF-8,在UTF-8编码的项目中的

    当我们使用Post请求时:
    处理POST编码问题!

    我们知道,请求信息中,只有POST存在正文,所谓POST参数编码就是就是请求正文的编码。

    默认情况下,使用getParameter()获取POST请求参数时,使用的是ISO-8859-1编码。

           String name = request.getParameter("name");

           name = new String(name.getBytes("ISO-8859-1"), "UTF-8");

           System.out.println(name);

    因为在获取参数时已经被错误的编码了,但因为我们知道,乱码的两个原因:本来是使用UTF-8编码的,还错误的使用了ISO-8859-1编码。所以我们可以先使用ISO-8859-1获取字节数组,然后再使用正确的UTF-8编码得到字符串,这样就没问题了。

    request的setCharacterEncodng()可以设置编码,当然这必须在调用所有的getParameter()方法之前调用request的setCharacterEncodng()方法来设置编码,这样,就不会使用ISO解读字节串了,而是使用你给定的编码来解读。

           request.setCharacterEncoding("UTF-8");

           String name = request.getParameter("name");

           System.out.println(name);

    对于每个请求,只需要调用request的setCharacterEncodng()一次,然后所有getParameter()都会使用这个编码来解读参数。但要注意,只对请求正文有效,即POST参数。

    字符串编码案例介绍:

    public class test {
     

           public static void main(String[] args) throws UnsupportedEncodingException {
                  //获取一个ISO-8869-1编码的字符串

                  String s = new String("李昆鹏".getBytes(),"ISO-8859-1");

                  //指定s的编码格式为ISO-8859-1,s的解码格式为默认格式UTF-8,s1的编码格式为默认格式UTF-8

                  String s1 = new String(s.getBytes("ISO-8859-1"));

                  //指定s的编码格式为ISO-8859-1,s的解码格式为默认格式UTF-8,s1的编码格式为指定格式UTF-8

                  String s2 = new String(s.getBytes("ISO-8859-1"),"UTF-8");

                  //指定s的编码格式为默认格式UTF-8,s的解码格式为默认格式UTF-8,s1的编码格式为指定格式UTF-8

                  String s3 = new String(s.getBytes(),"UTF-8");

                  //请看输出结果

                  System.out.println(s); //ææé¹

                  System.out.println(s1);//李昆鹏

                  System.out.println(s2);//李昆鹏

                  System.out.println(s3);//ææé¹

           }

    }

    Post方式处理中文乱码第一种方式:

    public class HelloServlet extends HttpServlet {
     

           public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  String name = request.getParameter("name");

                  String introduce = request.getParameter("introduce");

                  //以下输出字符串会出现乱码

                  System.out.println(name);

                  System.out.println(introduce);

                  //将name编码通过string构造器从ISO-8859-1变成UTF-8解码

                  name = new String(name.getBytes("ISO-8859-1"),"UTF-8");

                  introduce = new String(introduce.getBytes("ISO-8859-1"),"UTF-8");

                  System.out.println(name);

                  System.out.println(introduce);

           }

    }

    Post方式处理中文乱码第二种方式: 使用request中的setCharacterEncoding(“UTF-8”)方法(建议使用)

    public class HelloServlet1 extends HttpServlet {
     

           public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  //设置request编码为UTF-8

                  request.setCharacterEncoding("UTF-8");

                  String name = request.getParameter("name");

                  String introduce = request.getParameter("introduce");

                  System.out.println(name);

                  System.out.println(introduce);   

           }

    }

    当我们采用get请求时

    上述的post的处理方式不再生效

    第一种方式:
    我们可以采用字符串转码的方式来处理

           String s = request.getParameter(“s”);

           s = new String(s.getBytes(“iso-8859-1”), “utf-8”);

    第二种方式:
    GET参数不在请求正文中,而是在URL中。所以不能使用request的setCharacterEncodng()来设置GET参数的编码。

    处理GET参数编码可以有两种方式:第一种是设置<Connector>元素的URIEncoding属性的值为UTF-8。即confserver.xml中的<Connector>元素的URIEncoding属性。

    一旦设置了这个属性,那么对于GET参数就直接是UTF-8编码的了。但是,<Connector>元素来说,对整个Tomcat都是有效的!

    第三种JavaScript对超链接做URL编码
    处理这个问题的办法是把GET请求中的参数使用JavaScript做URL编码,URL编码后的内容就不再是中文了,这样IE6也就不会丢失字节了。

    <a href="#" onclick="click1()">ff</a>

    <script type="text/javascript">

    function click1(){

       var path = encodeURI(encodeURI("servlet/RequestDemo?namea=任亮"));

       location.href = path;

    }

    </script>

    http://localhost/encoding/EncodingServlet?name=%E5%A4%A7%E5%AE%B6%E5%A5%BD

      在使用URL编码后,大家好已经变成了%E5%A4%A7%E5%AE%B6%E5%A5%BD。这样就不会再丢失字节了。

    String val = request.getParameter("namea");

          val = URLDecoder.decode(val, "UTF-8");

          System.out.println(val);

    代码1.xml示例:

    <!DOCTYPE html>

    <html>

    <head>

    <meta charset="UTF-8">

    <title>Insert title here</title>

    <script type="text/javascript">

           function subreq(){
                  var path = encodeURI(encodeURI("/request_demo3/hello3?name=李昆鹏1"));

                  window.location.href=path;

           }

    </script>

    </head>

    <body>

           <h1>request接收参数</h1>

           <a href="/request_demo2/hello?name=likunpeng&age=30">访问1.html</a>

           <hr/>

           <h1>request处理post方式中文乱码问题</h1>

           <form action="/request_demo3/hello1" method="post">

                  姓名:<input name="name" type="text">

                         <br/>

                  年龄:<input name="age" type="text">

                         <br/>

                  简介:<br/>

                         <textarea name="introduce" rows="10" cols="30"></textarea>

                         <br/>

                         <input type="submit" value="提交">

           </form>

           <hr/>

           <h1>request处理get方式中文乱码问题</h1>

           <a href="/request_demo3/hello2?name=李昆鹏&introduce=你好">点击Get请求</a>

           <br/>

           <a href="#" οnclick="subreq()">点击Get请求1</a>

    </body>

    </html>

    HelloServlet3代码示例:

    public class HelloServlet3 extends HttpServlet {
     

           public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  //设置request编码为UTF-8

                  //在get方式请求中request.setCharacterEncoding("UTF-8");不再起作用

                  String name = request.getParameter("name");

                  //下面是第一种解决get方式中文乱码问题

                  //name = new String(name.getBytes("ISO-8859-1"),"UTF-8");

                  //第二种方式在服务器配置文件server.xml的Connector元素中添加编码属性URIEncoding="UTF-8"

                  //第三种方式利用javaScript解决中文乱码问题

                  name = URLDecoder.decode(name,"UTF-8");

                  System.out.println(name);

           }

    }

    6. HttpServletRequest请求转发(服务器端跳转forward)
    在Servlet中请求转发是大量要使用的,因为当我们访问一个Servlet的时候通常会执行一些后台的业务逻辑,然后跳转到一个结果页面,那么跳转到结果页面的这个过程就是请求转发,举个例子我们做登录的功能,我们填写用户名密码然后提交到一个负责登录的Servlet,Servlet为我们做用户名和密码的校验,如果我们都正确的话,我们就要跳转到登录的提示页面,如果错误就要跳转到登录失败的页面。

    Request的请求转发也可以叫做服务器端的跳转,虽然有页面的跳转但是我们会发现地址栏是不会有变化的。

    request.getRequestDispatcher("/success.html").forward(request, response);

    我们不但可以跳转到静态页面(后续主要讲解是动态页面我们通常会跳转到一个jsp(jsp在Servlet之后产生)的提示页面,因为我们要返回的是动态页面,所有html是不适合(后续讲解))。还可以跳转到Servlet,此时我们可以给request来设置当前域中的属性值,在该域之内(当前请求完成之前)都能获得到该属性值。

    request.setAttribute("name", "任亮");

    request.getAttribute("name");

    Servlet内部页面跳转代码示例:

    代码1.html

    <!DOCTYPE html>

    <html>

    <head>

    <meta charset="UTF-8">

    <title>请求转发</title>

    </head>

    <body>

            <h1>请求转发到success.html页面</h1>

            <form action="/request_demo4/hello" method="post">

                     姓名:<input name="name" type="text">

                             <br/>

                     年龄:<input name="age" type="text">

                             <br/>

                     简介:<br/>

                             <textarea name="introduce" rows="10" cols="30"></textarea>

                             <br/>

                             <input type="submit" value="提交">

            </form>

            <h1>请求转发到servlet</h1>

            <form action="/request_demo4/hello" method="post">

                     姓名:<input name="name" type="text">

                             <br/>

                     年龄:<input name="age" type="text">

                             <br/>

                     简介:<br/>

                             <textarea name="introduce" rows="10" cols="30"></textarea>

                             <br/>

                             <input type="submit" value="提交">

            </form>

            <hr/>

    </body>

    </html>

    HelloServlet代码:

    public class HelloServlet extends HttpServlet {
     

           @Override

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

                   * request请求转发

                   * 服务器的页面跳转,地址栏不变

                   */

                  System.out.println("servlet被访问");

                  //使用request.setAttribute来设置结果集

                  request.setAttribute("testAttribute", new String[]{"li","kun","peng"});

                  request.getRequestDispatcher("/hello1").forward(request, response);

           }

          

           @Override

           public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  doGet(request, response);

                 

           }

          

    }

    HelloServlet1代码:

    public class HelloServlet1 extends HttpServlet {
     

           @Override

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

                   * request请求转发

                   * 服务器的页面跳转,地址栏不变

                   */

                  System.out.println("servlet1被访问");

                  String[] attributeValues = (String[])request.getAttribute("testAttribute");

                  for (String attributeValue : attributeValues) {
                         System.out.println(attributeValue);

                  }

                  request.getRequestDispatcher("/success.html").forward(request, response);

           }

          

           @Override

           public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  doGet(request, response);

                 

           }

          

    }

    7.request域的作用范围
    在上一讲我们提及过ServletContext的概念,它也是一个域的对象,它的范围非常大,是指定项目所有Servlet的公共的对象,随着服务器的启动而产生,服务器的停止而销毁,那么request的也是域对象,它的作用范围小的多,它的范围只在一次请求响应范围之内,每一个线程的请求都会新产生一个HttpServletRequest和HttpServletResponse的对象
    ————————————————
    版权声明:本文为CSDN博主「李昆鹏」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/weixin_41547486/article/details/81266712

  • 相关阅读:
    centos 编码问题 编码转换 cd到对应目录 执行 中文解压
    centos 编码问题 编码转换 cd到对应目录 执行 中文解压
    centos 编码问题 编码转换 cd到对应目录 执行 中文解压
    Android MVP 十分钟入门!
    Android MVP 十分钟入门!
    Android MVP 十分钟入门!
    Android MVP 十分钟入门!
    mysql备份及恢复
    mysql备份及恢复
    mysql备份及恢复
  • 原文地址:https://www.cnblogs.com/muhy/p/14889479.html
Copyright © 2011-2022 走看看