LOADING

加载过慢请开启缓存 浏览器默认开启

2023/11/19

java学习(cookie、session、JSP与MVC)

总结下cookie和session,由于HTTP是非状态式的通信协议,为了保存一次连续通信的某些信息(例如登录信息),java提供了HttpSession类,该类可以根据随机数+时间+jvmID来生成一串JsessionID,用以标识客户端发来的一次通信对应的会话,然后服务器生成这存储这一串ID以及对应的HttpSession的信息(来源于输入,例如用户名),并自动通过响应头的set-cookie字段让浏览器通过请求头的cookie字段保存这串JsessionID,下次访问时会带着这串ID继续访问,服务器也可以根据cookie中(request.getSession()实际获得的就是cookie中的内容?)的这串ID获得其对应的信息。

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;


//!!!!由于tomcat服务器默认"localhost:8080/"目录运行的是ROOT.war文件,
// 所以不是以ROOT命名的文件,除了urlPatterns会默认加上,其他url都要补上war的文件名,这样才能正确跳转!!!!
@WebServlet(urlPatterns = "/login")
public class HTTPsession extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.write("<h1>Sign In</h1>");
        pw.write("<form action=\"/demo_web-1.0-SNAPSHOT/login\" method=\"post\">");
        pw.write("<p>Username: <input name=\"username\"></p>");
        pw.write("<p>Password: <input name=\"password\" type=\"password\"></p>");
        pw.write("<p><button type=\"submit\">Sign In</button> <a href=\"/demo_web-1.0-SNAPSHOT/\">Cancel</a></p>");
        pw.write("</form>");  //通过表单发送POST请求时,请求的路径是不变的,仍为当前路径
        pw.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        String expectedPassword = name.toLowerCase();
        HttpSession session = request.getSession();  //HttpSession注意同名类问题!
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        if (name != null) {
            if (password.equals(expectedPassword)) {  //字符串判断相等用.equals()!!
                session.setAttribute("name", name);
                response.sendRedirect("/demo_web-1.0-SNAPSHOT/");
            } else {
                //pw.flush()之后,html页面就不再接收后续发送的响应了!
                //response页面一旦调用一个flush()方法后,代表该response已经提交, 执行完毕,不能再使用
                //response是服务端对客户端请求的一个响应,其中封装了响应头、状态码、内容等,
                // 服务端在把response提交到客户端之前,会向缓冲区内写入响应头和状态码,然后将所有内容flush。
                //这就标志着该次响应已committed(提交)。对于当前页面中已经committed(提交)的response,
                // 就不能再使用这个response向缓冲区写任何东西

               pw.write("<html><body><h2>密码不正确!</h2></body></html>");
               pw.write("<script type=\"text/javascript\">location=\"/demo_web-1.0-SNAPSHOT/login\";</script>");
               pw.flush();

               //下:下面的代码不会再执行,因为一次flush之后就已经提交了response,不能再使用该response,想要实现页面显示信息再自动跳转
                //参考上面的用javascript实现自动跳转,会先显示密码不正确再跳转
               try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }

                response.sendRedirect("/demo_web-1.0-SNAPSHOT/login");
                //!!!Redirect都是get请求方式请求的
                //上
            }
        } else {
            pw.write("<html><body><h2>请输入用户名!</h2></body></html>");
            pw.flush();
            response.sendRedirect("/demo_web-1.0-SNAPSHOT/login");
        }
    }
}
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/")
public class mainsession extends HttpServlet {  //Servlet类必须声明为public!!!这样才能被包外的tomcat JVM访问到!!!

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name=(String) request.getSession().getAttribute("name");
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw=response.getWriter();
        pw.write("<h1>Welcome, " + (name != null ? name : "Guest") + "</h1>");
        if (name == null) {
            // 未登录,显示登录链接:
            pw.write("<p><a href=\"/demo_web-1.0-SNAPSHOT/login\">Sign In</a></p>");
        } else {
            // 已登录,显示登出链接:
            pw.write("<p><a href=\"/demo_web-1.0-SNAPSHOT/signout\">Sign Out</a></p>");  //a标签默认是发送get请求
        }
        pw.flush();
    }

}
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(urlPatterns = "/signout")
public class signoutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 从HttpSession移除用户名:
        request.getSession().removeAttribute("user");
        response.sendRedirect("/demo_web-1.0-SNAPSHOT/login");
    }

}
<%--
  Created by IntelliJ IDEA.
  User: 徐昊岩
  Date: 2023/11/19
  Time: 13:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Hello-jsp!</title>
</head>
<body>
<p>
    <%@ page import="java.io.*" %>
    <%@ page import="java.time.LocalDateTime" %>
    <%= "Time is"     %>
    <span style="color:red">
    <% LocalDateTime s =LocalDateTime.now(); %>
    <%= s %>
        <%= s.toLocalDate() %>
        <%= s.toLocalTime() %>
    </span>
</p>
</body>
</html>