javaweb登录后台的简单处理

来源:互联网 发布:淘宝网钓鱼竿 编辑:程序博客网 时间:2024/05/22 17:24

登录通过request.getParameter()方法获取用户名和密码 ,然后通过String sql = "select * from userinfo where username = '"+username+"'and password ='"+password+"'";sql语句查询时,如果从数据库中查不出数据,则通过

while(rs.next()){

user = rs.getString("username");
pass = rs.getString("password");
}

去遍历用户名和密码没有意义,也不用if(username.equals(user) && password.equals(pass)){}去判断是否相等,user和pass都为空,这两个变量已经声明为doGet方法的局部变量了且初始值为null。

登录可以改成执行String sql = "select * from userinfo where username = '"+username+"'and password 查询语句后,可以直接判断"rs.next"的返回值,返回值类型是boolean,如果为flase则不存在跳回登录页面,如果为true则登录成功。

****注:有人会这么想,如果用户名对了,密码不对或者反过来,会不会返回值还是true? 不会,肯定不会,必须在同一条字段里同时存在返回值才是true。注意SQL语句,WHERE后面的条件是and。。。。还有为了安全性考虑,一般都会用MD5进行加密,(MD5属于单向加密算法,不可逆,安全性较高)。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub
try {
String user = null;
String pass = null;
String username = request.getParameter("username");
String password = request.getParameter("password");
//将获取到的数据用MD5进行单向加密
username = EncryptUtil.encryptMD5(username);
password = EncryptUtil.encryptMD5(password);
//获取用户名输入的验证码
String captchaText = request.getParameter("captchaText");
//获取session中保存的随机验证码
String captchakey = request.getSession().getAttribute("validate").toString();
if(captchaText.equals(captchakey)){
System.out.println("SQL语句开始执行");
String sql = "select * from userinfo where username = '"+username+"'and password ='"+password+"'";
ResultSet rs = JDBC.getInstance().getResult(sql);
while(rs.next()){
user = rs.getString("username");
pass = rs.getString("password");
}


System.out.println(user);
System.out.println(pass);

if(username.equals(user) && password.equals(pass)){
RequestDispatcher rd = request.getRequestDispatcher("main.jsp");
rd.forward(request, response);
}else{
request.getRequestDispatcher("login.jsp").forward(request, response);

}
request.getRequestDispatcher("loginServlet.do").forward(request, response);
}else{
System.out.println("登录失败");
request.getRequestDispatcher("login.jsp").forward(request, response);
}

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
原创粉丝点击