当前位置:网站首页>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
边栏推荐
- OpenSea PHP开发包
- "Daily practice, happy water" 1108 IP address invalidation
- 台式电脑连不上wifi怎么办
- Immutable學習之路----告別傳統拷貝
- Wechat likes to pay attention to the solution of invalid automatic reply
- The consciousness of a programmer
- Coordinate system left multiply right multiply
- Use of deferred environment variable in gbase 8s
- 「 每日一练,快乐水题 」1108. IP 地址无效化
- Web3 DApp用户体验最佳实践
猜你喜欢

Record small knowledge points

halcon之区域:多种区域(Region)生成(3)

电脑的dwg文件怎么打开

How do the defi protocols perform under this round of stress test?

My IC journey - the growth of senior chip design verification engineers - "Hu" said that IC engineers are perfect and advanced

「 每日一练,快乐水题 」1108. IP 地址无效化

OLAP analysis engine kylin4.0

本轮压力测试下,DeFi协议们表现如何?

ASEMI三相整流桥的工作原理

Which programming language is the most cumbersome to implement Hello world?
随机推荐
Opensea PHP development kit
What if the desktop computer is not connected to WiFi
CTF_ Web: Advanced questions of attack and defense world expert zone WP (15-18)
Successfully solved: selenium common. exceptions. TimeoutException: Message: timeout: Timed out receiving message from
Gbase 8s parallel operation problem scenario description
Cascading deletion of gbase 8s
Gbase 8s index R tree
Wechat likes to pay attention to the solution of invalid automatic reply
Vscode 设置clang-format
Package for gbase 8s
Web3 DApp用户体验最佳实践
OpenSea PHP开发包
高效的NoSQL数据库服务Amozon DynamoDB体验分享
JS' sort() function
After the newly assigned variable of the applet is modified, the original variable will also be modified
《牛客刷verilog》Part I Verilog快速入门
坐标系左乘右乘
电脑的dwg文件怎么打开
Le chemin de l'apprentissage immutable - - Adieu à la copie traditionnelle
Blob page in gbase 8s