JNDI и настройка server.xml для работы с Tomcat и mysql-java-connextor-8

 
 
 
Сообщения:46
При использовании msql-java-connector8 изменились и настройки подключения.

Но почему то выдается ошибка

/src/jdbc/db/ConnectionManager.java

package jdbc.db;
 
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
 
public class ConnectionManager {
 
    private static final ConnectionManager manager = new ConnectionManager();
 
    public static ConnectionManager getManager() {
        return manager;
    }
 
    private DataSource dataSource;
 
    private ConnectionManager() {
        try {
            Context initContext = new InitialContext();
            Context rootContext = (Context) initContext.lookup("java:comp/env");
            dataSource = (DataSource) rootContext.lookup("jdbc/personnel_department_db_link");
        } catch (NamingException e) {
            throw new RuntimeException("Some errors occurred during DataSource lookup!", e);
        }
    }
 
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("Can not receive connection!", e);
        }
    }
    
    public void closeDbResources(Connection connection, Statement statement) {
        closeDbResources(connection, statement, null);
    }
 
    public void closeDbResources(Connection connection, Statement statement, ResultSet resultSet) {
        closeResultSet(resultSet);
        closeStatement(statement);
        closeConnection(connection);
    }
 
    private void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                System.out.println("Error: Connection has not been closed!");
            }
        }
    }
 
    private void closeStatement(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                System.out.println("Error: Statement has not been closed!");
            }
        }
    }
 
    private void closeResultSet(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                System.out.println("Error: ResultSet has not been closed!");
            }
        }
    }
}


база данных

DROP SCHEMA IF EXISTS `personnel_department_db`;
 
CREATE SCHEMA IF NOT EXISTS `personnel_department_db`
CHARACTER SET `utf8`;
 
USE `personnel_department_db`;
 
CREATE TABLE `employees` (
  `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `email` VARCHAR(255) NOT NULL,
  `password` VARCHAR(255) NOT NULL,
  `salary` NUMERIC(10, 2) NOT NULL
);
 
INSERT INTO `personnel_department_db`.`employees` (`id`, `email`, `password`, `salary`) VALUES (1, '[email protected]', 'secret', 12.50);
INSERT INTO `personnel_department_db`.`employees` (`id`, `email`, `password`, `salary`) VALUES (2, '[email protected]', 'qwert', 55.99);
INSERT INTO `personnel_department_db`.`employees` (`id`, `email`, `password`, `salary`) VALUES (3, '[email protected]', 'SuperstR0NGpassWord', 1000.20);


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_3_1.xsd"
         version="3.1">

    <display-name>01.simple-jdbc-example</display-name>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>JspExample</servlet-name>
        <jsp-file>/WEB-INF/pages/jdbcExamplePage.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>JspExample</servlet-name>
        <url-pattern>/jdbc-example.html</url-pattern>
    </servlet-mapping>

    <resource-ref>
        <description>This section describes link to the DataSource JNDI resource</description>
        <res-ref-name>jdbc/personnel_department_db_link</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>


index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="0; url=jdbc-example.html">
 
    <title>JDBC Examples</title>
</head>
<body>
 
</body>
</html>



web-inf\pages\jdbcExamplePage.jsp

<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.util.Random"%>
<%@page import="jdbc.db.ConnectionManager"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 
<!DOCTYPE html>
 
<html>
<head>
    <meta charset="UTF-8">
    <title>JDBC Examples</title>
 
    <link rel="stylesheet" href="css/styles.css">
</head>
 
<%!
    private void saveUser(String email, String password, Double salary) {
        Connection c = null;
        PreparedStatement statement = null;
 
        try {
            c = ConnectionManager.getManager().getConnection();
            
            statement = c.prepareStatement("INSERT INTO personnel_department_db.employees (email, password, salary) VALUES (?, ?, ?)");
 
            statement.setString(1, email);
            statement.setString(2, password);
            statement.setDouble(3, salary);
 
            statement.executeUpdate();
        } catch(SQLException e) {
            throw new RuntimeException("Some errors occurred during DB access!", e);
        } finally {
            ConnectionManager.getManager().closeDbResources(c, statement);
        }
    }
 
    private void updateUser(Integer userId) {
        Connection c = null;
        PreparedStatement statement = null;
 
        String email = "_NEEEEEW_ Email!!!";
        String password = "_NEEEEEW_ Password!!!";
 
        try {
            c = ConnectionManager.getManager().getConnection();
            statement = c.prepareStatement("UPDATE personnel_department_db.employees SET email = ?, password = ? WHERE id = ?");
 
            statement.setString(1, email);
            statement.setString(2, password);
            statement.setInt(3, userId);
 
            statement.executeUpdate();
    
        } catch(SQLException e) {
            throw new RuntimeException("Some errors occurred during DB access!", e);
        } finally {
            ConnectionManager.getManager().closeDbResources(c, statement);
        }
    }
 
    private void deleteUser(Integer userId) {
        Connection c = null;
        PreparedStatement statement = null;
 
        try {
            c = ConnectionManager.getManager().getConnection();
            statement = c.prepareStatement("DELETE FROM personnel_department_db.employees WHERE id = ?");
 
            statement.setInt(1, userId);
 
            statement.executeUpdate();
    
        } catch(SQLException e) {
            throw new RuntimeException("Some errors occurred during DB access!", e);
        } finally {
            ConnectionManager.getManager().closeDbResources(c, statement);
        }
    }
 
    private int controlCrisis() {
        Connection c = null;
        PreparedStatement statement = null;
 
        try {
            c = ConnectionManager.getManager().getConnection();
            statement = c.prepareStatement("UPDATE personnel_department_db.employees SET salary = 1");
            int updatedRows = statement.executeUpdate();
 
            return updatedRows;
        } catch(SQLException e) {
            throw new RuntimeException("Some errors occurred during DB access!", e);
        } finally {
            ConnectionManager.getManager().closeDbResources(c, statement);
        }
    }
 
    private long importUsers() {
        Connection c = null;
        PreparedStatement statement = null;
 
        try {
            c = ConnectionManager.getManager().getConnection();
            statement = c.prepareStatement("INSERT INTO personnel_department_db.employees (email, password, salary) VALUES (?, ?, ?)");
 
            long start = System.nanoTime();
            Random random = new Random();
 
            for(int i = 0; i < 10; i++) {
                String email = "user_" + i + "@gmail.com";
                String password = "password_" + i;
                Integer salary = random.nextInt(1000);
 
                statement.setString(1, email);
                statement.setString(2, password);
                statement.setDouble(3, salary);
 
                statement.executeUpdate();
            }
 
            long finish = System.nanoTime();
            long delta = (finish - start);
 
            return delta;
        } catch(SQLException e) {
            throw new RuntimeException("Some errors occurred during DB access!", e);
        } finally {
            ConnectionManager.getManager().closeDbResources(c, statement);
        }
    }
 
    private int getDepartment(int employeeCount) {
        Connection c = null;
        PreparedStatement statement = null;
 
        int total = 0;
 
        try {
            c = ConnectionManager.getManager().getConnection();
            c.setAutoCommit(false);
 
            statement = c.prepareStatement("INSERT INTO personnel_department_db.employees (email, password, salary) VALUES (?, ?, ?)");
 
            
            Random random = new Random();
 
            for(int i = 0; i < employeeCount; i++) {
                String email = "user_" + i + "@gmail.com";
                String password = "password_" + i;
                Integer salary = random.nextInt(1000);
 
                if (salary > 500) {
                    throw new RuntimeException("Этот сотрудник слишком дорогой!");
                }
 
                statement.setString(1, email);
                statement.setString(2, password);
                statement.setDouble(3, salary);
 
                statement.executeUpdate();
 
                total = total + 1;
            }
 
            c.commit();
 
            return employeeCount;
        } catch(SQLException e) {
            total = 0;
 
            try {
                c.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException("Can not rollback transaction!", ex);
            }
 
            throw new RuntimeException("Some errors occurred during DB access!", e);
        } finally {
            ConnectionManager.getManager().closeDbResources(c, statement);
        }
    }
%>
 
<body>
 
    <%
        Integer updatedRows = null;
        Integer employeeCount = null;
 
        String btnSave = request.getParameter("btn_save_employee");
        String editId = request.getParameter("edit_id");
        String deleteId = request.getParameter("delete_id");
        String btnCrisis = request.getParameter("btn_crisis_control");
        String btnImport = request.getParameter("btn_import_users");
        String btnGetDepartment = request.getParameter("btn_get_department");
 
        Long delta = null;
 
        if (btnSave != null) {
            String email = request.getParameter("txt_email");
            String password = request.getParameter("txt_password");
            String salaryStr = request.getParameter("txt_salary");
            Double salary = new Double(salaryStr);
 
            saveUser(email, password, salary);
        } else if (btnCrisis != null) {
            updatedRows = controlCrisis();
        } else if (editId != null) {
            Integer intEditId = new Integer(editId);
            updateUser(intEditId);
        } else if (deleteId != null) {
            Integer intDeleteId = new Integer(deleteId);
            deleteUser(intDeleteId);            
        } else if (btnImport != null) {
            delta = importUsers();
        } else if (btnGetDepartment != null) {
            String countStr = request.getParameter("txt_employee_count");
            Integer count = new Integer(countStr);
 
            employeeCount = getDepartment(count);
        }
    %>
 
    <h1>Список сотрудников</h1>
 
    <%
        if (delta != null) {
    %>
        <h3>Импорт завершен за <%=delta %> мс.</h3>
    <%      
        }   
    %>
 
    <table >
        <tr>
            <th>ID</th>
            <th>Email</th>
            <th>Пароль</th>
            <th>Зараюотная плата</th>
            <th>Операции</th>
        </tr>
 
        <%
            Connection c = null;
            PreparedStatement statement = null;
            ResultSet set = null;
 
            try {
                c = ConnectionManager.getManager().getConnection();
                statement = c.prepareStatement("SELECT id, email, password, salary FROM personnel_department_db.employees");
                set = statement.executeQuery();
 
                while(set.next()) {
                    Integer id = set.getInt(1);             // Вот так получать данные - очень плохо!
                    String email = set.getString("email");  // А вот так - очень хорошо!
                    String password = set.getString("password");
                    Double salary = set.getDouble("salary");
        %>
                    <tr>
                        <td>
                            <%=id %>
                        </td>
                        <td>
                            <%=email %>
                        </td>
                        <td>
                            <%=password %>
                        </td>
                        <td>
                            <%=salary %>
                        </td>
                        <td>
                            <a href="jdbc-example.html?edit_id=<%=id%>">Обновить</a>
                            <a href="jdbc-example.html?delete_id=<%=id%>">Удалить</a>
                        </td>
                    </tr>
        <%  
                }
            } catch(SQLException e) {
                throw new RuntimeException("Some errors occurred during DB access!", e);
            } finally {
                ConnectionManager.getManager().closeDbResources(c, statement, set);
            }
        %>
 
    </table>
 
    <br />
    <hr />
    <br />
 
    <div class="formFrame">
        <h2>Добавить сотрудника</h2>
 
        <form action="jdbc-example.html">
            Email:
            <br />
            <input type="text" id="txt_email" name="txt_email" /> 
 
            <br />
            <br />
 
            Пароль:
            <br />
            <input type="text" id="txt_password" name="txt_password" />
 
            <br />
            <br />
 
            Заработная плата:
            <br />
            <input type="text" id="txt_salary" name="txt_salary" />
 
            <br />
            <br />
            <input type="submit" name="btn_save_employee" value="Сохранить" />
            &nbsp;
            <input type="submit" name="btn_import_users" value="Импортировать" />
        </form>
    </div>
 
    <div class="formFrame">
        <form action="jdbc-example.html">
            <h2>Управление финансовым кризисом</h2>
 
            <input type="submit" name="btn_crisis_control" value="Побороться с кризисом" />
            
            <%
                if (updatedRows != null) {
            %>
                <h3>Мы поборолись с кризисом <span style="color: red;"> <%=updatedRows %> раз(а)! </span></h3>
            <%
                }
            %>
            
        </form>
    </div>
 
    <div class="formFrame">
        <form action="jdbc-example.html">
            <h2>Нанять отдел сотрудников</h2>
 
            Сколько сотрудников хотите?
            <br />
            <input type="text" id="txt_employee_count" name="txt_employee_count" /> 
 
            <br />
            <br />
            <input type="submit" name="btn_get_department" value="Нанять всех" />
 
            <%
                if (employeeCount != null) {
            %>
                <h3>Вы наняли <span style="color: red;"> <%=employeeCount %> сотрудников! </span></h3>
            <%
                }
            %>
 
        </form>
    </div>
</body>
</html>


server.xml

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
 
    <Resource 
    type="javax.sql.DataSource" 
    
    auth="Container" 
    description="User database that can be updated and saved" 
    
    driverClassName="com.mysql.cj.jdbc.Driver" 
    name="jdbc/personnel_department_db_link" 
    username="root" 
    password="root" 
    
    url="jdbc:mysql://localhost:3306/personnel_department_db?verifyServerCertificate=false&amp;useSSL=false&amp;allowPublicKeyRetrieval=true&amp;requireSSL=false&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC" 
    />


ошибка

SEVERE: Servlet.service() for servlet [JspExample] in context with path [/jndi] threw exception [An exception occurred processing [/WEB-INF/pages/jdbcExamplePage.jsp] at line [287]
 
284:            } catch(SQLException e) {
285:                throw new RuntimeException("Some errors occurred during DB access!", e);
286:            } finally {
287:                ConnectionManager.getManager().closeDbResources(c, statement, set);
288:            }
289:        %>
290: 
 
 
Stacktrace:] with root cause
java.lang.NoClassDefFoundError: Could not initialize class jdbc.db.ConnectionManager
    at org.apache.jsp.WEB_002dINF.pages.jdbcExamplePage_jsp._jspService(jdbcExamplePage_jsp.java:442)


Подскажите в чем ошибка?
 
 
Сообщения:46
Исправил некоторые файлы

В Каталоге META-INF/context.xml

<?xml version="1.0" encoding="UTF-8"?>

<Context path="/jndi" docBase="jndi" reloadable="true">

	<ResourceLink name="jdbc/personnel_department_db_link" global="jdbc/personnel_department_db_resource" type="javax.sql.DataSource"/>
</Context>



/WEB-INF/pages/jdbcExamplePage.jsp

<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.util.Random"%>
<%@page import="jdbc.db.ConnectionManager"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>
<head>
	<meta charset="UTF-8">
	<title>JDBC Examples</title>

	<link rel="stylesheet" href="css/styles.css">
</head>

<%!
	private void saveUser(String email, String password, double salary) {
		Connection c = null;
		PreparedStatement statement = null;

		try {
			c = ConnectionManager.getManager().getConnection();
			
			statement = c.prepareStatement("INSERT INTO personnel_department_db.employees (email, password, salary) VALUES (?, ?, ?)");

			statement.setString(1, email);
			statement.setString(2, password);
			statement.setDouble(3, salary);

			statement.executeUpdate();
		} catch(SQLException e) {
			throw new RuntimeException("Some errors occurred during DB access!", e);
		} finally {
			ConnectionManager.getManager().closeDbResources(c, statement);
		}
	}

	private void updateUser(int userId) {
		Connection c = null;
		PreparedStatement statement = null;

		String email = "_NEEEEEW_ Email!!!";
		String password = "_NEEEEEW_ Password!!!";

		try {
			c = ConnectionManager.getManager().getConnection();
			statement = c.prepareStatement("UPDATE personnel_department_db.employees SET email = ?, password = ? WHERE id = ?");

			statement.setString(1, email);
			statement.setString(2, password);
			statement.setInt(3, userId);

			statement.executeUpdate();
	
		} catch(SQLException e) {
			throw new RuntimeException("Some errors occurred during DB access!", e);
		} finally {
			ConnectionManager.getManager().closeDbResources(c, statement);
		}
	}

	private void deleteUser(int userId) {
		Connection c = null;
		PreparedStatement statement = null;

		try {
			c = ConnectionManager.getManager().getConnection();
			statement = c.prepareStatement("DELETE FROM personnel_department_db.employees WHERE id = ?");

			statement.setInt(1, userId);

			statement.executeUpdate();
	
		} catch(SQLException e) {
			throw new RuntimeException("Some errors occurred during DB access!", e);
		} finally {
			ConnectionManager.getManager().closeDbResources(c, statement);
		}
	}

	private int controlCrisis() {
		Connection c = null;
		PreparedStatement statement = null;

		try {
			c = ConnectionManager.getManager().getConnection();
			statement = c.prepareStatement("UPDATE personnel_department_db.employees SET salary = 1");
			int updatedRows = statement.executeUpdate();

			return updatedRows;
		} catch(SQLException e) {
			throw new RuntimeException("Some errors occurred during DB access!", e);
		} finally {
			ConnectionManager.getManager().closeDbResources(c, statement);
		}
	}

	private long importUsers() {
		Connection c = null;
		PreparedStatement statement = null;

		try {
			c = ConnectionManager.getManager().getConnection();
			statement = c.prepareStatement("INSERT INTO personnel_department_db.employees (email, password, salary) VALUES (?, ?, ?)");

			long start = System.nanoTime();
			Random random = new Random();

			for(int i = 0; i < 10; i++) {
				String email = "user_" + i + "@gmail.com";
				String password = "password_" + i;
				Integer salary = random.nextInt(1000);

				statement.setString(1, email);
				statement.setString(2, password);
				statement.setDouble(3, salary);

				statement.executeUpdate();
			}

			long finish = System.nanoTime();
			long delta = (finish - start);

			return delta;
		} catch(SQLException e) {
			throw new RuntimeException("Some errors occurred during DB access!", e);
		} finally {
			ConnectionManager.getManager().closeDbResources(c, statement);
		}
	}

	private int getDepartment(int employeeCount) {
		Connection c = null;
		PreparedStatement statement = null;

		int total = 0;

		try {
			c = ConnectionManager.getManager().getConnection();
			c.setAutoCommit(false);

			statement = c.prepareStatement("INSERT INTO personnel_department_db.employees (email, password, salary) VALUES (?, ?, ?)");

			
			Random random = new Random();

			for(int i = 0; i < employeeCount; i++) {
				String email = "user_" + i + "@gmail.com";
				String password = "password_" + i;
				Integer salary = random.nextInt(1000);

				if (salary > 500) {
					throw new RuntimeException("Этот сотрудник слишком дорогой!");
				}

				statement.setString(1, email);
				statement.setString(2, password);
				statement.setDouble(3, salary);

				statement.executeUpdate();

				total = total + 1;
			}

			c.commit();

			return employeeCount;
		} catch(SQLException e) {
			total = 0;

			try {
				c.rollback();
			} catch (SQLException ex) {
				throw new RuntimeException("Can not rollback transaction!", ex);
			}

			throw new RuntimeException("Some errors occurred during DB access!", e);
		} finally {
			ConnectionManager.getManager().closeDbResources(c, statement);
		}
	}
%>

<body>

	<%
		Integer updatedRows = null;
		Integer employeeCount = null;

		String btnSave = request.getParameter("btn_save_employee");
		String editId = request.getParameter("edit_id");
		String deleteId = request.getParameter("delete_id");
		String btnCrisis = request.getParameter("btn_crisis_control");
		String btnImport = request.getParameter("btn_import_users");
		String btnGetDepartment = request.getParameter("btn_get_department");

		Long delta = null;

		if (btnSave != null) {
			String email = request.getParameter("txt_email");
			String password = request.getParameter("txt_password");
			String salaryStr = request.getParameter("txt_salary");
			Double salary = new Double(salaryStr);

			saveUser(email, password, salary);
		} else if (btnCrisis != null) {
			updatedRows = controlCrisis();
		} else if (editId != null) {
			Integer intEditId = new Integer(editId);
			updateUser(intEditId);
		} else if (deleteId != null) {
			Integer intDeleteId = new Integer(deleteId);
			deleteUser(intDeleteId);			
		} else if (btnImport != null) {
			delta = importUsers();
		} else if (btnGetDepartment != null) {
			String countStr = request.getParameter("txt_employee_count");
			Integer count = new Integer(countStr);

			employeeCount = getDepartment(count);
		}
	%>

	<h1>Список сотрудников</h1>

	<%
		if (delta != null) {
	%>
		<h3>Импорт завершен за <%=delta %> мс.</h3>
	<%		
		}	
	%>

	<table >
		<tr>
			<th>ID</th>
			<th>Email</th>
			<th>Пароль</th>
			<th>Зараюотная плата</th>
			<th>Операции</th>
		</tr>

		<%
			Connection c = null;
			PreparedStatement statement = null;
			ResultSet set = null;

			try {
				c = ConnectionManager.getManager().getConnection();
				statement = c.prepareStatement("SELECT id, email, password, salary FROM personnel_department_db.employees");
				set = statement.executeQuery();

				while(set.next()) {
					Integer id = set.getInt(1);				// Вот так получать данные - очень плохо!
					String email = set.getString("email");	// А вот так - очень хорошо!
					String password = set.getString("password");
					Double salary = set.getDouble("salary");
		%>
					<tr>
						<td>
							<%=id %>
						</td>
						<td>
							<%=email %>
						</td>
						<td>
							<%=password %>
						</td>
						<td>
							<%=salary %>
						</td>
						<td>
							<a href="input?edit_id=<%=id%>">Обновить</a>
							<a href="input?delete_id=<%=id%>">Удалить</a>
						</td>
					</tr>
		<%	
				}
			} catch(SQLException e) {
				throw new RuntimeException("Some errors occurred during DB access!", e);
			} finally {
				ConnectionManager.getManager().closeDbResources(c, statement, set);
			}
		%>

	</table>

	<br />
	<hr />
	<br />

	<div class="formFrame">
		<h2>Добавить сотрудника</h2>

		<form action="input">
			Email:
			<br />
			<input type="text" id="txt_email" name="txt_email" /> 

			<br />
			<br />

			Пароль:
			<br />
			<input type="text" id="txt_password" name="txt_password" />

			<br />
			<br />

			Заработная плата:
			<br />
			<input type="text" id="txt_salary" name="txt_salary" />

			<br />
			<br />
			<input type="submit" name="btn_save_employee" value="Сохранить" />
			&nbsp;
			<input type="submit" name="btn_import_users" value="Импортировать" />
		</form>
	</div>

	<div class="formFrame">
		<form action="input">
			<h2>Управление финансовым кризисом</h2>

			<input type="submit" name="btn_crisis_control" value="Побороться с кризисом" />
			
			<%
				if (updatedRows != null) {
			%>
				<h3>Мы поборолись с кризисом <span style="color: red;"> <%=updatedRows %> раз(а)! </span></h3>
			<%
				}
			%>
			
		</form>
	</div>

	<div class="formFrame">
		<form action="input">
			<h2>Нанять отдел сотрудников</h2>

			Сколько сотрудников хотите?
			<br />
			<input type="text" id="txt_employee_count" name="txt_employee_count" /> 

			<br />
			<br />
			<input type="submit" name="btn_get_department" value="Нанять всех" />

			<%
				if (employeeCount != null) {
			%>
				<h3>Вы наняли <span style="color: red;"> <%=employeeCount %> сотрудников! </span></h3>
			<%
				}
			%>

		</form>
	</div>
</body>
</html>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">

	<display-name>jndi</display-name>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>


	<resource-ref>
		<description>This section describes link to the DataSource JNDI resource</description>
		<res-ref-name>jdbc/personnel_department_db_link</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>

</web-app>


public class InputFormServlet

package jdbc.db;

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;

@WebServlet({"/input"})
public class InputFormServlet extends HttpServlet {


        public InputFormServlet() {
        }

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            ServletUtils.getDispatcher(request, response, "/WEB-INF/pages/jdbcExamplePage.jsp");
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            ServletUtils.getDispatcher(request, response, "/WEB-INF/pages/jdbcExamplePage.jsp");
        }

}


InputFormServlet
package jdbc.db;

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;

@WebServlet({"/input"})
public class InputFormServlet extends HttpServlet {


        public InputFormServlet() {
        }

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            ServletUtils.getDispatcher(request, response, "/WEB-INF/pages/jdbcExamplePage.jsp");
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            ServletUtils.getDispatcher(request, response, "/WEB-INF/pages/jdbcExamplePage.jsp");
        }

}



ServletUtils

package jdbc.db;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Создан разработчиком IT
 * Дата 24.06.2018
 */
public class ServletUtils extends HttpServlet {


    ServletContext context;

    public ServletUtils() {
        this.context =  getServletContext();;
    }

    /*перенаправление запроса внутри приложения*/
    public static void getDispatcher(HttpServletRequest request, HttpServletResponse response,
                                     String url) throws ServletException, IOException {
        ServletContext context = request.getServletContext();
        String contextPath = context.getContextPath();


        String styleUrl = contextPath + "/styles/";
          RequestDispatcher dispatcher = request.getRequestDispatcher(url);
          dispatcher.forward(request, response);
    }


     /*паттерн post-send-redirect
    * при этом используем передачу
    * Метод encodeURL() есть у объекта response.
    * Таким образом мы можем клиенту отправить
    * id-сессии с помощью дополнительного параметра response,
    * то есть объект, который содержит в себе ответ клиенту,
    * может также передавать ему URL с присоединенным id-сессии.*/

    public static void sendRedirect(HttpServletResponse response,
                                    HttpServletRequest request,String url){
        ServletContext context = request.getServletContext();
        String contextPath = context.getContextPath();


        String styleUrl = contextPath + "/styles/";
        url = response.encodeURL(url);
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


index.jsp

<%--
  Created by IntelliJ IDEA.
  User: v.parfenchik
  Date: 11.07.2018
  Time: 9:47
  To change this template use Settings | Editor |  File and Code Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"  %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>

  <%

   String url = response.encodeURL("input");
   response.sendRedirect(url);

  %>

  </body>
</html>
Изменен:11 июл 2018 11:54
 
 
Сообщения:46
server.xml

    <Resource auth="Container"
              driverClassName="com.mysql.cj.jdbc.Driver"
              type="javax.sql.DataSource"


              name="jdbc/personnel_department_db_resource"
              url="jdbc:mysql://localhost:3306/personnel_department_db?verifyServerCertificate=false&amp;useSSL=false&amp;allowPublicKeyRetrieval=true&amp;requireSSL=false&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC"
              username="root"
              password="root"

              maxTotal="100" maxIdle="30" maxWaitMillis="10000"

             />
 
 
Сообщения:46
Веб-приложение обращается к web.xml, web.xml читает context.xml, а он обращается к JNDI, JNDI вызывает JNDI provider (в данном случае это Tomcat). provider читает файл server.xml, обращается к базе и получает нужное число коннекторов , затем возвращает в приложение объект DataSource, который является хранилищем для уже полученных коннекторов (пул коннекторов)

Только непонятно почему нужно использовать именно context.xml, данный файл нужно настраивать когда на сервере приложений ожидается развертывание сразу нескольких приложений ?
А без него не удалось запустить.
Изменен:11 июл 2018 12:06
 
Модераторы:Нет
Сейчас эту тему просматривают:Нет