1.获取请求的基本信息
1>获取请求的url和uri
2>获取url后面的请求参数部分的字符串
3>获取请求方式
4>获取主机名,IP地址
5>获取 Contexpath
String url = request.getRequestURL().toString();
System.out.println(url);
String uri = request.getRequestURI().toString();
System.out.println(uri);
String params = request.getQueryString();
System.out.println(params);
String method = request.getMethod();
System.out.println(method);
String addr = request.getRemoteHost() + request.getRemotePort() + request.getRemoteAddr() +
"==user=" + request.getRemoteUser();
System.out.println("addr: " + addr);
String contextPath = request.getContextPath();
response.sendRedirect(contextPath + "/index.jsp");
获取请求参数
Map<String, String[]> params = request.getParameterMap();
for (String name : params.keySet()) {
String value = request.getParameter(name);
System.out.println("name=" + name + ", value=" + value);
}
解决请求乱码问题:
request.setCharacterEncoding("Utf-8");
如果上面的代码只能解决POST的乱码问题, 则可以自行进行解码操作
String userName = request.getParameter("username");
userName = new String(userName.getBytes("ISO8859-1"), "UTF-8");
请求转发:
request.getRequestDispatcher("/DispatcherTest2").forward(request, response);
或
this.getServletContext().getRequestDispatcher("/DispatcherTest2").forward(request, response);
Note:
1)一次请求只能转发一次, 否则会发生下面的异常: -- 可以得到第一次转发获取的数据
java.lang.IllegalStateException: Cannot forward after response has been committed
2)当有数据已经写到客户端时再请求转发也会抛出异常.
3)若转发前有数据写入到response缓冲区,则请求转发会清空response缓冲区的实体内容, 但不会清空请求头信息.
请求重定向:
response.sendRedirect(request.getContextPath() + "/Servlet02");
Notice:
1) 不能在数据已经发送到浏览器之后再进行请求重定向:
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
2) 在请求重定向之前写入到response缓冲区的数据会被清空
3) 一次请求只能重定向一次