Servlet四—HttpRequest
一.概述
浏览器发起http请求时,会传入HttpServletRequest和HttpServletResponse两个参数,HttpServletRequest负责接收浏览器发送的数据,而HttpServletResponse则负责向浏览器返回数据。浏览器的任何数据都可以通过HttpRequest对象发送到Servlet。其数据结构包含参数(Parameters),头(Headers),数据流(InputStream),会话(Session),上下文(ServletContext)。下面我们对此作出具体讲解。
二.HttpRequest详解
1.参数(Parameters)
如果浏览器通过get方式发起访问请求,参数将会包含在URL中,如:http://localhost:8080/test?param1=hello¶m1=world
获取参数代码如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
}
如果浏览器通过post方式发起请求,则参数会包含在body中,如:
$.ajax({
type: "POST",
dataType: 'json',
data:{param1:hello,param1:world},
url: "http://localhost:8080/test",
success: function(msg){
}
});
获取参数代码如下:
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
}
2.头(Headers)
通过HttpServletRequest能读取到所有的头信息,读取方式为response.getHeader(“Cookie”)
3.数据流(InputStream)
当浏览器发送HTTP POST请求时,可以通过request.getInputStream()获取浏览器发送的数据。
4.会话(Session)
session对象可以在请求时保存有关用户的信息。因此,如果在一个请求期间将对象设置为会话对象,则可以在同一会话时间范围内的任何后续请求期间读取该对象。获取Session代码:HttpSession session = request.getSession();
5.上下文(ServletContext)
ServletContext包含有关Web应用程序的元信息。如:web.xml文件中设置的上下文参数,获取后也可以将其转发给其他servlet,也可以存储应用程序范围的参数ServletContext。ServletContext获取代码:ServletContext context = request.getSession().getServletContext().