登录验证操作login_action.jsp

2、登录验证操作login_action.jsp

接下来开发登录提交时的相应处理页面login_action.jsp。该页面不用于显示,其作用是检验用户的用户名和密码是否合法。按照顺序需要编写以下的代码:

①由于要进行数据库查询,因此首先使用include指令包含数据库配置文件inc.jsp;

②取得login.jsp页面中用户输入的用户名和密码的参数变量username和password;

③检查用户名和密码是否为空,如果有一个为空,则返回页面login.jsp重新登录;

④定义一个变量isValid来表示是否验证通过。根据用户名和密码的参数组合查询的SQL语句,从用户表user中查询记录。建立数据库的连接,并执行该SQL语句的查询。如果能够查询到记录,则表示用户名和密码正确,则赋予isValid为true。并依次关闭rs、stm、conn对象;

⑤判断isValid的值,如果为真,则表示验证通过,此时需要调用Session的setAttritute()方法来保存用户的用户名,并跳转到欢迎页面welcome.jsp;如果为假,则返回到登录页面login.jsp。

最后的代码如程序4-5所示。
<%@ include file="inc.jsp"%>
<% 
//get parameters 
String username = request.getParameter("username"); 
String password = request.getParameter("password"); 

//check null 
if (username == null || password == null) { 
      response.sendRedirect("login.jsp"); 


//validate 
boolean isValid = false; 
String sql = "select * from user where username='"
+username+"' and password='"+password+"'"; 
try { 
Class.forName(drv).newInstance(); 
Connection conn = DriverManager.getConnection(url, usr, pwd); 
      Statement stm = conn.createStatement(); 
      ResultSet rs = stm.executeQuery(sql); 
      if(rs.next())isValid = true; 
      rs.close(); 
      stm.close(); 
      conn.close(); 
} catch (Exception e) { 
      e.printStackTrace(); 
      out.println(e); 
} finally { 


if (isValid) { 
session.setAttribute("username", username); 
      response.sendRedirect("welcome.jsp"); 
} else { 
      response.sendRedirect("login.jsp"); 

%>

猜你喜欢

转载自huangcaiyan.iteye.com/blog/2230122