Monitor Listener

Learning goals

Case study - Use the monitor to complete the birthday wish

One 、 Monitor Listener

javaEE Include 13 Door specification In the course, we mainly study servlet technology and jsp technology

among servlet The specification includes three technical points :servlet  listener  filter

1. What is a monitor ?

A listener is a component that monitors the state changes of an object

The concept of the listener :

Event source : Monitored objects   ----- Three domain objects request  session  servletContext

Monitor : Listen to the event source object   Changes in the state of the event source object trigger the listener ---- 6+2

Register listener : Bind the listener to the event source

Response behavior : When the listener detects the state change of the event source The function code involved ---- Programmers write code

2. What are the monitors ?

The first dimension : According to the monitored objects :ServletRequest Domain    HttpSession Domain       ServletContext Domain

The second dimension : The content of monitoring is divided into : The creation and destruction of a listening domain object change the properties of the listening domain object

3. A listener that monitors the creation and destruction of three domain objects

(1) monitor ServletContext A listener for creating and destroying domains ServletContextListener

1)Servlet Life cycle of domain

When to create : Server start creation

When to destroy : The server is shut down and destroyed

2) The writing steps of the listener ( a key ):

a、 Write a listener class to implement the listener interface

b、 The way to cover the listener

c、 Need to be in web.xml To configure --- register

3) How to monitor :

4) The configuration file :

5)ServletContextListener The main function of the monitor

a、 Initialization work : Initialize object
Initialization data ---- Load database driver   Initialization of connection pool

b、 Load some initialized configuration files --- spring Configuration file for

c、 Task scheduling ---- Timer ----Timer/TimerTask

Task scheduling :

(2) monitor Httpsession The creation of a domain depends on the destruction of the listener HttpSessionListener

1)HttpSession Object lifecycle

When to create : First call request.getSession Created on

When to destroy : The server is shut down and destroyed   session Be overdue   Destroy by hand

2)

HttpSessionListener Methods

(3) monitor ServletRequest Listeners for domain creation and destruction ServletRequestListener

1)ServletRequest Life cycle of

establish : Every request is created request

The destruction : End of request

2)ServletRequestListener Methods

4. Listen to the property changes of the three domain objects

(1) General methods of domain objects :

setAttribute(name,value)

--- The method that triggers the listener that adds the property

--- The method that triggers the listener that modifies the property

getAttribute(name)

removeAttribute(name)

--- The method that triggers the listener to delete a property

(2)ServletContextAttibuteListener Monitor

(3) HttpSessionAttributeListener Monitor ( ditto )

(4) ServletRequestAriibuteListenr Monitor ( ditto )

5. And session The listener associated with the bound object in ( Object aware listeners )

(1) About to be bound to session There are several states of objects in

Binding state : Just one object is put into session domain

Unbound state : It's this object from session Domain removed

Passivation state : Yes, it will session Object persistence in memory ( serialize ) To disk

Activation state : Is to restore the objects on the disk to session In the memory

Interview questions : When there are a lot of users , How to optimize the server ?

Passivation and activation can be used , For example, more people visit Jingdong , Some of them haven't been moving for a long time , You can use passivation to store data on disk to make more space for memory , Achieve the effect of tuning .

(2) Binding and unbinding listeners HttpSessionBindingListener

(3) Passive and activated monitors HttpSessionActivationListener

Take an object ( for example user) Inherit the interface above , Remember to achieve Serializable, So that it can be stored in the disk .

Configuration files are available Specifies the object passivation time --- How long does the object not have to be passivated

stay META-INF Next create a context.xml

<Context>

<!-- maxIdleSwap:session Objects in are passivated as long as they are not in use -->

<!-- directory: The file of the passivated object is written to which directory on the disk   Configure the passivation object file in work/catalina/localhost/ Passivation files -->

<Manager
className="org.apache.catalina.session.PersistentManager"maxIdleSwap="1">

<Store
className="org.apache.catalina.session.FileStore"
directory="itcast205" />

</Manager>

</Context>

Passivated to work/catalina/localhost/ The file of

Two 、 Mailbox server

1. The basic concept of mailbox server

The client of the mail : It can only be installed on the computer or in the form of a web page

Mail server : Play the role of mail acceptance and push

Protocol for sending mail :

agreement : It's the constraint of data transmission

An agreement to accept mail :POP3   IMAP

Protocol for sending mail :SMTP

2. Email sending process

3. Installation of mailbox server

1) Double click the mailbox server software

2) Configure the mailbox server

4. Installation of mailbox client

5. Email code

public class MailUtils {
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 1. Create a program and mail server session object Session Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", "smtp.126.com");
props.setProperty("mail.smtp.auth", "true");// Specifies that validation is true // Create validators
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("haohao_itcast", "hao12345");
}
}; Session session = Session.getInstance(props, auth); // 2. Create a Message, It's the equivalent of email content
Message message = new MimeMessage(session); message.setFrom(new InternetAddress("haohao_itcast@126.com")); // Set sender message.setRecipient(RecipientType.TO, new InternetAddress(email)); // Set the sending method and receiver message.setSubject(" User activation ");
// message.setText(" This is an activation email , please <a href='#'> Click on </a>"); message.setContent(emailMsg, "text/html;charset=utf-8"); // 3. establish Transport Used to send mail to Transport.send(message);
}
}

6、 ... and 、 Case study - Use the monitor to complete the birthday wish

public class BirthdayListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
// When web App launch Turn on task transfer --- Function to send email on the user's birthday
// Turn on a timer
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() { @Override
public void run() {
// Email the current birthday user
//1、 The person who got today's birthday
// Get today's date
SimpleDateFormat format = new SimpleDateFormat("MM-dd");
String currentDate = format.format(new Date());
// Query today's birthday from the data according to the current time
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from customer where birthday like ?";
List<Customer> customerList = null;
try {
customerList = runner.query(sql, new BeanListHandler<Customer>(Customer.class) ,"%"+currentDate+"%");
} catch (SQLException e) {
e.printStackTrace();
} //08-18
//2、 email
if(customerList!=null&&customerList.size()>0){
for(Customer c : customerList){
String emailMsg = " dear :"+c.getRealname()+", Happy birthday, !";
try {
MailUtils.sendMail(c.getEmail(), " Birthday wishes ", emailMsg);
System.out.println(c.getRealname()+" The mail has been sent ");
} catch (MessagingException e) {
e.printStackTrace();
}
}
} }
}, new Date(), 1000*10);
// In actual development, the starting time is a fixed time
// The actual development interval is 1 God
} @Override
public void contextDestroyed(ServletContextEvent sce) { } }

【JAVAWEB Learning notes 】23_Listener More articles about email server

  1. JavaWeb Summary of learning notes Contents

    JavaWeb Study note 1 : XML analysis JavaWeb Study note 2 Http The protocol and Tomcat The server JavaWeb Learning notes 3 Servlet JavaWeb Study note 4 request&resp ...

  2. javaweb Study notes, make up lessons

    javaweb Study notes, make up lessons * JavaWeb: * Use Java Language development projects based on the Internet * Software architecture : 1. C/S: Client/Server client / Server side * There is a client in the user's local area ...

  3. JavaWeb Learning notes ( Two )—— Tomcat The server

    One .Web Development Overview 1.1 Web Common concepts in development [B/S Systems and C/S System ] Brower/Server: browser The server System ----- Website Client/Server: client The server System - ...

  4. 【JAVAWEB Learning notes 】06_jQuery Basics

    Pick up 05 Learning notes of . Four . Use JQ Complete the two-level linkage between provinces and cities 1. Demand analysis Use jquery Complete the two-level linkage between provinces and cities 2. Technical analysis 2.1 Array traversal operation Mode one : $(function(){ // Future generations / Totally unselected $(& ...

  5. Javaweb Learning notes ( One )

    One .javaweb Learning is the detail needed 1. Send response header related methods 1).addHeader() And setHeader() It's all settings HTTP Response header field of the protocol , The difference is that addHeader() Method can add a response with the same name ...

  6. 【JAVAWEB Learning notes 】 The real battle of online mall : Environment construction and user module completion

    The real battle of online mall Today's mission Complete the function of user module 1.1      The real battle of online mall : 1.1.1    Demonstrate the functions of online mall : 1.1.2    The purpose of making : Flexible use of knowledge learned to complete the actual battle of the mall . 1.1.3    ...

  7. JavaWeb Learning notes 8 Monitor

    Monitor Listener jservlet The specification includes three technical points :servlet :listener :filter: A listener is a component that monitors the state changes of an object . The concept of listener, event source : Monitored objects ( Three domains ...

  8. JavaWeb Study ( Two )———Tomcat Server learning and using ( One )

    One .Tomcat Configuration of server port Tomcat All the configurations of are in conf In the folder , Inside server.xml File is the core file of configuration . If you want to modify Tomcat Start port of the server , Can be in server.xml ...

  9. 【JAVAWEB Learning notes 】 The real battle of online mall 1: Environment construction and user module completion

    Today's mission Complete the function of user module 1.1      The real battle of online mall : 1.1.1    Demonstrate the functions of online mall : 1.1.2    The purpose of making : Flexible use of knowledge learned to complete the actual battle of the mall . 1.1.3    Database analysis and design ...

Random recommendation

  1. MVC4 Based on bootstrap and HTML5 Upload your pictures Jquery Custom control

    scene :mvc4 Upload pictures in , Batch upload , Browse before uploading , operation . Picture progress bar . solve : Customize jquery Control No solution : Not when the picture is uploaded , There will be problems with browsing styles ; Solution ; 1. style – bootstrap Of css and ...

  2. Vue - Event binding

    1. inline : A: Bind the event handler to a method , All of the following events are marked by click Events as cases Be careful : In inline mode, only one method can be bound to an event handler , If you want to bind multiple methods , Still using js Medium addEventList ...

  3. jQuery File upload plugin jQuery Upload File There's an upload progress bar

    jQuery File upload plugin jQuery Upload File There's an upload progress bar jQuery File upload plugin jQuery Upload File, Plug ins are easy to use , Support single file and multi file upload , Support file drag upload , There is progress ...

  4. TinyXML: A good one C++ XML Parser

    //-------------------------------------------------------------------------------------------------- ...

  5. character string : All kinds of wonderful built-in methods - Basic learning Python014

    character string : All kinds of wonderful built-in methods Let programming change the world Change the world by program character string : All kinds of wonderful built-in methods Maybe now I'll come back to strings , Some friends may think it's unnecessary , Some of my friends don't think ...

  6. Intercept one of the strings slice

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. PAT ( ladder on high buildings )L2-004. Is this a binary search tree ?

    L2-004. Is this a binary search tree ? The time limit 400 ms Memory limit 65536 kB Code length limit 8000 B The procedure of judging questions Standard author Chen Yue A binary search tree can be recursively defined as ...

  8. SAX,DOM,JAXP,JDOM,DOM4J Compare

    dom,sax,jdom,dom4j The technical characteristics of : 1: DOMDOM It's expressed in a platform - and language independent way XML The official document W3C standard .DOM A collection of nodes or pieces of information organized in a hierarchy . This hierarchy allows ...

  9. 【 turn 】 Efficient use of Fundebug track Node.js Log found problems

    No matter which language you use for project development , We all consciously use the log to make relevant records . such as ,HTTP request , Error message . Some key node buried point records and so on . stay Java Some of them are famous Log4J, So in Node.js It's in log4js. Japan ...

  10. springdata jpa For inquiry like You need to enter the type bytecode of the attribute when you need to