当前位置:网站首页>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

边栏推荐
- Introduction to C language (8)
- 分布式相关面试题总结
- Web side 3D visualization engine hoops communicator reads 10g super large model test | digital twin Technology
- shardingjdbc踩坑记录
- 动态性能视图概述
- 一文掌握mysql数据库审计特点、实现方案及审计插件部署教程
- Distributed system and distributed database system (Introduction)
- Unity metaverse (II), mixamo & animator hybrid tree and animation fusion
- Utils connection pool
- Crawler - > tpimgspider
猜你喜欢

一文掌握mysql数据库审计特点、实现方案及审计插件部署教程

Wrong Addition

Establishment and use of openstack cloud platform

MySQL implementation plan

Unity metaverse (II), mixamo & animator hybrid tree and animation fusion

Unity Metaverse(二)、Mixamo & Animator 混合树与动画融合

总结软件测试岗的那些常见高频面试题

Network trimming: a data driven neuron pruning approach towards efficient deep architectures paper translation / Notes

Idea settings set shortcut keys to convert English letters to case in strings

File parsing (JSON parsing)
随机推荐
2022.7.22DAY612
Devaxpress.xtraeditors.datanavigator usage
为啥谷歌的内部工具不适合你?
Common database commands (special for review)
2019 ZTE touyue · model compression scheme
MMOE multi-objective modeling
Web page basic label
WCF deployed on IIS
《门锁》引爆独居安全热议 全新海报画面令人窒息
[uniapp] encapsulation of multiple payment methods
JWT quick start
Introduction to C language (8)
Shardingjdbc pit record
Master slave database deployment
Leetcode 206. reverse chain list (2022.07.25)
A tutorial for mastering MySQL database audit characteristics, implementation scheme and audit plug-in deployment
Reading and writing properties file
1. MySQL Architecture [MySQL advanced]
Next item recommendations in short sessions
Parameterization of JMeter performance test using CSV file