当前位置:网站首页>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
边栏推荐
- Package for gbase 8s
- Gbase 8s memory management
- File upload vulnerability shooting range upload labs learning (pass1-pass5)
- Upgrade PHP to php7 X (III) failure of wechat payment callback
- What if the desktop computer is not connected to WiFi
- 重磅直播 | 相移法+多频外差之数学原理推导+实现
- Use text analysis to identify the main gender in a text
- MySQL concept and operation (III)
- Mongodb cluster
- Construction scheme of distributed websocket
猜你喜欢

Web3 DApp用户体验最佳实践

The SQL response is slow. What are your troubleshooting ideas?
Triangle class (construction and deconstruction)

The solution of wechat applet switchtab unable to take parameters

多睡觉,能减肥,芝加哥大学最新研究:每天多睡1小时,等于少吃一根炸鸡腿...

SOC验证环境的启动方式

为什么TCP握手刚刚好是3次呢?

Leader: who can use redis expired monitoring to close orders and get out of here!
![[image fusion] image fusion based on MATLAB directional discrete cosine transform and principal component analysis [including Matlab source code 1907]](/img/a1/f7a35a04e180e89d7f2fdbf89c1160.jpg)
[image fusion] image fusion based on MATLAB directional discrete cosine transform and principal component analysis [including Matlab source code 1907]

Xiaobai learns MySQL - Statistical 'opportunism'
随机推荐
Region of Halcon: generation of multiple regions (3)
JS arguments
三角形类(构造与析构)
Basic introduction of gbase 8s blocking technology
PostgreSQL database Wal - RM_ HEAP_ ID logging action
Calculate student grade (virtual function and polymorphism)
本轮压力测试下,DeFi协议们表现如何?
深度学习——几种学习类型
绝了!自动点赞,我用 PyAutoGUI!
js的arguments
Gbase 8s overall architecture
为什么SQL语句命中索引比不命中索引要快?
使用文本分析识别一段文本中的主要性别
小白一键重装官网下载使用方法
多睡觉,能减肥,芝加哥大学最新研究:每天多睡1小时,等于少吃一根炸鸡腿...
Deep learning - several types of learning
parallel recovery slave next change & parallel recovery push change
固态硬盘开盘数据恢复的方法
Gbase 8s stored procedure flow control
cannot import name ‘escape’ from ‘jinja2’【成功解决】