javax.servlet.http.HttpServletRequest接口:
- HttpServletRequest是Servlet规范重要接口之一。
- 继承ServletReuest.
- HttpServletRequest接口的实现类由web容器实现。封装了Http请求协议的全部内容。
- HttpServletRequest生命周期短暂,只在一次请求中有效。
接口中常用方法:
String getParameter(String name);
通过key获取value这个一维数组的首元素。String[] getParameterValues(String name);
通过map集合获取valueMap<String, String[]> getParameterMap();
获取整个map集合Enumeration<String> getParameterNames();
获取整个map集合的key- getContextPath()
- getMethod()
- getRequestURI()
- getRequestURL()
- getServletPath
- getRemoteAddr
- Object getAttribute(String var1); 向HttpServletRequest获取数据
- void setAttribute(String var1, Object var2);向HttpServletRequest添加数据
- void removeAttribute(String var1); 向HttpServletRequest删除数据
-RequestDispatcher getRequestDispatcher(String path);转发器
/**
* Created by King on 2017/5/2.
*/
@WebServlet(value ="/a")
public class Myservlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//获取上下文路径(webapp下)
String contextPath = request.getContextPath();
out.print("上下文路径 = " + contextPath);
out.print("<br>");
//获取浏览器请求方式
String method = request.getMethod();
out.print("method = " + method);
out.print("<br>");
//获取请求的URI
String requestURI = request.getRequestURI();
out.print("requestURI = " + requestURI);
out.print("<br>");
//获取请求的URL
String requestURL = request.getRequestURL().toString();
out.print("requestURL = " + requestURL);
out.print("<br>");
//获取servlet path
String servletPath = request.getServletPath();
out.print("servletPath = " + servletPath);
out.print("<br>");
//获取客户端IP地址
String remoteAddr = request.getRemoteAddr();
System.out.print(remoteAddr);
//执行A,跳转到B,将A和B执行放到同一个请求中,
//必须使用转发forward.
//获取请求转发器对象(以下转发器,指向了B servlet)
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/b");
//调用请求转发器完成跳转
requestDispatcher.forward(request,response );
}
}
上下文路径 = /servlet
method = GET
requestURI = /servlet/a
requestURL = http://localhost:8080/servlet/a
servletPath = /a