Simple example of fool servlet listener

Assuming that the java and tomcat environments have been configured

Create AppListener.java file

import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppListener implements ServletContextListener
{
    @Override
    public void contextDestroyed(ServletContextEvent sce)
    {
    }
    @Override
    public void contextInitialized(ServletContextEvent sce)
    {
        ServletContext servletContext = sce.getServletContext()
                                        ;
        Map<String, String> countries =
            new HashMap<String, String>();
        countries.put("ca", "Canada");
        countries.put("us", "United States");
        servletContext.setAttribute("countries", countries);
    }
}
View Code

Compile and place the .class file in apache-tomcat-9.0.6 (Tomcat installation directory)\webapps\ROOT\WEB-INF\classes, and add it in WEB-INF\web-xml

  <listener>
        <listener-class>AppListener</listener-class>
  </listener>

The parent tag is web-app

Create the countries.jsp file

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Country List</title>
</head>
<body>
We operate in these countries:
<ul>
<c:forEach items="${countries}" var="country">
<li>${country.value}</li>
</c:forEach>
</ul>
</body>
</html>
View Code

Save it in \ROOT\jsp (jsp folder is added by itself)

Add jstl-1.2.jar and javax.servlet-api-4.0.1.jar to \ROOT\WEB-INF\lib

start tomcat

Browser input http://localhost:8080/jsp/countries.jsp

can be seen

This method is only for a successful addiction, and the specific principles and tutorials are Baidu.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324969785&siteId=291194637