当前位置:网站首页>Cookie & session & JSP (XII)
Cookie & session & JSP (XII)
2022-06-25 04:47:00 【hercu1iz】
Conversational Technology
1. conversation : A session contains multiple requests and responses .
* One session : The first time a browser sends a request to a server resource , Session creation , Until one side is disconnected
2. function : Between multiple requests within the scope of a session , Shared data
3. The way :
1. Client session technology :Cookie
2. Server side session technology :Session
Cookie:
1. Concept : Client session technology , Save data to client
2. Quick start :
* Use steps :
1. establish Cookie object , Data binding
* new Cookie(String name, String value)
2. send out Cookie object
* response.addCookie(Cookie cookie)
3. obtain Cookie, Get the data
* Cookie[] request.getCookies()
3. Realization principle
* Based on the response header set-cookie And the request header cookie Realization
4. cookie The details of the
1. Can I send more than one at a time cookie?
* Sure
* You can create multiple Cookie object , Use response Call several times addCookie Method to send cookie that will do .
2. cookie How long to save in the browser ?
1. By default , When the browser is closed ,Cookie The data is destroyed
2. Persistent storage :
* setMaxAge(int seconds)
1. Positive numbers : take Cookie The data is written to a file on the hard disk . Persistent storage . And designate cookie Survival time , After the time ,cookie The file is automatically invalidated
2. negative : The default value is
3. zero : Delete cookie Information
3. cookie Can you save Chinese ?
* stay tomcat 8 Before cookie Can't store Chinese data directly in .
* Need to transcode Chinese data --- It is generally used URL code (%E3)
* stay tomcat 8 after ,cookie Support Chinese data . Special characters are still not supported , It is recommended to use URL Encoding storage ,URL Decoding and parsing
4. cookie Sharing issues ?
1. Suppose it's in a tomcat Server , Deployed multiple web project , So in these web In the project cookie Can we share ?
* By default cookie Cannot share
* setPath(String path): Set up cookie The scope of acquisition . By default , Set the current virtual directory
* If you want to share , Then you can put path Set to "/"
2. Different tomcat Server room cookie Sharing issues ?
* setDomain(String path): If the primary domain name is the same , So many servers cookie Can be Shared
* setDomain(".baidu.com"), that tieba.baidu.com and news.baidu.com in cookie Can be Shared
5. Cookie The characteristics and functions of
1. cookie Store data in the client browser
2. Browser for single cookie There is a limit to the size of (4kb) as well as For the total under the same domain name cookie There is also a limit to the number (20 individual )
* effect :
1. cookie Generally used to store a small amount of less sensitive data
2. Without logging in , Complete the identification of the client by the server
6. Case study : Remember the last time you visited
1. demand :
1. Visit one Servlet, If it's a first visit , Prompt : Hello! , Welcome to .
2. If it's not my first visit , Prompt : welcome back , Your last visit was : Display time string
2. analysis :
1. May adopt Cookie To complete
2. On the server Servlet Determine if there is a name lastTime Of cookie
1. Yes : Not for the first time
1. The response data : welcome back , Your last visit was :2018 year 6 month 10 Japan 11:50:20
2. Write back to Cookie:lastTime=2018 year 6 month 10 Japan 11:50:01
2. No, : It's my first visit to
1. The response data : Hello! , Welcome to
2. Write back to Cookie:lastTime=2018 year 6 month 10 Japan 11:50:01
3. Code implementation :
package cn.itcast.cookie;
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;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the data format and encoding of the message body of the response
response.setContentType("text/html;charset=utf-8");
//1. Get all Cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;// No, cookie by lastTime
//2. Traverse cookie Array
if(cookies != null && cookies.length > 0){
for (Cookie cookie : cookies) {
//3. obtain cookie The name of
String name = cookie.getName();
//4. Determine if the name is :lastTime
if("lastTime".equals(name)){
// There is a reason Cookie, Not for the first time
flag = true;// Yes lastTime Of cookie
// Set up Cookie Of value
// Get the string of the current time , To reset Cookie Value , To resend cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan HH:mm:ss");
String str_date = sdf.format(date);
System.out.println(" Before coding :"+str_date);
//URL code
str_date = URLEncoder.encode(str_date,"utf-8");
System.out.println(" After the coding :"+str_date);
cookie.setValue(str_date);
// Set up cookie Life time of
cookie.setMaxAge(60 * 60 * 24 * 30);// A month
response.addCookie(cookie);
// The response data
// obtain Cookie Of value, Time
String value = cookie.getValue();
System.out.println(" Before decoding :"+value);
//URL decode :
value = URLDecoder.decode(value,"utf-8");
System.out.println(" After decoding :"+value);
response.getWriter().write("<h1> welcome back , Your last visit was :"+value+"</h1>");
break;
}
}
}
if(cookies == null || cookies.length == 0 || flag == false){
// No, , First visit
// Set up Cookie Of value
// Get the string of the current time , To reset Cookie Value , To resend cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan HH:mm:ss");
String str_date = sdf.format(date);
System.out.println(" Before coding :"+str_date);
//URL code
str_date = URLEncoder.encode(str_date,"utf-8");
System.out.println(" After the coding :"+str_date);
Cookie cookie = new Cookie("lastTime",str_date);
// Set up cookie Life time of
cookie.setMaxAge(60 * 60 * 24 * 30);// A month
response.addCookie(cookie);
response.getWriter().write("<h1> Hello! , Welcome to </h1>");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
Session: The main course
1. Concept : Server side session technology , Sharing data among multiple requests in a session , Save the data in the object on the server side .HttpSession
2. Quick start :
1. obtain HttpSession object :
HttpSession session = request.getSession();
2. Use HttpSession object :
Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)
3. principle
* Session The realization of depends on Cookie Of .
4. details :
1. When the client is shut down , The server does not shut down , Get twice session Is it the same ?
* By default . No .
* If you need the same , You can create Cookie, The key is JSESSIONID, Set the maximum lifetime , Give Way cookie Persistent save .
Cookie c = new Cookie("JSESSIONID",session.getId());
c.setMaxAge(60*60);
response.addCookie(c);
2. The client does not shut down , After the server is shut down , Acquired twice session Is it the same ?
* Not the same , But make sure the data is not lost .tomcat Automatically complete the following work
* session Passivation of :
* Before the server is shut down properly , take session Serialize objects to hard disk
* session Activation of :
* After the server starts , take session The file is converted to... In memory session Object can .
3. session When it was destroyed ?
1. Server down
2. session Object call invalidate() .
3. session Default expiration time 30 minute
Optional configuration modification
<session-config>
<session-timeout>30</session-timeout>
</session-config>
5. session Characteristics
1. session Data used to store multiple requests for a session , There is a server side
2. session Can store any type , Data of any size
* session And Cookie The difference between :
1. session Store data on the server side ,Cookie On the client side
2. session There is no data size limit ,Cookie Yes
3. session Data security ,Cookie Relative to insecurity
JSP
1. Concept :
* Java Server Pages: java Server side page
* It can be understood as : A special page , Where you can specify either the definition html label , You can also define java Code
* Used to simplify writing !!!
2. principle
* JSP It's essentially one Servlet
3. JSP Script for :JSP Definition Java The way the code works
1. <% Code %>: Defined java Code , stay service In the method .service What can be defined in the method , What can be defined in this script .
2. <%! Code %>: Defined java Code , stay jsp Converted java Class member location .
3. <%= Code %>: Defined java Code , It will be output to the page . What can be defined in the output statement , What can be defined in this script .
4. JSP Built in objects for :
* stay jsp There is no need to get and create , Objects that can be used directly
* jsp Altogether 9 Built in objects .
* Learning today 3 individual :
* request
* response
* out: Character output stream object . You can output data to the page . and response.getWriter() similar
* response.getWriter() and out.write() The difference between :
* stay tomcat Before the server actually responds to the client , Will look for response Buffer data , Look again out Buffer data .
* response.getWriter() Data output is always out.write() Before
1. Instructions
* effect : Used for configuration JSP page , Import resource file
* Format :
<%@ Instruction names Property name 1= Property value 1 Property name 2= Property value 2 ... %>
* classification :
1. page : To configure JSP Page
* contentType: Equate to response.setContentType()
1. Set the mime Type and character set
2. Set up current jsp Page code ( It can only be advanced IDE To take effect , If you use low-level tools , You need to set pageEncoding Property to set the character set of the current page )
* import: Guide pack
* errorPage: When the current page is abnormal , Will automatically jump to the specified error page
* isErrorPage: Identifies whether or not the current is also an error page .
* true: yes , You can use built-in objects exception
* false: no . The default value is . You can't use built-in objects exception
2. include : The page contains . Import the resource file of the page
* <%@include file="top.jsp"%>
3. taglib : Import resources
* <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
* prefix: Prefix , Self defined
2. notes :
1. html notes :
<!-- -->: Only comment html code snippet
2. jsp notes : Recommended
<%-- --%>: Can annotate all
3. Built-in objects
* stay jsp There is no need to create , Objects used directly
* Altogether 9 individual :
Variable name The real type effect
* pageContext PageContext The current page shares data , You can also get eight other built-in objects
* request HttpServletRequest Multiple resources accessed at one request ( forward )
* session HttpSession Between multiple requests in a session
* application ServletContext All users share data
* response HttpServletResponse The response object
* page Object Current page (Servlet) The object of this
* out JspWriter Output object , Data output to page
* config ServletConfig Servlet Configuration objects for
* exception Throwable Exception object
边栏推荐
- 本轮压力测试下,DeFi协议们表现如何?
- Upgrade PHP to php7 The impact of X (I). The problem of session retention. Keep login
- Record small knowledge points
- At the age of 30, I began to learn programming by myself. Is it still time for me to have difficulties at home?
- CTF_ Web: Changan cup-2021 old but a little new & asuka
- Gbase 8s stored procedure execution and deletion
- Triangle class (construction and deconstruction)
- leetcode1221. Split balance string
- 【Keil】ADuCM4050官方库的GPIO输出宏定义
- 融合CDN,为客户打造极致服务体验!
猜你喜欢

Startup mode of SoC verification environment

Separation of storage and computing in Dahua cloud native database

"Daily practice, happy water" 1108 IP address invalidation

《牛客刷verilog》Part I Verilog快速入门

CTF_ Web: deserialization of learning notes (II) CTF classic test questions from shallow to deep

Upgrade PHP to php7 The impact of X (2), the obsolescence of mcrypt decryption

Web3 DAPP user experience best practices

魔法猪系统重装大师怎么使用
![[esp32 learning path 6 - Flash encryption]](/img/4c/f317ca4823dca50a9bccd285967ab0.png)
[esp32 learning path 6 - Flash encryption]

Cnpm: unable to load file c:\users\administrator\appdata\roaming\npm\cnpm PS1 because running scripts is prohibited on this system.
随机推荐
小白一键重装官网下载使用方法
[Flink] problems and solutions of the continuous growth of checkpoint size in rocksdb incremental mode
js的call()和apply()
At the age of 30, I began to learn programming by myself. Is it still time for me to have difficulties at home?
SOC验证环境的启动方式
哪个编程语言实现hello world最烦琐?
"Daily practice, happy water" 1108 IP address invalidation
Gbase 8s stored procedure flow control
JS' sort() function
Leader: who can use redis expired monitoring to close orders and get out of here!
【FLink】access closed classloader classloader.check-leaked-classloader
Multithreading structure of gbase 8s
Opensea PHP development kit
为什么TCP握手刚刚好是3次呢?
OOP vector addition and subtraction (friend + copy construction)
Use text analysis to identify the main gender in a text
Gbase 8s stored procedure syntax structure
【图像融合】基于matlab方向离散余弦变换和主成分分析图像融合【含Matlab源码 1907期】
冰冰学习笔记:循环队列的实现
Which programming language is the most cumbersome to implement Hello world?