我是靠谱客的博主 现实指甲油,最近开发中收集的这篇文章主要介绍转发和重定向、Cookie和Session,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

转发与重定向

转发

特点:

  1. 浏览器向服务器发送一次请求
  2. 能够携带数据共享
  3. 内部其实是服务器行为
  4. 地址栏不会改变

编写代码测试

1.LoginServlet类,请求转发

package com.qfedu.servlet;

import com.qfedu.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author pengyu
 * @Date 2022/9/5 10:15
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User("彭宇","111111");
        //转发时,提前将数据设置进来
        //请求域
        req.setAttribute("user",user);


        //请求转发路径加/,以服务器为跟路径,因为是服务器行为
        //转发是浏览器发起请求一次服务器,而重定向则向服务器发送两次请求
        //转发可以携带数据实现共享,重定向不能共享数据
        req.getRequestDispatcher("/login/page").forward(req,resp);

        System.out.println("接着执行java代码");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.接收到转发,LoginPageServlet类

package com.qfedu.servlet;

import com.qfedu.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author pengyu
 * @Date 2022/9/5 10:30
 */
@WebServlet("/login/page")
public class LoginPageServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        User user = (User) req.getAttribute("user");

        resp.getWriter().write("<!DOCTYPE html>n" +
                "<html lang="en">n" +
                "<head>n" +
                "    <meta charset="UTF-8">n" +
                "    <title>Title</title>n" +
                "</head>n" +
                "<body>n" +
                "欢迎"+user.getName()+"登录n" +
                "</body>n" +
                "</html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

图解

在这里插入图片描述

重定向

特点:

  1. 浏览器向服务器发送两次请求
  2. 不能携带数据共享
  3. 浏览器行为
  4. 地址栏会发生改变

编写代码测试

1.实现重定向的RedirectServlet类

package com.qfedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author pengyu
 * @Date 2022/9/5 11:25
 */
@WebServlet("/redirect")
public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("name","依依");


        //重定向是浏览器行为,不需要加/,如果加了会出现url地址栏丢失项目名
        //地址栏发生变化,请求两次
        //正常:http://localhost:8080/day40/redirec2
        //这里如果加/,地址就变为了http://localhost:8080/redirec2导致项目名丢失
        //报404错误,如果非要加/,可以这样写req.getContextPath()来获取项目路径
        //resp.sendRedirect(req.getContextPath() + "/redirect2");
        resp.sendRedirect("redirect2");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.重定向到的RedirectServlet2类

package com.qfedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author pengyu
 * @Date 2022/9/5 11:27
 */
@WebServlet("/redirect2")
public class RedirectServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("重定向");
        String name = (String) req.getAttribute("name");

        System.out.println(name);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

图解

在这里插入图片描述

请求域

可以看到咱们在请求转发中使用了req.setAttribute("user",user);,这是将数据存储到请求域中,它只能在一次请求中存在,因此在请求转发中可以共享数据,而在重定向中是无法进行数据共享的

会话技术

Cookie

存在于浏览器

  • 创建

    //创建Cookie 传参String name,String value
    Cookie cookie = new Cookie("name", "admin");
    
  • 使用

    //响应给浏览器cookie
    resp.addCookie(cookie1);
    
  • 获取

    //获得Cookie 通过请求从浏览器来得到cookie,咱们获取到的不止一个cookie,因此需要进行遍历
    Cookie[] cookies = req.getCookies();
    
    //判断cookies是否为空,不加判断的话可能会出现空指针异常
    
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
    
            System.out.println(name + "=" + value);
        }
    }
    
  • 删除

    //删除的话咱们可以设置cookie的生命时间
    //设置cookie生命周期,单位是秒,如果该秒是0的话,意思是创建后就销毁了。如果是-1时,关闭浏览器即销毁。大于0的数值时,为存活多少秒
    cookie.setMaxAge(30);
    

小案例

1.CookieServlet类进行创建cookie,并进行一系列设置

package com.qfedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @Author pengyu
 * @Date 2022/9/5 15:08
 */
@WebServlet("/ck1")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建Cookie 传参String name,String value
        Cookie cookie = new Cookie("name", "admin");
//
        //设置cookie生命周期,单位是秒
//        cookie.setMaxAge(30);

        //设置路径即设置cookie的一个范围
        //cookie.setPath();

        //编码,不进行编码的话很容易发生数据被泄露
        Cookie cookie1 = new Cookie(URLEncoder.encode("账户", "UTF-8"), URLEncoder.encode("张三", "UTF-8"));

        //生命周期设置负数即浏览器关闭即销毁cookie
        cookie1.setMaxAge(-1);
        //响应给浏览器cookie
        resp.addCookie(cookie1);

        System.out.println("已经响应给浏览器cookie");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.CookieServlet2类进行获取cookie,并将其遍历

package com.qfedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @Author pengyu
 * @Date 2022/9/5 15:10
 */
@WebServlet("/ck2")
public class CookieServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得Cookie 通过请求从浏览器来得到cookie
        Cookie[] cookies = req.getCookies();

        //判断cookies是否为空,不加判断的话可能会出现空指针异常

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();

                //解码
                String u = URLDecoder.decode(name, "UTF-8");
                String v = URLDecoder.decode(value, "UTF-8");

                System.out.println(u + "=" + v);
            }
        }

        //上面判断可以写为
        for (int i = 0;cookies != null && i < cookies.length; i++) {

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Session

存在于服务器(可以用于用户退出功能)

小案例

登录界面

<%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2022/9/5
  Time: 10:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <form action="login2" method="post">
      用户名:<input type="text" name="username">
      <br>
      密码:<input type="password" name="password">
      <br>
      <input type="submit" value="提交">
    </form>
  </body>
</html>

登录请求类

package com.qfedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @Author pengyu
 * @Date 2022/9/5 17:13
 */
@WebServlet("/login2")
public class LoginServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //乱码处理
        req.setCharacterEncoding("utf-8");

        //创建session,保存登录用户数据
        HttpSession session = req.getSession();


        //获取前端登录的用户名和密码
        String userrname = req.getParameter("username");
        String password = req.getParameter("password");

        if (userrname.equals("admin") && password.equals("111")) {

            session.setAttribute("name","彭宇");
            req.setAttribute("user","admin");

            //携带数据转发
            req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
        } else {
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

用户的添加和删除请求

package com.qfedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author pengyu
 * @Date 2022/9/5 17:15
 */
@WebServlet("/user/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        String attribute = (String) session.getAttribute("name");
        System.out.println(attribute);
        //判断服务器中是否含有session来让用户是否登录
        if (attribute == null) {
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } else {
            System.out.println("您登陆了,并执行了/user/add操作");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
package com.qfedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author pengyu
 * @Date 2022/9/5 17:15
 */
@WebServlet("/user/update")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        String attribute = (String) session.getAttribute("name");
        if (attribute == null) {
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } else {
            System.out.println("您登陆了,并执行了/user/update操作");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

退出请求

package com.qfedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author pengyu
 * @Date 2022/9/5 17:47
 */
@WebServlet("/loginOut")
public class LoginOutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String name = (String) session.getAttribute("name");
        if (name == null) {
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } else {
            //如果已经登录,退出时销毁session
            session.invalidate();
            System.out.println("当前session已经销毁");
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

有什么问题欢迎讨论,大家共同学习进步

最后

以上就是现实指甲油为你收集整理的转发和重定向、Cookie和Session的全部内容,希望文章能够帮你解决转发和重定向、Cookie和Session所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(39)

评论列表共有 0 条评论

立即
投稿
返回
顶部