JavaWeb listener, file upload, mail upload, MD5 encryption

Keywords: Java listener

Listener

Listener is also one of the three components of web project.

Function: the listener is used to listen to the creation and destruction of domain objects (except page domain) and the property changes of domain objects.

Classification:
Class I: creation and destruction of listening domain objects
Domain object typemonitorCorresponding methoddescribe
ServletContextServletContextListenercontextInitializedapplication initialization
contextDestroyedapplication destroy
HttpSessionHttpSessionListenersessionCreatedsession creation
sessionDestroyedsession destruction
HttpServletRequestServletRequestListenerrequestInitializedrequest creation
requestDestroyedrequest destroy
Type 2: listen for attribute changes of domain objects
Domain object typemonitorCorresponding methoddescribe
ServletContextServletContextAttributeListenerattributeAddedAdd attribute
attributeRemovedDelete attribute
attributeReplacedModify attribute value
HttpSessionHttpSessionAttributeListenerattributeAddedAdd attribute
attributeRemovedDelete attribute
attributeReplacedModify attribute value
HttpServletRequestServletRequestAttributeListenerattributeAddedAdd attribute
attributeRemovedDelete attribute
attributeReplacedModify attribute value
The third type: listen for the state changes of JavaBean s in HttpSession

The third type of listener is very special. This type of listener does not need to be configured. The listener acts on the JavaBean, which can sense the state in the session by itself.

Domain object typemonitorCorresponding methoddescribe
HttpSessionHttpSessionBindingListenervalueBoundbinding
valueUnboundUnbind
HttpSessionHttpSessionActivationListenersessionWillPassivateSerialization (passivation)
sessionDidActivateDeserialization (activation)
Test use

Creation of listening domain object

package com.woniuxy.listenner;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * To create a listener
 * 1,Implement the corresponding listener interface and copy its corresponding method
 * 2,Configure listener
 */
@WebListener
public class MyListener implements ServletRequestListener, HttpSessionListener, ServletContextListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        System.out.println("requestDestroyed...");
    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        System.out.println("requestInitialized...");
    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("sessionCreated...");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("sessionDestroyed...");
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("contextInitialized...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("contextDestroyed...");
    }
}

Listening attribute change

monitor

package com.woniuxy.listenner;

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class YourListener implements ServletRequestAttributeListener {
    /**
     * The listening request object calls setAttribute() for the first time
     * @param servletRequestAttributeEvent
     */
    @Override
    public void attributeAdded(ServletRequestAttributeEvent servletRequestAttributeEvent) {
        System.out.println("attributeAdded...");
    }

    /**
     * The listener request object calls removeAttribute()
     * @param servletRequestAttributeEvent
     */
    @Override
    public void attributeRemoved(ServletRequestAttributeEvent servletRequestAttributeEvent) {
        System.out.println("attributeRemoved...");
    }

    /**
     * Listen for the second and more calls to setAttribute() by the request object
     * Note: setAttribute() is applied to the same key multiple times
     * @param servletRequestAttributeEvent
     */
    @Override
    public void attributeReplaced(ServletRequestAttributeEvent servletRequestAttributeEvent) {
        System.out.println("attributeReplaced...");
    }
}

servlet

package com.woniuxy.servlet;

import com.woniuxy.commons.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/user")
public class UserServlet extends BaseServlet {


    public String login(HttpServletRequest req, HttpServletResponse resp){


        System.out.println("Processing login requests");

        req.setAttribute("a","1");
        System.out.println("===========================");
        req.setAttribute("b","2");
        System.out.println("===========================");
        req.removeAttribute("a");
        return "/index.jsp";

    }
}

Listener application
Count the number of people online
Count the number of online logins

Case code:

monitor

package com.woniuxy.listenner;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Use the listener to count the number of people online
 * The purpose of implementing the ServletContextListener interface is to create a variable to save the number of online users when creating the servetcontext
 */
@WebListener
public class OnlineListener implements HttpSessionListener, ServletContextListener, HttpSessionAttributeListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

        ServletContext context = httpSessionEvent.getSession().getServletContext();
        Integer onlineCount = (Integer) context.getAttribute("onlineCount");

        context.setAttribute("onlineCount",++onlineCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext context = httpSessionEvent.getSession().getServletContext();
        Integer onlineCount = (Integer) context.getAttribute("onlineCount");

        context.setAttribute("onlineCount",--onlineCount);
    }

    /**
     * ServletContext During initialization, save a variable to store the number of online people
     * @param servletContextEvent
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext context = servletContextEvent.getServletContext();
        //When the servletContext object completes initialization, a data is saved to the object to record the number of online people
        context.setAttribute("onlineCount",0);
        //When the servletContext object completes initialization, a data is saved to the object to record the number of online logins
        context.setAttribute("onlineLoginCount",0);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }



    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        ServletContext context = httpSessionBindingEvent.getSession().getServletContext();
        Integer onlineLoginCount = (Integer) context.getAttribute("onlineLoginCount");
        String name = httpSessionBindingEvent.getName();
        if ("loginUser".equals(name)) {
            context.setAttribute("onlineLoginCount",++onlineLoginCount);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        ServletContext context = httpSessionBindingEvent.getSession().getServletContext();
        Integer onlineLoginCount = (Integer) context.getAttribute("onlineLoginCount");
        String name = httpSessionBindingEvent.getName();
        if ("loginUser".equals(name)) {
            context.setAttribute("onlineLoginCount",--onlineLoginCount);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}

servlet

package com.woniuxy.servlet;

import com.woniuxy.commons.BaseServlet;
import com.woniuxy.model.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/user")
public class UserServlet extends BaseServlet {


    public String login(HttpServletRequest req, HttpServletResponse resp){

        boolean flag=true;//true indicates successful login and false indicates failed login.

        if (flag) {
            req.getSession().setAttribute("loginUser",new User());
        }

        return "/index.jsp";

    }

    public void logout1(HttpServletRequest req, HttpServletResponse resp){
        req.getSession().invalidate();
//        return "/index.jsp";
    }

    public String logout2(HttpServletRequest req, HttpServletResponse resp){
        req.getSession().removeAttribute("loginUser");
        return "/index.jsp";
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <a href="/user?method=logout1">Log off online status</a>
    <a href="/user?method=logout2">Logout login status</a>
    The number of people currently online is: ${onlineCount}<br>
    The current number of online logins is: ${onlineLoginCount}
  </body>
</html>

File upload

File field: < input type = "file" / >

Through the file field, you can collect the content of a file in the system and store it in the form.

front end

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <!--
    File upload cannot be used BaseServlet
    Form submission:  post
    enctype:  multipart/form-data
    File fields must also have name attribute
    -->
    <form action="/upload" method="post" enctype="multipart/form-data">
        user name:<input type="text" name="username"/><br>
        password:<input type="password" name="password"><br>
        Upload Avatar:<input type="file" name="upload"><br>
        <input type="submit" value="Register now">
    </form>
</body>
</html>

servlet

package com.woniuxy.servlet;

import com.woniuxy.commons.RandomString;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //isMultipartContent(req) is used to judge whether there is a file upload operation in the request. If yes, it returns true
        boolean multipartContent = ServletFileUpload.isMultipartContent(req);

        try {
            if (multipartContent) {//File upload
                //Create a ServletFileUpload object
                ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
                //Prepare resolution request
                List<FileItem> fileItems = fileUpload.parseRequest(req);
                //Traverse the fileItems collection to determine whether fileItem is the content of the file field
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//Common form fields
                        //fileItem.getFieldName() is used to get the name property value of the form control
                        //fileItem.getString("utf-8") is used to get the value of the form control
                        System.out.println(fileItem.getFieldName()+":"+fileItem.getString("utf-8"));
                    }else{//File field, which should be uploaded.
                        //Where should the uploaded files be stored? The local file system tomcat is a dedicated file server
                        String path = this.getServletContext().getRealPath("/files");
                        File file = new File(path);
                        if (!file.exists()) {
                            file.mkdirs();
                        }

                        //Should the file name saved by the uploaded file be unique?
                        String originFileName = fileItem.getName();
                        String fileType = originFileName.substring(originFileName.lastIndexOf("."));

                        String saveFileName = RandomString.getRandomString(128)+fileType;

                        //Create a file object to save
                        File saveFile = new File(file, saveFileName);

                        //Save the name of the uploaded file to the session for later reference
                        req.getSession().setAttribute("imagePath",saveFile.getName());

                        //Write the contents of the file in fileItem to the file.
                        fileItem.write(saveFile);

                        //Delete the temporary files generated during uploading because the files are too large
                        fileItem.delete();

                    }
                }

            }else{//Not file upload

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        resp.sendRedirect("/show.jsp");
    }
}

javamail

javamail is a standard development package developed by sun company to facilitate developers to send and receive mail in the development process.

Mail protocol:

Mail protocol is a part of TCP/IP protocol cluster.

SMTP: can receive or send

POP3: send

IMAP: connected

In the development process, we only care about the sending of e-mail, not the receiving of e-mail.

Key classes in javamail package:

Message class: it represents a message. Its subclass MimeMessage is recommended.

Session class: used to set the basic environment for sending mail.

Transport class: send(): a static method for sending mail.

Prepare the basic environment for mail sending

1. Register a 163 email and log in.

2. Start the pop3/smtp service in settings and pay attention to saving the authorization code.

3. Write code, email. Import javax.mail.jar first

package com.woniuxy.test;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class Test {
    public static void main(String[] args) throws MessagingException {
        //Create properties: used to set the basic environment for sending mail
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol","SMTP");
        properties.setProperty("mail.host","smtp.163.com");
        properties.setProperty("mail.smtp.auth","true");

        //Create Session
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("hjy15823115656@163.com","KNMKUJFZSZBYNPYF");
            }
        });

        //1. Create message
        Message message = new MimeMessage(session);
        //Set the sender of the message
        message.setFrom(new InternetAddress("hjy15823115656@163.com"));
        //Set the recipient of the message
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("93502690@qq.com"));
        //Set message header
        message.setSubject("20210915-Test mail sending");
        //Set message content
        //Parameter 1: mail content
        //Parameter 2: content type of message
        message.setContent("Test 63 e-mail sending","text/html;charset=utf-8");

        //Send mail
        Transport.send(message);


    }
}
MD5 encryption

md5 encryption is a hash algorithm,

characteristic:

1. If you encrypt the same value multiple times, the returned value will always be the same.

2. md5 encryption is an irreversible process. The original value cannot be deduced from the encrypted result.

Wang Xiaoyun!!

code implementation

package com.woniuxy.test;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Test1 {
    public static void main(String[] args) {
        try {
            String password="111111";
            //Generate encrypted object
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            //Call the digest() method to encrypt the string
            byte[] bytes = md5.digest(password.getBytes("utf-8"));
            //Use Base64 to process the encryption result and generate the corresponding string
            String s = Base64.getEncoder().encodeToString(bytes);
            System.out.println(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

try {
String password="111111";
//Generate encrypted object
MessageDigest md5 = MessageDigest.getInstance("MD5");
//Call the digest() method to encrypt the string
byte[] bytes = md5.digest(password.getBytes("utf-8"));
//Use Base64 to process the encryption result and generate the corresponding string
String s = Base64.getEncoder().encodeToString(bytes);
System.out.println(s);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}





Posted by g00bster on Sat, 18 Sep 2021 13:48:17 -0700