Description: Get the IP address of a web page visitor and display the access time
Principle: Use the getRemoteAddr method of the JSP built-in object request to obtain the visitor's address; use SimpleDateFormat to convert the current time to the specified time format, and finally use the expression language for output
Code:
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> <%@ page import="java.util.*"%> <%@ page import="java.text.*"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JSP</title> </head> <body> <% // get IP String ip = request.getRemoteAddr(); // Get Time String data = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()); %> <%-- use expression language for output--%> <h2>Your IP address is: <%=ip%></h2> <h2>Time of this visit: <%=data%></h2> </body> </html>
Improvement: The obtained IP address can be saved to the database, otherwise the previous IP will disappear after each refresh