JSP 中request与response的用法详解

jsp 中request与response的用法详解

概要:

在学习这两个对象之前,我们应该已经有了http协议的基本了解了,如果不清楚http协议的可以看我的关于http协议的介绍。因为其实request和response的使用大部分都是对http协议的操作。

request对象的介绍

我们先从request对象进行介绍:

我们知道http协议定义了请求服务器的格式:

请求行
请求头
空格
请求体(get请求没有请求体)

好了,这里我们就不详细介绍了,我们只看几个应用就可以了,没什么难度:

应用1 获取请求头

/** 
 * 获取http请求头 
 *   string getheader(string name),适用于单值头 
 *   int getintheader(string name),适用于单值int类型的请求头 
 *   long getdateheader(string name),适用于单值毫秒类型的请求头 
 *    enumeration<string> getheaders(string name),适用于多值请求头 
 * 
 * 
 */ 
public class cservlet extends httpservlet { 
 
  public void doget(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
 
    string ip = request.getremoteaddr();//获取ip地址 
    string method = request.getmethod();//获取请求方式 
    system.out.println(ip); 
    system.out.println(method); 
    getliulanqi(request); 
    protectmethod(request, response); 
  } 
//防盗链 
  public void protectmethod(httpservletrequest request, 
      httpservletresponse response) { 
    string url = request.getheader("referer"); 
    system.out.println(url); 
    if(url != null && url.equalsignorecase("http://localhost:8080/day10/myhtml.html") ) { 
      system.out.println("hi"); 
    } 
    else { 
      response.setstatus(302); 
      response.setheader("location","/day10/myhtml.html"); 
      system.out.println("重定向"); 
    } 
  } 
//判断浏览器的类型 
  public void getliulanqi(httpservletrequest request) { 
    string user = request.getheader("user-agent"); 
    if(user != null) { 
      string usernoc = user.tolowercase(); 
      if(usernoc.contains("chrome")) { 
        system.out.println("浏览器类型:谷歌" ); 
      } 
      else if(usernoc.contains("firefox/")) { 
        system.out.println("浏览器类型:火狐"); 
      } 
      else { 
        system.out.println("浏览器类型:ie"); 
      } 
    } 
    else { 
      system.out.println("null"); 
    } 
  } 
} 

应用2获取url路径

/** 
 * 获取请求url 
  http://localhost:8080/day10_2/aservlet?username=xxx&password=yyy 
    > string getscheme():获取协议,http 
    > string getservername():获取服务器名,localhost 
    > string getserverport():获取服务器端口,8080 
    > *****string getcontextpath():获取项目名,/day10_2 
    > string getservletpath():获取servlet路径,/aservlet 
    > string getquerystring():获取参数部分,即问号后面的部分。username=xxx&password=yyy 
    > string getrequesturi():获取请求uri,等于项目名+servlet路径。/day10_2/aservlet 
    > string getrequesturl():获取请求url,等于不包含参数的整个请求路径。http://localhost:8080/day10_2/aservlet 
 * 
 * 
 */ 
public class dservlet extends httpservlet { 
 
  public void doget(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    system.out.println(request.getscheme()); 
    system.out.println(request.getservername()); 
    system.out.println(request.getserverport()); 
    system.out.println(request.getcontextpath()); 
    system.out.println(request.getservletpath()); 
    system.out.println(request.getquerystring()); 
    system.out.println(request.getrequesturi()); 
    system.out.println(request.getrequesturl()); 
  } 
 
} 

应用3获取请求参数

/** 
 * 
 * 请求参数:有一个参数一个值的,还有一个参数多个值! 
    > *****string getparameter(string name):获取指定名称的请求参数值,适用于单值请求参数 
    > string[] getparametervalues(string name):获取指定名称的请求参数值,适用于多值请求参数 
    > enumeration<string> getparameternames():获取所有请求参数名称 
    > *****map<string,string[]> getparametermap():获取所有请求参数,其中key为参数名,value为参数值。 
 * 
 */ 
public class eservlet extends httpservlet { 
 
  public void doget(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    dopost(request,response); 
  } 
 
  public void dopost(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    request.setcharacterencoding("utf-8");//调用他来解决乱码问题的,不会的可以看我写的解决乱码的那一篇 
    string name = request.getparameter("name"); 
    string password = request.getparameter("password"); 
    string[] aihao = request.getparametervalues("aihao"); 
    response.setheader("content-type", "text/html;charset=utf-8"); 
    printwriter pw = response.getwriter(); 
    pw.println("name:" + name + "<br/>"); 
    pw.println("password:" + password + "<br/>"); 
    pw.print("aihao"); 
    for (int i = 0; i < aihao.length; i++) { 
      switch (i) { 
      case 1: 
        pw.print("吃饭"); 
        break; 
      case 2: 
        pw.print("睡觉"); 
        break; 
      case 3: 
        pw.print("打豆豆"); 
        break; 
 
      default: 
         
        break; 
      } 
    } 
    pw.close(); 
  } 
 
} 
<!-- 用于发送请求的html --> 
<html> 
 <head> 
  <title>denglu.html</title> 
  <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
 </head> 
  
 <body> 
  <form action="/day10/eservlet" method="post"><!-- 通过post方法提交 --> 
    姓名:<input type="text" name="name"/><br/> 
    密码:<input type="password" name="password"><br/> 
    爱好:<input type="checkbox" name="aihao" value="1"/>吃饭 
    <input type="checkbox" name="aihao" value="2"/>睡觉 
    <input type="checkbox" name="aihao" value="3"/>打豆豆 
    <input type="submit" value="提交"> 
  </form> 
 </body> 
</html> 

应用4设置request对象属性

用来实现同一个应用程序servlet之间值得传递,我们还用到了转发

/** 
 * 
 ** request域 
    servlet中三大域对象:request、session、application,都有如下三个方法: 
    > void setattribute(string name, object value) 
    > object getattribute(string name) 
   > void removeattribute(string name); 
    > 同一请求范围内使用request.setattribute()、request.getattribute()来传值!前一个servlet调用setattribute()保存值,后一个servlet调用getattribute()获取值。 
 
 * 
 */ 
public class fservlet extends httpservlet { 
 
  public void doget(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    request.setattribute("name","weijinhao"); 
    request.setattribute("password", "123"); 
    requestdispatcher rd = request.getrequestdispatcher("/gservlet"); 
    rd.forward(request, response); 
  } 
 
} 

public class gservlet extends httpservlet { 
 
  public void doget(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    string name = (string)request.getattribute("name"); 
    string password = (string)request.getattribute("password"); 
    response.setheader("content-type", "text/html;charset=utf-8"); 
    printwriter pw = response.getwriter(); 
    pw.println("name:" + name + "<br/>"); 
    pw.println("password:" + password + "<br/>"); 
    pw.close(); 
  } 
 
} 

好了,request的用法大致就是这摸多了。

让我们来看看response对象吧。

response对象的使用

http协议定义了响应浏览器的格式:

响应行
响应头
空格
响应体

response对象的大致应用是用在设置响应码,设置响应头,及设置响应正文。

应用1设置响应正文

/** 
   * response的正文 
   * 1,字符流 
   * 2,字节流 
   */ 
  public void doget(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    //string n = "hello javaweb"; 
    //byte[] b = n.getbytes(); 
    //字节流的使用 
    /*servletoutputstream outputstream = response.getoutputstream(); 
    outputstream.write(b); 
    outputstream.close();*/ 
     
     
    //字符流的使用 
    /*printwriter p = response.getwriter(); 
    p.write(n); 
    p.close();*/ 
     
    //commoms工具包的使用 
    fileinputstream fileinputstream = new fileinputstream("c:/users/74087/desktop/6226354_994604.jpg"); 
    byte[] b = ioutils.tobytearray(fileinputstream); 
    servletoutputstream outputstream = response.getoutputstream(); 
    outputstream.write(b); 
    outputstream.close(); 
  } 
 
} 

应用2 设置响应码和响应头

/** 
   *response 的响应码 
   *1, senderror(int sc)//发送错误代码 
   *2, senderror(int sc, java.lang.string msg) //发送错误代码及描述 
   *3, setstatus(int sc) //发送成功响应代码 
   *response 的响应头 
   *1, setdateheader(java.lang.string name, long date) 
   *2, setheader(java.lang.string name, java.lang.string value) 
   *3, setintheader(java.lang.string name, int value) 
   *  下面的和上面的作用一样但是是为了进行多值的添加 
   *  adddateheader(java.lang.string name, long date) 
   *  addheader(java.lang.string name, java.lang.string value) 
   *  addintheader(java.lang.string name, int value) 
   */ 
  public void doget(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    //sendnum(response); 
    //sendre(response); 
    //refresh(response); 
    //nocache(response); 
  } 
  //禁用浏览器缓存 
  public void nocache(httpservletresponse response) { 
    response.setheader("cache-control","no-cache"); 
    response.setheader("pragma","0"); 
    response.setheader("expires","no-cache"); 
  } 
  //自动跳转 
  public void refresh(httpservletresponse response) { 
    response.setheader("refresh", "5;url=http://www.baidu.com"); 
  } 
  //重定向的使用 
  public void sendre(httpservletresponse response) { 
    response.setstatus(302); 
    response.setheader("location", "http://www.baidu.com"); 
  } 
 
  public void sendnum(httpservletresponse response) throws ioexception { 
    response.setstatus(200); 
    response.senderror(404); 
    response.senderror( 404, "ser accept your request but i don't want to you see my web page"); 
  } 
 
} 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章