HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,
HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息
获取前端传递的参数,并且请求转发
返回String 返回单个
返回数组 返回多个
这两个已经过时了
转发时"/"代表的是本应用程序的根目录 重定向时"/"代表的是webapps目录
重定向需要写项目名 请求转发不需要
getRequestDispatcher分成两种,可以用request调用,也可以用getServletContext()调用
问题:重定向和转发的区别
相同点
`页面都会实现跳转
不同点
`请求转发的时候,url不会产生变化 307
`重定向时候,url地址栏会发生变化; 302
代码练习:前台输入表单信息 后台接收前端传递的参数,提交后转发到另一个页面
页面乱码的设置响应头resp.setHeader("Content-Type", "text/html;charset=UTF-8");
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录</title> </head> <body> <h1 align="center">登录</h1> <div style="text-align: center"> <%--居中--%> <%--这里表单表示的意思:以post方式提交表单,提交到我们的Login请求---%> <form action="${pageContext.request.contextPath}/login" method="post"> 用户名:<input type="text" name="username"><br/> 密码: <input type="password" name="password"><br/> 愿望: <%--checkbox 多选框 radio单选框--%> <input type="checkbox" name="hobby" value="金钱">金钱 <input type="checkbox" name="hobby" value="头发">头发 <input type="checkbox" name="hobby" value="瘦">瘦 <input type="checkbox" name="hobby" value="颜值">颜值 <br/> <input type="submit"> </form> </div> </body> </html>
成功后转发页面
后台接收
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //接收的时候为UTF-8 req.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobby = req.getParameterValues("hobby"); System.out.println("----------"); System.out.println(username); System.out.println(password); System.out.println(Arrays.toString(hobby)); System.out.println("----------"); //通过请求转发 //这里的 / 代表当前的web应用 req.getRequestDispatcher("/success.jsp").forward(req,resp); }
设置webapp映射
运行测试
输入后提交