前言:
本文内容:Response重定向、Request应用
推荐免费JavaWeb入门到实战视频:【狂神说Java】JavaWeb入门到实战_哔哩哔哩_bilibili
Response重定向
重定向:一个Web资源收到客户端请求,他会通知客户端去访问另一个Web资源
常见场景:
-
用户登录
1
| void sendRedirect(String var1)throws IOException
|
-
测试
1 2 3 4 5 6 7 8 9
| @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/re1/image"); }
|
提问:重定向和请求转发的区别?
相同点
不同点
- 请求转发,url不会产生变化
- 重定向,url地址会产生变化
练习:
1 2 3 4 5 6 7 8 9
| @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("进入请求"); String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username+" "+password); resp.sendRedirect("/re1/success.jsp"); }
|
Request应用
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过HttpServletRequest方法,获取客户端所有信息;
获取前端的参数
1 2 3 4
| req.getParameter(String s); req.getParameterMap(); req.getParameterNames(); req.getParameterValues(String s);
|
请求转发
Java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package com.jokerdig.servlet;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays;
public class LoginServlet extends HttpServlet {
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobbies = req.getParameterValues("hobby"); System.out.println("----------------"); System.out.println(username); System.out.println(password); System.out.println(Arrays.toString(hobbies)); System.out.println("----------------"); req.getRequestDispatcher("/success.jsp").forward(req,resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } }
|
Jsp页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2>登录</h2> <form action="${pageContext.request.contextPath}/login" method="post"> 账号:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 爱好:<input type="checkbox" name="hobby" value="音乐">音乐 <input type="checkbox" name="hobby" value="电影">电影 <input type="checkbox" name="hobby" value="其他">其他<br> <input type="submit"> </form> </body> </html>
|
Web.xml
1 2 3 4 5 6 7 8
| <servlet> <servlet-name>login</servlet-name> <servlet-class>com.jokerdig.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>
|