首页 > 解决方案 > Welcome servlet 在初始化时运行 3 次而不是 1 次

问题描述

所以问题是,每当我运行本地 tomcat 服务器时,它都会运行欢迎 servlet 3 次。doGet 方法中的内容并不重要,它可能只是 System.out.println("something"); 它会打印 3 次:“某事”。当服务器正在运行并且我通过 Web 浏览器调用相同的 servlet 时,它可以正常工作。我相信初始化有问题,但我不知道是什么,到目前为止我找不到任何解决方案。我曾尝试构建一个全新的项目,复制所有类和 .xml 文件,但结果完全相同。编辑:我正在使用 Itnellij UE。Edit2:当我停止本地服务器时,我收到此警告:

> 18-Dec-2018 21:41:23.388 WARNING [main]
> org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads
> The web application [ROOT] appears to have started a thread named
> [Abandoned connection cleanup thread] but has failed to stop it. This
> is very likely to create a memory leak. Stack trace of thread: 
> java.lang.Object.wait(Native Method) 
> java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144) 
> com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:70)
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
> java.lang.Thread.run(Thread.java:748)

这些是我的类和 xmls:

小服务程序:

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.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "Servlet1", urlPatterns = {"/servlet1"})
public class Servlet1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String numberOfSolutions = getServletContext().getInitParameter("number-solutions");
        int numberOfRows = Integer.parseInt(numberOfSolutions);
        List<Solution> allSolutions;
        Solution solution = new Solution();
        Solution solution1 = new Solution("newServlet", 2, 3);
        System.out.println();
        try {
            solution1.saveSolutionToDb();
            allSolutions = solution.getAllSolutions(numberOfRows);
            request.setAttribute("solutionsList", allSolutions);
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

解决方案:

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

public class Solution {
    private int id;
    private Timestamp created;
    private Timestamp updated;
    private String description;
    private int exerciseId;
    private long usersId;

    public Solution() {
    }

    public Solution(String description, int exerciseId, long usersId) {
        this.description = description;
        this.exerciseId = exerciseId;
        this.usersId = usersId;
    }

    public void saveSolutionToDb() throws SQLException {
        String query = "INSERT INTO solution(created,description,exercise_id,users_id) VALUES(NOW(),?,?,?);";
        PreparedStatement preparedStatement = DbUtil.getConnection().prepareStatement(sql);
        preparedStatement.setString(1, this.description);
        preparedStatement.setInt(2, this.exerciseId);
        preparedStatement.setLong(3, this.usersId);
        preparedStatement.executeUpdate();
        DbUtil.getConnection().close();
    }

    public ArrayList<Solution> getAllSolutions(int rows) throws SQLException {
        ArrayList<Solution> listOfLoadedSolutions;
        String query = "SELECT * FROM solution ORDER BY id DESC LIMIT " + rows + ";";
        PreparedStatement preparedStatement = DbUtil.getConnection().prepareStatement(query);
        listOfLoadedSolutions = getSolutions(preparedStatement);
        DbUtil.getConnection().close();
        return listOfLoadedSolutions;
    }

    private ArrayList<Solution> getSolutions(PreparedStatement preparedStatement) throws SQLException {
        ArrayList<Solution> allLoadedSolutions = new ArrayList<>();
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            Solution loadedSolution = new Solution();
            loadedSolution.id = resultSet.getInt("id");
            loadedSolution.created = resultSet.getTimestamp("created");
            loadedSolution.updated = resultSet.getTimestamp("updated");
            loadedSolution.description = resultSet.getString("description");
            loadedSolution.exerciseId = resultSet.getInt("exercise_id");
            loadedSolution.usersId = resultSet.getLong("users_id");
            allLoadedSolutions.add(loadedSolution);
        }
        return allLoadedSolutions;
    }
}

联系:

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DbUtil {
    private static DataSource ds;

    public static Connection getConnection() throws SQLException {
        return getInstance().getConnection();
    }

    private static DataSource getInstance() {
        if (ds == null) {
            try {
                Context ctx = new InitialContext();
                ds = (DataSource) ctx.lookup("java:comp/env/jdbc/szkola_programowania");
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
        return ds;
    }
}

上下文.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/szkola_programowania"
              auth="Container"
              type="javax.sql.DataSource"
              username="user"
              password="pass"
              driverClassName="com.mysql.cj.jdbc.Driver"
              connectionProperties="useUnicode=yes;characterEncoding=utf8;"
              url="jdbc:mysql://localhost:3306/szkola_programowania"
              maxTotal="100"
              maxIdle="30"
              maxWaitMillis="10000" />
</Context>

网页.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <welcome-file-list>
        <welcome-file>servlet1</welcome-file>
        <welcome-file>default.html</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>number-solutions</param-name>
        <param-value>5</param-value>
    </context-param>
</web-app>

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation=
                 "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>pl.coderslab</groupId>
    <artifactId>webExample</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <dependency>
            <groupId>org.mindrot</groupId>
            <artifactId>jbcrypt</artifactId>
            <version>0.4</version>
        </dependency>
    </dependencies>
</project>

标签: java

解决方案


推荐阅读