java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Request对象获取请求头数据

Request对象如何获取请求头数据

作者:xuebanub1

这篇文章主要介绍了Request对象如何获取请求头数据问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

Request对象获取请求头数据

getHeaderNames()

getHeader(String name) (重点)

测试代码

@WebServlet(name = "RequestDemo2", value = "/requestDemo2")
public class RequestDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取所有请求头的名称
        Enumeration<String> headerNames = request.getHeaderNames();
        //遍历
        while (headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            //根据请求头的名称获取请求头的值
            String value = request.getHeader(name);
            System.out.println(name+":"+value);
        }

    }
}

结果:

host:localhost
connection:keep-alive
cache-control:max-age=0
sec-ch-ua:"Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"
sec-ch-ua-mobile:?0
sec-ch-ua-platform:"Windows"
upgrade-insecure-requests:1
user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 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.7
sec-fetch-site:cross-site
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
cookie:JSESSIONID=BACA32C62CC73505DD0178E34531D21C; _ga=GA1.1.1717905582.1633016465; JSESSIONID=E576986031221D734A3D7882557C867A

使用Request对象获取表单的信息

通过request对象可以获取表单中的输入信息,并将这些信息存入到指定的字符串中去

例如有下面一个表单

<form action="responseUserLogin.jsp" method="post">
    输入右面的认证码:<input type="text" name="verifyCodeDigit"/><br/>
    用户类型:<select name="type_User_Admin">
    <option value="1">前台用户</option>
    <option value="2">后台管理员</option>
      </select><br/>
    您的名称:<input type="text" name="userName"/><br/>
    您的密码:<input type="password" name="userPassword"/><br/>
    <input type="submit" value="提交" name="submitButton"/>
    <input type="reset" value="取消" />
 </form>
<body>
  <%! String verifyCodeDigit; %>
  <%! String type_User_Admin; %>
  <%! String userName; %>
  <%! String userPassword; %>
    <% request.setCharacterEncoding("UTF-8");
verifyCodeDigit = request.getParameter("paperTitle"); 
     if(request.getParameter("type_User_Admin").equals("1")) {
    type_User_Admin = "前台用户";
    }else{
            type_User_Admin = "后台管理员";
    }
    
      userName = request.getParameter("userName");
      userPassword = request.getParameter("userPassword");
     %>
 </body>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文