HttpServletRequest对象

通过HttpServletRequest对象可获取客户端在访问服务器时,请求的所有信息

  • 获取客户机的信息
  1. getRequestURL:返回客户端发出请求时的完整URL
  2. getRequestURI:返回请求行中的部分资源名名称
  3. getQueryString:返回请求中的参数部分
  4. getRemoteAddr:返回请求中客户机的IP地址
  5. ......
String requestURL= request.getRequestURL;
String requestURI = request.getRequestURI;
String queryString = request.getQueryString;
String IP = getRemoteAddr;
  • 获取客户机的请求头
  1. getHeader(string name);返回String;
  2. getHeaders(String name);返回Enumeration;
  3. getHeaderNames();返回Enumeration;返回所有的请求头;
PrintWriter out = response.getWriter();
Enumertion<String> reqHeadInfos = request.getHeaderNames();
while(reqHeadInfos.hasMoreElements()){
    String name = reqHeadInfos.nextElement();
    String value = request.getHeader(name);
    out.write(name +":"+value);
}    
  • 获取客户端提交的数据
  1. getParameter(String name );
  2. getParameterValues(String name);
  3. getParameterMap();编写框架时常用;

表单信息:

<form action="xxx" method = "post">
<input type="text" name = "userid" maxlength = "2"><br>
<input type="checkbox" name = "hobby" value = "唱歌">唱歌
<input type="checkbox" name = "hobby" value = "跳舞">跳舞
<input type="checkbox" name = "hobby" value = "rap">rap
<input type="checkbox" name = "hobby" value = "打篮球">打篮球
<br>

所提交到的xxxjava文件中通过request获取其提交的数据:

PrintWriter out = response.getWriter();
String username = request.getParameter("name");
String[] hobbys = request.getParameterValues("hobby");
String hobbyStr = "";
for (int i = 0 ;hobbys!=null && i <hobbys.length;i++){
    if(i = hobbys.length-1){
        hobbyStr += hobbys[i];
        }else{
            hobbyStr +=hobbys[i]+",";
        }
}
out.write("name="+username);
out.write("hobbys="+hobbyStr);

request接收表单出现乱码问题

  • 以POST方式提交表单

出现乱码的原因是服务器和客户端沟通的编码不一致,而服务器可以通过ServletRequest接口继承而来的setCharacterEncoding(charset)方法来统一编码设置;

在获取数据前先统一编码设置:

request.setCharacterEncoding("UTF-8");
  • 以GET方式提交表单

即使统一编码,以GET方式提交的表单也会出现乱码,原因未知,request对象是以ISO8859-1的字符编码来接收数据,为了可以解决乱码问题,request对象需先获取以ISO8859-1字符编码接收到的数据的字节数组,再指定以"UTF-8"编码重新构建字符串;

PrintWriter out = response.getWriter();
String name = request.getparameter("name");
name = new String(name.getBytes("ISO8859-1"),"UTF-8");
out.write("name = "+name);

Request对象实现转发

之前我们有学过通过ServletContext实现转发:

RequestDispatcher reqDispatcher = this.getServletContext().getRequestDispatcher("/xxx/xxx");//这里返回的RequestDispatcher对象也可由request对象直接通过getRequestDispatcher()方法获取到
reqDispatcher.forward(request,response);//再通过forward方法实现请求转发

因此通过Request对象实现转发如下:

request.getRequestDispatcher("/xxx/xxx").forward(request,response);
02-12 20:30