mardi 1 juin 2021

Web application doesnt convert jsp variable

I'm trying to do simple web application. But i think, i configured it wrong. Here is my project structure:

Project structure part 1

Project structure part 2

Here is my Service class with connection to 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();

    }
}

Here is my Servlet class:

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);
        }
    }

}

Here is my JSP class:

<%--@ 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>

I expected that it will return an html page with counter value (from DB), and with click button it will concurrent-safety add 1 to counter value in DB and returns new value.

But here server didnt replase ${count}:

enter image description here

Here is my configuration: Configuration tomcat I created web application from "add Framework support to project": enter image description here

My web.xml file:

<?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>

What did i wriong? Did i configured my application wrong, or wrong code? Run Output LOG INFO return some exceptions in catalina and tomcat at the start. Shall i post them?




Aucun commentaire:

Enregistrer un commentaire