Answer the question
In order to leave comments, you need to log in
Why does insert fire when reloading a JSP page?
Good afternoon.
When the JSP page is reloaded, an unscheduled insert is executed.
Insert is assumed only after pressing "Insert in MySQL" button
How to fix this problem?
jsp code
<%@ 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>
Answer the question
In order to leave comments, you need to log in
I have never been a java programmer, but the error is obvious:
If you want to trigger a server event from the client, use ajax.
Or perhaps the JSP has something illogical ASP.NET WebForms, its own markup that allows you to do something like
But it should be knowledgeable people to suggest.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question