在线急等,关于一个很简单的javabean+jsp登陆问题
昨天发贴问题没有解决,今天再发希望能够解决
初学JSP有许多问题不懂,最近就有一个做登录的,在javabean中定义了两个类
public class ConnUtil {
public static Connection getuser() {
Connection conn = null;
try {
String url = "jdbc:odbc:news ";
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver ");
conn = DriverManager.getConnection(url, " ", " ");
} catch (Exception e) {
System.out.print(e.toString());
}
return conn;
}
public static void closeConnection(Connection conn) {
try {
conn.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
还有一个查询表的
public class UserDenglu {
Connection conn = ConnUtil.getuser();
public ResultSet getdentlu(Connection conn, HttpServletRequest request) {
ResultSet rs = null;
try {
String username = request.getParameter( "username ");
String password = request.getParameter( "password ");
Statement smt = conn.createStatement();
String sql = "select username,password from usersdenglu where username= ' "+username+ " ' ";
sql+= "and password= ' "+password+ " ' ";
smt.executeQuery(sql);
System.out.println(sql);
} catch (Exception e) {
System.out.println(e.toString());
}
return rs;
}
在页面中这样调用:
<%
String username = request.getParameter( "username ");
String password = request.getParameter( "password ");
request.setCharacterEncoding( "gb2312 ");
Connection conn = ConnUtil.getuser();
UserDenglu bean = new UserDenglu();
ResultSet rs = bean.getdentlu(conn, request);
if(rs.getString( "Username ")!=null && rs.getString( "password ")!=null){
if (rs.next()) {
session.setAttribute( "username ", username);
session.setAttribute( "password ", password);
response.sendRedirect( "homepage.jsp ");
}
} else {
out.print( " <script language=javascript> alert( '用户名或密码错误! ') ");
}
%>
但是运行时说第一个if语句哪儿有问题;真的不知道怎么解决,麻烦各位高手帮忙看一下,是哪儿错呢?在下不胜感激,从控制台输出的SQL语句都是空值;麻烦各位解决;
我用的是access数据库,数据源名在上面已经定义,问题解决马上结贴
[解决办法]
class改一下:
public class UserDenglu {
Connection conn = ConnUtil.getuser(); //这个不要,不然会出现连数据库2次。
public ResultSet getdentlu(Connection conn, HttpServletRequest request) {
ResultSet rs = null;
try {
String username = request.getParameter( "username ");
String password = request.getParameter( "password ");
Statement smt = conn.createStatement();
String sql = "select username,password from usersdenglu where username= ' "+username+ " ' ";
sql+= "and password= ' "+password+ " ' ";
smt.executeQuery(sql);//这里改为:rs = smt.executeQuery(sql);
System.out.println(sql);
} catch (Exception e) {
System.out.println(e.toString());
}
return rs;
}
[解决办法]
1.应该先用rs = smt.executeQuery(sql);
否则你的rs永远都是Null;
2.不要用ResultSet rs = bean.getdentlu(conn,request);来传参
讲方法中形参改为 ResultSet rs = bean.getdentlu(conn,username,password);试试
username,password是你页面中取到的值
[解决办法]
lizhe0428
说的好像有道理!
lz, 你先判断一下
String username = request.getParameter( "username ");
String password = request.getParameter( "password ");是不是为空,如果他们俩为空,他们俩如果为空,你执行的sql就如你上面所说的了!!!