登录验证操作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");
}
%>
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值