表单:
<body> <form action="http://localhost:8080/07_servlet/parameterServlet" method="get"> 用户名:<input type="text" name="username"><br/> 密码:<input type="password" name="password"><br/> 兴趣爱好:<input type="checkbox" name="hobby" value="cpp">C++ <input type="checkbox" name="hobby" value="java">Java <input type="checkbox" name="hobby" value="js">JavaScript<br/> <input type="submit"> </form> </body>
java代码:
public class ParameterServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取请求参数 String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobby = req.getParameterValues("hobby"); System.out.println("用户名:" + username); System.out.println("密码:" + password); System.out.println("兴趣爱好:" + Arrays.asList(hobby)); } }
请求转发是指,服务器收到请求后,从一次资源跳转到另一个资源的操作叫请求转发。
也就是一次请求调用几个Servlet程序,并返回客户端
Servlet1 代码:
public class Servlet1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.获取请求的参数(办事的材料)查看 String username = req.getParameter("username"); System.out.println("在 Servlet1(柜台 1)中查看参数(材料):" + username); // 2.给材料 盖一个章,并传递到 Servlet2(柜台 2)去查看 req.setAttribute("key1","柜台 1 的章"); // 3.问路:Servlet2(柜台 2)怎么走 /** * 请求转发必须要以斜杠打头,/ 斜杠表示地址为:http://ip:port/工程名/ , 映射到 IDEA 代码的 web 目录 <br/> * */ RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servlet2"); // RequestDispatcher requestDispatcher = req.getRequestDispatcher("http://www.baidu.com"); // 4.走向 Sevlet2(柜台 2) requestDispatcher.forward(req,resp); } }
Servlet2 代码:
public class Servlet2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.获取请求的参数(办事的材料)查看 String username = req.getParameter("username"); System.out.println("在 Servlet2(柜台 2)中查看参数(材料):" + username); // 2.查看 柜台 1 是否有盖章 Object key1 = req.getAttribute("key1"); System.out.println("柜台 1 是否有章:" + key1); // 3.处理自己的业务 System.out.println("Servlet2 处理自己的业务 "); } }