当前位置:网站首页>JSP implicit object -- scope
JSP implicit object -- scope
2022-07-26 07:58:00 【Super Qi】
jsp Implicit objects - Scope
session object :
1. Definition :
a. session Object is a session between client and server ( Connect to the server and start , Until the client is disconnected from the server )
b. javax.serlvet.http.HttpSession Interface instance of
2. effect :
session Object is used to save the information of each customer , Used to detect the usage status of each user ( Operation state )
3. perform :
session Object will give the new user a unique identifier session id And save it in the client's cookie in , Used to distinguish other customers
*session The information is stored in the client container ,session id Saved in the client's cookie in
4. Valid time :(session Validity period of space )
a. The user closes the browser program he is browsing
b. Shut down the web server
c. The user did not make a request to the server for more than the preset time ,Tomcat The server defaults to 30 minute
d. End of run session The program
5. session The common method of
getAttribute(String name): Gets the property associated with the specified name .
getAttributeNames(): return session The object of every attribute stored in the object
getCreateTime(): Back to create session Time of object , The unit is millisecond
getId(): return session The object is on the server side id Number
getLastAccessedTime(): return session The request time when the object last sent the request
getMaxInactiveInterval(): return session The lifetime of the object , The unit is in seconds
setMaxInactiveInterval( int interval): Set up session The lifetime of the object , The unit is in seconds
setAttribute(String name, java.lang.Object value): Set the attribute value of the specified name attribute , And store it in session In the object
invalidate(): The destruction session object , Make the objects bound to it invalid
6. visit session Data in
a. establish session Variable :
session.setAttribute(" Variable name ", Variable content (String type ));
b. return session Data in ( obtain session The data in ):
session.getAttribute(" Variable name "); // The type of return is Object type
c. eliminate session The variables in the :
session.removeAttribute(" Variable name "); // Eliminate the named session Object's data
d. end session:
session.invalidate(); // take session end , The destruction session object
7.session Object instances :
a. establish session Object and get session Object's data
/***Demo1.jsp***/
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>session</title>
</head>
<body>
<%
session.setAttribute("information"," towards session Save data in ");
response.sendRedirect("Demo1_to.jsp");
%>
</body>
</html>
/***Demo1_to.jsp***/
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>session Save the information page </title>
</head>
<body>
<%
out.print(session.getAttribute("information"));
%>
</body>
</html>
b. Set up session Object lifetime and cleanup assignments session Data of object name
/***Demo1_to.jsp***/
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>session Save the information page </title>
</head>
<body>
<%
out.print(session.getAttribute("information"));
%>
<%
session.setMaxInactiveInterval(30);
%>
<%
session.removeAttribute("information");
if (session.getAttribute("information")== null){
out.print("session object information non-existent !");
}
%>
</body>
</html>
8. session Three methods of timeout setting
a. stay java Set... In the code :
session.setMaxInactiveInterval(300); //session Without operation 300 Seconds out
b. In the project web.xml Set in :
<!-- Set the value to 0、-1 It means never timeout , In minutes -->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
c. Set in the application server
priority :a > b > c
Code instance :
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>Title</title>
</head>
<body style="font-size: 40px">
<%! int number = 1; // Login times of initialization interface %>
<%
Object obj = session.getAttribute("number"); // obtain session Inside number Value
if (obj == null){ // Set up number Pair value of // Set up session The value of the object
session.setAttribute("number",String.valueOf(number));
}else{
number = Integer.parseInt(obj.toString());
number++; // Count the number of visits
session.setAttribute("number",number);
}
session.setMaxInactiveInterval(2);
%>
You visit the... Of this website <%=number %> Users , welcome !
</body>
</html>
9. session Object instances
/***buy.jsp***/
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title> customer </title>
</head>
<body>
<form action="goods.jsp">
<b> Enter your name to connect to the first department store </b><br>
<input type="text" name="name">
<input type="submit" value=" Submit name ">
</form>
</body>
</html>
/***goods.jsp***/
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title> The supermarket </title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
Object name = request.getParameter("name");
session.setAttribute("name",name);
%>
<form action="account.jsp">
<b> Please enter the goods you want to buy and connect to the checkout </b><br>
<input type="text" name="goods">
<input type="submit" value=" Submit goods ">
</form>
</body>
</html>
/***account.jsp***/
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Settle accounts </title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
Object goods = request.getParameter("goods");
session.setAttribute("goods",goods);
%>
<b> This is the checkout </b><br>
<b> The customer's name is :</b><%=session.getAttribute("name") %><br>
<b> What products do customers buy :</b><%=session.getAttribute("goods") %>
</body>
</html>
application object
1. Definition
Application It is a data access area shared by all online users . Server startup application The object is created , Until the web server shuts down or exceeds the scheduled time application The object will disappear automatically . Customers browse various web pages ,application It's all the same .
2. session And application The difference between
session The object is dedicated to each customer , Private , Store private variables
application The object is a shared data access area , Public storage of global variables
3. Method
1. setAttribute(String name,Object o);// Set up application Object's attribute name and its attribute value
2. getAttribute(String name);// Get the attribute value of the specified attribute name
3. getAttributeNames();// obtain Enumeration Type of application An initial value of an object
4. getServerInfo();// obtain servlet Current version information of the compiler
5. getContext(String uripath);// Get the specified WebApplication Of application object
6. getMimeType(String file);// obtain application Object specifies the MIME type
7. getResource(String path);// obtain application Object specifies the url route
8. getServlet(String name);// obtain application Object specified Servlet
4. access application Data in
1. establish application object
application.setAttribute(" Variable name "," Variable content ")
2. obtain application The object is worth
application.getAttribute(" Variable name ");
application.getAttributeNames();// The return is application The collection object of all object names in , The data type is array
3. Delete application object
application.removeAttribute(" Variable name ");
example 1: Message board
/***inputMessage.jsp***/
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Input information </title>
</head>
<body>
<form action="checkMessage.jsp" method="post">
Please enter a name :<input type="text" name="name"><br>
Please enter a title :<input type="text" name="title"><br>
Please enter the content :<textarea name="message" cols="40" rows="10"></textarea><br>
<input type="submit" value=" Leaving a message. ">
</form>
<form action="showMessage.jsp" method="post" id="form2">
<input type="submit" value=" Check the message board ">
</form>
</body>
</html>
/***checkMessage.jsp***/
%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="jdk.nashorn.internal.ir.CallNode" %>
<%@ page import="java.util.logging.SimpleFormatter" %>
<%@ page import="java.util.Calendar" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Information processing </title>
</head>
<body>
<%!
List<String> v = new ArrayList<String>();
int i = 0;
%>
<%
String datetime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Calendar.getInstance().getTime());// Get system time
%>
<%
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String title = request.getParameter("title");
String message = request.getParameter("message");
%>
<%
if(name == null || "".equals(name.trim())){
name = " Net friend " + (int)(Math.random()*10000+10000); // When name by null Will output 5 Random number of digits
}
if (title == null || "".equals(title.trim())){
title = " nothing ";
}
if (message == null || "".equals(message.trim())){
message = " nothing ";
}
%>
<%
i++;
String str = " The first " + i + " floor " + ". Message sender :" + name + ". title :" + title + ". Content :" + message + ". Time :" + datetime + ".<hr>";
v.add(str);
application.setAttribute("message",v);
%>
Message success :<a href="inputMessage.jsp"> Return to the message board </a>
</body>
</html>
/***showMessage.jsp***/
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.StringTokenizer" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Message content </title>
</head>
<body>
<%
Object o = application.getAttribute("message");
if (o == null) {
out.print(" No one has left a message yet ");
} else {
List<String> v = (ArrayList<String>) o;
for (int i = v.size() - 1; i >= 0; i--) {
StringTokenizer st = new StringTokenizer(v.get(i), ".");
while (st.hasMoreElements()) {
out.print(st.nextToken() + "<br>");
}
}
}
%>
</body>
</html>
example 2: Page counters ( It needs to be improved )
<%@ page import="java.util.StringTokenizer" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Page counters </title>
</head>
<body style="font-size: 40px">
<%
int i = 0;
if (application.getAttribute("num") == null) {
application.setAttribute("num", 1);
} else {
if (session.isNew()) { // Determine whether it is a new user
String str = application.getAttribute("num").toString();
i = Integer.parseInt(str);
i++;
application.setAttribute("num", i);
}
}
%>
You are the first <%=application.getAttribute("num") %> Visitors
</body>
</html>
5. session Object and the application The difference between objects

6. application Object instances
/***chat.jsp***/
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Chat </title>
</head>
<body>
<%request.setCharacterEncoding("UTF-8"); %>
<%
if (application.getAttribute("information") == null) {
application.setAttribute("information", "Start:");
out.print((String) application.getAttribute("information"));
}
if (request.getParameter("information") != null) {
if (request.getParameter("information").trim() == "end") { // Judge the end of the conversation , unsuccessful
application.removeAttribute("information");
out.print(" End of conversation !");
}
String information = request.getParameter("information");
information = (String) application.getAttribute("information") + "<br>" + information; // Copy the previous conversation to application In the object
application.setAttribute("information", information);
out.print((String) application.getAttribute("information"));
}
%>
<form action="chat.jsp">
<input type="text" name="information">
<input type="submit" value=" send out ">
</form>
</body>
</html>
page object
1. Definition
a. page Object represents the running by jsp File generated class objects , This object is in jsp It's not often used in English
b. java.lang.Object class , have access to Object Class method
2. effect
Set to execute the response request of the current page Servlet Class , Only in jsp The page is legal .page The implied object essentially contains the present Servlet Variables referenced by interfaces , Can be seen as this Another name for
3. Method

边栏推荐
- Enterprise private network construction and operation and maintenance
- 总结软件测试岗的那些常见高频面试题
- Machine learning related competition website
- Matlab-二/三维图上绘制黑点
- Simulation of transfer function step response output of botu PLC first-order lag system (SCL)
- 【uniapp】多种支付方式封装
- 2022-07-09 group 5 Gu Xiangquan's learning notes day02
- ARIMA model for time series analysis and prediction
- MySQL implementation plan
- OVSDB
猜你喜欢

Lambda and stream

Basic knowledge of convolutional neural network

Audio and video learning (10) -- PS streaming

什么是消息订阅和发布?

JWT quick start

File parsing (JSON parsing)
![[uniapp] encapsulation of multiple payment methods](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[uniapp] encapsulation of multiple payment methods

以太网交换安全

Selenium: detailed explanation of browser crawler use (I)

Kdd2022 | uncover the mystery of Kwai short video recommendation re ranking, and recommend the new SOTA
随机推荐
Using ordered dictionary to copy pcap files
ShardingSphere数据分片
Leetcode 206. reverse chain list (2022.07.25)
[uniapp] encapsulation of multiple payment methods
Hystrix配置简单说明
如何关闭高位端口
OVSDB
2022.7.22DAY612
API (common class 2)
给项目日志加上traceid
微服务feign调用时候,token丢失问题解决方案
QT listview add controls and pictures
Common templates for web development
What are the differences between FileInputStream and bufferedinputstream?
Network trimming: a data driven neuron pruning approach towards efficient deep architectures paper translation / Notes
Libevent custom event (asynchronous)
程序环境和预处理
Network ()
No valid host was found when setting up openstack to create an instance There are not enough hosts available. code:500
Solution to the problem of token loss when microservice feign is called