Struts1.x 用户登录模块的实现
页面验证部分:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset==UTF-8"> 7 <title>Insert title here</title> 8 <script type="text/javascript" src="resources/js/lib/jquery.min.js"></script> 9 <script type="text/javascript"> 10 $(function(){ 11 $("[type='button']").click(function(){ 12 if($.trim($("[name='userName']").val()) == ""){ 13 $("[name='userName']").select(); 14 $("[name='userName']").focus(); 15 $("#msg").html("请输入用户名!"); 16 return; 17 } 18 if($.trim($("[name='pwd']").val()) == ""){ 19 $("[name='pwd']").select(); 20 $("[name='pwd']").focus(); 21 $("#msg").html("请输密码!"); 22 return; 23 } 24 $.post("user.do?op=checkLogin",{userName:$("[name='userName']").val(),pwd:$("[name='pwd']").val()},function(data){ 25 if(data == "1"){ 26 location.href = "main.jsp"; 27 } 28 else{ 29 $("#msg").html("用户名密码错误,请重新输入!"); 30 } 31 }); 32 }); 33 }); 34 </script> 35 </head> 36 <body> 37 用户注册<br/> 38 39 <form method="post" action="addUser.do"> 40 <table> 41 <tr> 42 <td>用户名:</td> 43 <td><input type="text" name="userName"/></td> 44 </tr> 45 <tr> 46 <td>密码:</td> 47 <td><input type="password" name="pwd"/></td> 48 </tr> 49 <tr> 50 <td colspan="2"> 51 <input type="button" value="提 交"/> 52 </td> 53 </tr> 54 </table> 55 </form> 56 <div id="msg"></div> 57 <br/> 58 <br/> 59 <a href="main.jsp">返回主页面</a> 60 </body> 61 </html>
上面的代码说明一个地方:在ajax的post方法中,回调函数 return false 表单是还会提交的,所以没办法,只能将提交按钮改为type="button",暂时没想到其他办法。
DAO
1 /** 2 * 登录检查 3 * @param user 4 * @return 5 */ 6 public boolean checkLogin(User user){ 7 boolean flag = false; 8 String sql = "select * from users where userName = ? and pwd=?"; 9 Connection conn = DBLib.getConn(); 10 PreparedStatement pstmt; 11 try { 12 pstmt = conn.prepareStatement(sql); 13 pstmt.setString(1, user.getUserName()); 14 pstmt.setString(2, user.getPwd()); 15 ResultSet set = pstmt.executeQuery(); 16 if(set.next()){ 17 flag = true; 18 } 19 set.close(); 20 pstmt.close(); 21 } catch (SQLException e) { 22 e.printStackTrace(); 23 } finally{ 24 try { 25 conn.close(); 26 } catch (SQLException e) { 27 e.printStackTrace(); 28 } 29 } 30 return flag; 31 }
Action 方法
1 /** 2 * 登录认证 3 * @param mapping 4 * @param form 5 * @param request 6 * @param response 7 * @return 8 * @throws Exception 9 */ 10 public ActionForward checkLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, 11 HttpServletResponse response) throws Exception { 12 User user = (User)form; 13 UserDAO dao = new UserDAO(); 14 String rel = dao.checkLogin(user) ? "1" : "0"; 15 response.getWriter().write(rel); 16 return null; 17 }
struts-config.xml就不用配置了。
OK.
代码链接:http://pan.baidu.com/s/1qYe1rWw 提取码:8zt3