request对象
- request和response对象是由服务器创建的。我们来使用它们
- request对象是来获取请求消息,response对象是来设置响应消息
request和response的内部实现
public interface HttpServletRequest extends ServletRequest
public interface HttpServletResponse extends ServletResponse
从源码可以看出这两个玩意儿分别继承ServletRequest ServletResponse。
HttpServletRequest 的常用方法
String getContextPath()
//Returns the portion of the request URI that indicates the context of the request.
//获取虚拟目录URI
String getMethod()
//获取请求方法
String getQueryString()
//获取请求参数,当然这个方法不是很常用
**HttpServletResponse的常用方法 **
void sendRedirect(String location)
//Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.
//资源重定位,这里可以直接定位到其它站点的网址,但是缺点是不能在域内共享数据。
void setContentType(String type)
//Sets the content type of the response being sent to the client, if the response has not been committed yet.
//设置响应头消息,便以浏览器解析(此方法继承ServletResponse)
void setCharacterEncoding(String charset)
//Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.
//设置响应的字符集编码防止乱码(此方法继承ServletResponse)
PrintWriter getWriter()
//Returns a PrintWriter object that can send character text to the client.
//将响应消息写道浏览器中
其他常用的方法
/**获取参数的方法(post和get通用的方法)**/
1. String getParameter(String name):根据参数名称获取参数值
2. String[] getParameterValues(String name):根据参数名称获取参数值的数组
3. Enumeration<String> getParameterNames():获取所有请求的参数名称
4. Map<String,String[]> getParameterMap():获取所有参数的map集合
/**请求转发:一种在服务器内部的资源跳转方式**/
RequestDispatcher getRequestDispatcher(String path)//通过request对象获取请求转发器对象
forward(ServletRequest request, ServletResponse response)// forward(ServletRequest request, ServletResponse response)
//只能在服务器内部转发。可以获取共享域中的数据。
* 域对象:一个有作用范围的对象,可以在范围内共享数据
* request域:代表一次请求的范围,一般用于请求转发的多个资源中共享数据
* 方法:
1. void setAttribute(String name,Object obj):存储数据
2. Object getAttitude(String name):通过键获取值
3. void removeAttribute(String name):通过键移除键值对
4. 获取ServletContext:
* ServletContext getServletContext()