![](/img/trans.png)
[英]trying to set focus on the form element by its id using after alert message but the jsp page submitted
[英]After inserting value in a form using jsp, return a message with the values inserted on top of the form page
我有一個表單,在按下“添加”按鈕后,轉到 DataInsert.jsp 運行插入后,只需在 end () 中輸入一條消息“已插入”並重定向到主頁。
我有這樣的東西(index.jsp 中的表格):
<form onsubmit="return checkempty(form1)" action="Data_insert.jsp" method="post" name="form1">
<table class="table" width="25%">
<tr>
<td><label for="name">Name: </label></td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td><label for="city">City: </label></td>
<td><input type="text" name="city" id="city"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="button" id="button" value="Add"></td>
</tr>
</table>
<p><br>
</p>
</form>
插入在:Data_insert.jsp
<body>
<%
String name=request.getParameter("name");
String city=request.getParameter("city");
// Connect to the database using Tomcat Resources
Context ctx = null;
Context initCtx = null;
Connection con = null;
DataSource ds = null;
ctx = new InitialContext();
initCtx = (Context) ctx.lookup("java:comp/env");
ds = (DataSource) initCtx.lookup("jdbc/table_pool");
con = ds.getConnection();
PreparedStatement stmt;
String instruccionSql="INSERT INTO table (name,city) VALUES ('" + name + "','" + city + "')";
stmt = con.prepareStatement(instruccionSql);
stmt.executeUpdate();
stmt.close();
con.close();
out.println("Insertado"+"<br>");
%>
</body>
問題是“已插入”消息清除了屏幕。 如果我們放一個 Javascript 警報,window.alert("Inserted;"),它不會作為警報框出現,
我們也嘗試過:
<script>
window.location.href = '/index.jsp';
</script>
它重定向到頁面,但我們沒有將 Inserted 消息視為彈出窗口。
如何在主頁頂部以彈出窗口的形式獲取“已插入”消息。 謝謝
您可以使用setAttribute
在其中設置一些消息,並根據該警報將顯示在您的index.jsp
頁面上。如下所示:
<%
String name=request.getParameter("name");
String city=request.getParameter("city");
int row=0;
// Connect to the database using Tomcat Resources
Context ctx = null;
Context initCtx = null;
Connection con = null;
DataSource ds = null;
ctx = new InitialContext();
initCtx = (Context) ctx.lookup("java:comp/env");
ds = (DataSource) initCtx.lookup("jdbc/table_pool");
con = ds.getConnection();
PreparedStatement stmt;
String instruccionSql="INSERT INTO table (name,city) VALUES (?,?)";
stmt = con.prepareStatement(instruccionSql);
stmt.setString(1,name);
stmt.setString(2,city);
row=stmt.executeUpdate();
stmt.close();
con.close();
//if inserted
if (row > 0) {
//setting message
session.setAttribute("add", "Added Succesfully");
//redirecting
request.getRequestDispatcher("index.jsp").forward(request,response);
}
%>
然后在index.jsp
中執行如下操作:
<% if(session.getAttribute("add") != null){ %>
<script>
alert("${add}");
</script>
<% } %>
或者使用EL
在您的<form>
標簽上方添加以下行:
<p style="color: red;text-align:center">${add}</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.