web应用程序不转换jsp变量

txu3uszq  于 2021-10-10  发布在  Java
关注(0)|答案(0)|浏览(250)

我正在尝试做一个简单的web应用程序。但我想,我配置错了。以下是我的项目结构:


这是我的连接到postgresql的服务类

package NedraTask;

import java.sql.*;

public class CounterService {
    private final String url = "jdbc:postgresql://localhost/postgres";
    private final String username = "postgres";
    private final String password = "examplePassword";
    private Connection connection;

    CounterService() {
        try {
            connection = DriverManager.getConnection(url, username, password);
            createIfNotExistsAndInsert(connection);
        }catch (Exception ex) {}
    }
        /**
         * creates table with name COUNTERS
         * with 1 INTEGER column
         * with name COUNTER
         */
    private void createIfNotExistsAndInsert(Connection conn) throws SQLException {
        conn.setAutoCommit(false);
        DatabaseMetaData dbm = conn.getMetaData();

        ResultSet rs = dbm.getTables(null, null, "COUNTERS", null);
        if (!rs.next()) {
            conn.createStatement().executeUpdate("create table if not exists COUNTERS(COUNTER INTEGER)");
            conn.createStatement().executeUpdate("INSERT INTO COUNTERS VALUES 0");
        }
        conn.commit();
        conn.setAutoCommit(true);
    }
    public int getCounter() throws SQLException{
        ResultSet resultSet = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
                .executeQuery("SELECT * FROM COUNTERS");
        int currentCounter = 0;
        while(resultSet.next())
            currentCounter = resultSet.getInt(1);

        return currentCounter;
    }
    public void incrCounter() throws SQLException {
        PreparedStatement statement = connection.prepareStatement(
                "UPDATE COUNTERS SET COUNTER = COUNTER + 1",
                ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_UPDATABLE,
                ResultSet.CLOSE_CURSORS_AT_COMMIT);
        statement.executeUpdate();

    }
}

下面是我的servlet类:

package NedraTask;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

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

public class CounterServlet extends javax.servlet.http.HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            CounterService cs = new CounterService();

            request.setAttribute("count", Integer.toString(cs.getCounter()));

            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
        }catch(Exception ex){
            request.setAttribute("count", "Some error at doPOST method");
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            CounterService cs = new CounterService();
            request.setAttribute("count", Integer.toString(cs.getCounter()));
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
        }
        catch(Exception ex){
            request.setAttribute("count", "Some error at doGET method");
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }

}

这是我的jsp类:

<%--@ page contentType="text/html;charset=UTF-8" language="java" --%>
<!DOCTYPE html>
<html>
  <head>
    <title>Title</title>
    <style>
      .button {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
  <p>Count: ${count}</p>
  <button type="button" class="button" id="myBtn" onclick="myFunction()">Add</button>

  <script>
    function myFunction() {
      var x = document.getElementById("myBtn");
      var xhr = new XMLHttpRequest();

      xhr.open("POST", '/task_war_exploded');
      xhr.send();
    }
  </script>
  </body>
</html>

我希望它会返回一个 html 带有计数器值(来自db)的页面,单击按钮,它将向db中的计数器值添加1,并返回新值。
但这里服务器没有重放 ${count} :

以下是我的配置:

我从“向项目添加框架支持”创建了web应用程序:

我的 web.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>CounterServlet</servlet-name>
        <servlet-class>NedraTask.CounterServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CounterServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

我干了什么?我是否配置了错误的应用程序或错误的代码?运行输出日志信息在开始时返回catalina和tomcat中的一些异常。我要寄吗?
编辑:这里是输出界面:

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题