request部分用法如代码:
AServlet
1 package cn.yzu; 2 import java.io.IOException; 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 public class AServlet extends HttpServlet { 8 9 public void doGet(HttpServletRequest request, HttpServletResponse response)10 throws ServletException, IOException {11 //演示简单用法12 System.out.println("访问的IP地址:"+request.getRemoteAddr());13 System.out.println("请求方法:"+request.getMethod());14 System.out.println("操作系统浏览器信息:"+request.getHeader("User-Agent"));15 System.out.println("项目名:"+request.getContextPath());16 //可用于防盗链,只会显示通过链接点击进入该servlet的请求路径,如果在浏览器地址栏直接输入则输出null17 System.out.println("请求来自:"+request.getHeader("Referer"));18 System.out.println("用户名:"+request.getParameter("username"));19 20 /**21 * 演示请求转发(留头不留体),如果是请求包含(request.getRequestDispatcher("BServlet").include(request, response))22 * 则留头又留体23 */24 System.out.println("AServlet被访问到");25 response.setHeader("aaa", "AAA");//响应头26 response.getWriter().println("AServlet..............................");//响应体27 //request域28 //需要在下一个Servlet中获取request域中的数据,必须要使用转发29 request.setAttribute("bbb", "BBB");30 //请求转发只能转发到本项目的其他servlet,不可转发到其他项目(比如百度),但是重定向可以重定向到其他项目31 //请求转发是服务器端行为,只需给出转发的Servlet路径,而重定向需要给出requestURI,即包含项目名!32 //需要地址栏发生变化,那么必须使用重定向!33 request.getRequestDispatcher("BServlet").forward(request, response);34 }35 }
BServlet
1 package cn.yzu; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 public class BServlet extends HttpServlet {11 public void doGet(HttpServletRequest request, HttpServletResponse response)12 throws ServletException, IOException {13 response.getWriter().println("BServlet..............................");14 response.getWriter().println(request.getAttribute("bbb"));15 }16 17 18 }
控制台输出:
页面输出:
补充:request获取请求路径相关的方法