Добрый день.
При перезагрузке JSP страницы выполняется не запланированный insert.
Insert предполагается только после нажатия кнопки "Insert в MySQL"
Как исправить эту проблему?
код JSP
<%@ page language="java" %>
<%@ page import="java.sql.*, java.io.*, java.text.*, java.util.Date, java.Math.*, java.math.RoundingMode" %>
<%@page contentType="text/html; charset=UTF-8"%>
<input id="user_location" type="text" value="?" style="display:none">
<c:set var="NUM" value='<%= request.getParameter("NUM") %>'/>
<c:set var="SOLUTION" value='<%= request.getParameter("SOLUTION") %>'/>
<c:if test="${NUM==null}">
<c:set var="NUM" value="7"/>
<c:set var="SOLUTION" value="Быстрый пример"/>
</c:if>
<%!
private static class Insert_In_DB {
private String Insert_to_MySQL(String NUM, String SOLUTION) throws UnsupportedEncodingException {
String Insert_to_MySQL;
String Insert_Text;
Insert_to_MySQL="";
Insert_Text="";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
Insert_to_MySQL="Драйвер не найден!";
}
try {
Connection conn = DriverManager.getConnection ("jdbc:mysql://хост:порт/", "имя", "пароль" );
Insert_Text = "insert into test.example (num, solution) VALUES (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(Insert_Text);
preparedStmt.setString (1, NUM);
preparedStmt.setString (2, SOLUTION);
preparedStmt.execute();
conn.close();
Insert_to_MySQL="Insert выполнен.";
} catch (Exception e) {
Insert_to_MySQL=Insert_to_MySQL+" "+Insert_Text+" НЕ выполнен. Ошибка:"+e.getMessage();
}
return Insert_to_MySQL;
}
}
%>
<script type="text/javascript">
$(function(){
var local = $('#user_location').val();
$('#insert_to_mysql').on('click', function () {
console.log('Нажали кнопку insert_to_mysql');
var NUM=document.getElementById('num').value;
var SOLUTION=document.getElementById('solution').value;
console.log("<%=new Insert_In_DB().Insert_to_MySQL(pageContext.getAttribute("NUM", PageContext.PAGE_SCOPE).toString(),pageContext.getAttribute("SOLUTION", PageContext.PAGE_SCOPE).toString())%>");
window.location.replace(local+"&NUM="+NUM+"&SOLUTION="+SOLUTION);
})
})
</script>
<input id="num" name="num" type="text" size="10" value="${NUM}">
<input id="solution" name="solution" type="text" size="30" value="${SOLUTION}">
<button id="insert_to_mysql" class="btn btn-primary">Insert в MySQL</button>