Detailed tutorial on Java Web practice (XX) cookie practice

Miss Zhu 2022-02-13 08:37:21 阅读数:877

detailed tutorial java web practice

         because HTTP The agreement itself is stateless , It is impossible to record which browser the request comes from through the network protocol itself . As shown in the figure below , browser 1 And browser 2 Separate requests , For servers , adopt HTTP The request itself is no different .
 Insert picture description here
         If the server has no way to separate which browser the request comes from , Then you can't separate the relevance between requests , That is, there is no way to record the session between the browser and the server .
         So called conversation (Session), Generally speaking, users open a browser to visit a website , Click multiple links on the website 、 Button , Access multiple resources of the server , Until you close the browser , The whole process is called a conversation .
         since HTTP The protocol itself has no implementation status record , That requires the cooperation of server and browser , Record the conversation .
         The principle of implementation is Cookie and Session technology , among Session The conversation depends on Cookie Implementation of technology . This article will explain Cookie, The next article explains Session.
        Cookie The original meaning is biscuit , Transliterated as cookies , It refers to small pieces of information . Server generation Cookie,Cookie Is a string in the form of a key value pair ,Cookie It will respond to the hard disk or memory of the client where the browser is located . And you can set Cookie When the client exists , Such as a month or 60 second . Every time you make a request to visit the website , Will save the website in the client's all Cookie Send it to the server together .
         As shown in the figure below ,Cookie Use , You need to have at least the following two program functions in the server-side code :
1. Generate Cookie、 Set the time limit 、 Respond back to the browser
2. adopt request Object to get all the information sent by the browser Cookie, Select the desired , To deal with .
 Insert picture description here

         below , We do this through a function in the cross project Cookie actual combat . The function is shown in the figure below , When the login is successful , The login page of the browser will automatically record the last login account , The time limit is one minute .
 Insert picture description here
        UserController Class doLogin The method is to be responsible for the login function , When login is successful , Generate Cookie, Key value pair information is “username” And the login name filled in by the user , Set the time limit to 60 second , And corresponding to the browser .

// Login successful 
if (u != null) {

Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60);
response.addCookie(cookie);
response.sendRedirect("stu");
}

         such doLogin The method is finished , It will cookie Send it to the hard disk of the corresponding client of the browser and save it 60 second . Through the console Network tab of the browser , It can be observed that admin After the account is successfully logged in , Will respond to a person named username、 Value call admin Of Cookie:
 Insert picture description here
         here , Visit any path under this website , Will put the Cookie Send to server , Continue to the landing page , The test shows (JSessionID The next article will talk about ):
 Insert picture description here
         Since the claim carries username Of Cookie, That's on the server side showLogin In the method , Add a section to get the key value as “username” Of cookie that will do :
// get Cookies

String username="";
Cookie[] cookies = request.getCookies();
if(cookies!=null){

for(Cookie cookie:cookies){

if("username".equals(cookie.getName())){

username=cookie.getValue();
}
}
}
request.setAttribute("username", username);
request.getRequestDispatcher("WEB-INF/login.jsp").forward(request, response);

         stay login.jsp On the page , Only need request Get... From the scope username Value , Then in the account text box value Property .
complete login.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="java.util.*,entity.*"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<style> #main {
 width: 600px; margin: 120px auto; } #mes {
 color: red; text-align: center; margin-bottom: 20px; } </style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script> $(document).ready(function() {
 $("[name='username']").keyup(function() {
 $("#mes").text(""); }) }) </script>
</head>
<body>
<div id="main">
<div id="mes">
<%
String mes = (String) request.getAttribute("mes");
if (mes == null) {
mes = "";
}
out.print(mes);
String username=(String)request.getAttribute("username");
%>
</div>
<form class="form-horizontal" action="user">
<input type="hidden" name="type" value="doLogin" />
<div class="form-group">
<label class="col-sm-2 control-label"> account number </label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder=" Please enter your account number " name="username" value="<%=username %>">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> password </label>
<div class="col-sm-10">
<input type="password" class="form-control" placeholder=" Please input a password " name="password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary"> Sign in </button>
</div>
</div>
</form>
</div>
</body>
</html>
copyright:author[Miss Zhu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130837178090.html