我有一个带有表单的 JSP 页面,该表单在按下提交按钮后调用同一页面。在页面中,我定义了一个变量 x
,初始值为 1,因此它从 DB 中获取对应于 1 的数据。现在当按下提交时,x 的值增加到 2,数据应该从与新值对应的数据库中获取。我的问题是值增加了但没有获取数据。请告诉我为什么?
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="Student" scope="session" class="StudentBean.StudentLoginBean"></jsp:useBean>
<%int x=1; %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>welcome <jsp:getProperty property="login" name="Student" />
</title>
</head>
<body>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
String URL="jdbc:mysql://localhost:3306/OnTest";
Connection con=null;
con=DriverManager.getConnection(URL,"root","root");
PreparedStatement stat=con.prepareStatement("select * from questions where qnNo="+x);
x+=1;
ResultSet rs=stat.executeQuery();
while(rs.next()) {
out.println(x);
out.println(rs.getString(1));%>
<form action="sucess.jsp">
<br><input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(2));%>
<input type ="radio" name ="answer" value="b">
<%
out.println(rs.getString(3));%>
<input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(4));%>
<input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(5));%>
<input type="submit" value="submit" name="submit">
</form>
<%
//System.out.println(rs.getString("name"));
//System.out.println(" "+rs.getString("password"));
//v.addElement(rs.getString("name"));
//v.addElement(rs.getString("name"));
}
if(!con.isClosed()) {
out.println("success");
}
}
catch(Exception e)
{
out.println(e);
}
%>
<h1><h1><h1>i am inside sucess</h1></h1></h1>
</body>
</html>
最佳答案
更改此代码 - <%int x=1; %>
对此 <%!int x=1; %>
.
问题是:你的x
声明在本地范围内,每次调用 .jsp (jsp_servlet) 时都会重新初始化。
通过使用 <%! ... %>
你的x
可以全局定义。
关于java - JSP 中的变量没有增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110461/