有两个点。
1. rs cannot be resolved to a variable(无法将rs解析为变量)
通过查找发现少定义了 Resultset rs = null; 等
原因:定义在try{}代码块里,就使它们成了局部变量,只在try{}里有效,而不是全局变量,导致下面代码不能使用。
2.在这个代码中,rs、pstmt、conn如果不判断是否为空,则错误。
错误类型为java.lang.NullPointerException(空指针异常)
而在之前写这种代码的时候,我从来没有判断过,但是也没有错误。为什么这里就必须要判断了?
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录提交页面</title>
</head>
<body>
<form action="1_yanzheng.jsp" method="post">
<table>
<tr><td>用户名:</td><td><input type="text" name="username"></td></tr>
<tr><td>用户密码:</td><td><input type="text" name="passward"></td></tr>
<tr align="center">
<td colspan="2"><input type="submit" value="提交">
</td></tr>
</table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录验证界面</title>
</head>
<body>
<%
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
String driverName="com.mysql.jdbc.Driver";
String dbName="user";
String url1="jdbc:mysql://localhost:3306/"+dbName;
String url2="?user=***&passward=***";
String url3="&useUnicode=true&characterEncoding=UTF-8";
String url=url1+url2+url3;
Class.forName(driverName);
conn=DriverManager.getConnection(url,"***","***");
String sql="select uname,upassward from user_b where uname=? and upassward=?";
pstmt=conn.prepareStatement(sql);
request.setCharacterEncoding("UTF-8");
String name=request.getParameter("username");
String pw=request.getParameter("passward");
pstmt.setString(1, name);
pstmt.setString(2, pw);
rs=pstmt.executeQuery();
if(rs.next()){%><%=name %>:登录成功<br><%
}
else%>登录失败<br><%
}catch(Exception e){%>出现异常错误
<%= e.getMessage()%><% }
finally{
if(rs!=null){rs.close();}
if(pstmt!=null){pstmt.close();}
if(conn!=null){conn.close();}
}
%>
</body>
</html>