关于登录模块的编写(新手模块化编程)

来源:互联网 发布:淘宝客服培训视频 编辑:程序博客网 时间:2024/06/09 17:05

    该实例主要使使用Servlet+mysql+jsp基于mvc开发模式进行开.(由于本人项目经验的问题,代码编写不尽人意,错误之处希望多多指点)

数据库的中的用户表 :

数据库表设计  

       在myeclipse中的文件目录结构 :

            首先,编写登录页面,并完成相应的客户端验证 :

     <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      <%
                   String path = request.getContextPath();
   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
   %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function validate(){// 简单的客户端验证

var name = document.getElementsByName("name")[0] ;

var pwd  = document.getElementsByName("password")[0] ;
if(name.value.length == 0){
alert("用户名不能为空") ;
return false ;
}
if(pwd.value.length == 0 ){
alert("密码不能为空") ;
return false ;
}
return true ;
}
</script>
  </head>
  <body>
    <center>
    <form onsubmit="return validate() ;" action="CheckLogin" method="POST"> 
    <table border="1"bordercolor="green" name="myForm"width="80%">
    <tr>
    <td colspan="2" align="center">
    <font color="red">欢迎登陆 XXX系统 ,<br><br>
    请输入用户名,密码,密保号登入 :</font><br><br>
    </td>
    </tr>
    <tr>
    <td>
    用&nbsp;&nbsp;&nbsp;&nbsp;户&nbsp;&nbsp;&nbsp;&nbsp;名 :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="text"name="name"/>&nbsp;&nbsp;
    <font color="red">${requestScope.error1}</font> 
    </td>
    </tr>
    <tr>
    <td>
    密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码 :&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="password"name="password" />&nbsp;&nbsp;
    <font color="red">${requestScope.error2} </font>
    </td>
   
    </tr>
    <tr>
    <td>
    <%      int b1 = 0 ;//记录伪随机数1
    int b2 = 0 ;//记录伪随机数2
    %>
    第一行密保中的第<% Random rand = new Random () ;%><%=(b1 = rand.nextInt(6) + 1) %>个字符是:
    <input type="password" name="mb1" /> &nbsp;&nbsp;
    <font color="red">${requestScope.error3} </font>
    </td>
    </tr>
    <tr>
    <td>
    第二行密保中的第<%=(b2=rand.nextInt(6)+1) %>个字符是:
    <input type="password"name="mb2"/>&nbsp;&nbsp;
    <font color="red">${requestScope.error4}</font>
    </td>
    </tr>
    <tr>
    <td colspan="2" align="center">
    <input type="submit" value="提交"/>
    <input type="reset"value="重置" />&nbsp;&nbsp;
    </td>
    </tr>
    </table>
    <input type="hidden" name="m1"value="<%=b1%>" />
    <input type="hidden" name="m2"value="<%=b2%>" />
    </form>
    </center>
  </body>
</html>

                      实体bean的开发(使用JavaBean)

   package com.logsys.entity;
/**
  * 提供用户数据封装的 Bean
  * @author Administrator
  *
  */
public class UserModel {


// 定义用户 这个对象的属性列表 
private String name ;
private String password ;
private String firstline ;
private String secondline  ;
// 提供默认的构造方法 ,使得创建对象时传入参数过多,影响阅读性
public UserModel(){
}
// 生成用户这个模型对象的getter与setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstline() {
return firstline;
}
public void setFirstline(String firstline) {
this.firstline = firstline;
}
public String getSecondline() {
return secondline;
}
public void setSecondline(String secondline) {
this.secondline = secondline;
}
// 根据主键写出相应的equals和hashCode,防止该对象使用集合存储和比较排序
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstline == null) ? 0 : firstline.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((password == null) ? 0 : password.hashCode());
result = prime * result
+ ((secondline == null) ? 0 : secondline.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserModel other = (UserModel) obj;
if (firstline == null) {
if (other.firstline != null)
return false;
} else if (!firstline.equals(other.firstline))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (secondline == null) {
if (other.secondline != null)
return false;
} else if (!secondline.equals(other.secondline))
return false;
return true;
}
}

      定义操作用户操作数据库的规范(DAO接口):

package com.logsys.dao.dao;


import com.logsys.entity.UserModel;


/**
  * 规定管理员与数据库的操作的规范
  * @author Administrator
  *
 */
public interface UserDAO {
// 本例比较简单只提供,查询功能.
/**
* 根据姓名查询用户信息
* @param name
* @return
*/
public UserModel getUser(String name) ;
}

DAO的实现类:

package com.logsys.dao.imple;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.management.RuntimeErrorException;
import com.logsys.dao.dao.UserDAO;
import com.logsys.dao.util.DBUtil;
import com.logsys.entity.UserModel;
/**
 * 提供对于用户操作数据库的规范的实现
  */
public class UserDAOImple implements UserDAO {
// 操作数据库的连接对象和结果集以及PreparedStatement
private Connection conn = null ;
private PreparedStatement psm = null ;
private ResultSet rs = null ;
@Override
public UserModel getUser(String name) {
UserModel model = null ;
try {
conn = DBUtil.getConnection() ;
String sql = "select name,password,firstline,secondline from user where name =?" ;
psm = conn.prepareStatement(sql);
psm.setString(1, name) ;
rs = psm.executeQuery() ;
if(rs.next()){
model = new UserModel() ;
model.setName(rs.getString("name")) ;
model.setPassword(rs.getString("password")) ;
model.setFirstline(rs.getString("firstline")) ;
model.setSecondline(rs.getString("secondline")) ;
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("获取连接失败..."+e) ;
}
return model;
}
}

创建UserDAO实例的工厂方法:

package com.logsys.dao.factory;
import com.logsys.dao.dao.UserDAO;
import com.logsys.dao.imple.UserDAOImple;
/**
  * 获取UserDAO的实例 
  * @author Administrator
  *
  */
public class UserDAOFactory {


// 防止外建立实例
private UserDAOFactory () {}
// 生成UserDAO实例,并返回
public static UserDAO getUserDAO(){
return new UserDAOImple() ;
}
       }

处理客户端请求的Servlet

package com.logsys.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.logsys.dao.factory.UserDAOFactory;
import com.logsys.entity.UserModel;
public class CheckLogin extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 获取用户名,密码,密保
String name = req.getParameter("name") ;
String pwd = req.getParameter("password") ;
String mb1 = req.getParameter("mb1") ;
String mb2 = req.getParameter("mb2") ;
UserModel user = UserDAOFactory.getUserDAO().getUser(name) ;
if(user != null){
// 数据库中存在该用户 ,判断其密码,密保
if(!user.getPassword().equals(pwd)){
// 密码不正确
req.setAttribute("error2", "密码不正确") ;
dispathURI(req, resp, "/login.jsp") ;
return ;
}
// 密码正确,第一行密保号.
int m1 = Integer.valueOf(req.getParameter("m1")) ;
int m2 = Integer.valueOf(req.getParameter("m2")) ;
String userM1 = user.getFirstline().substring(m1-1,m1);
String userM2 = user.getSecondline().substring(m2-1,m2) ;
if(!userM1.equals(mb1)){
// 第一行密保验证有误....
req.setAttribute("error3", "第一行验证码有误 ") ;
dispathURI(req, resp, "/login.jsp") ;
return ;
}
if(!userM2.equals(mb2)){
//第二行密保号有误....
req.setAttribute("error4", "第二行验证码错误") ;
dispathURI(req, resp, "/login.jsp") ;
return ;
}
//所有的用户数据验证成功
req.getSession().setAttribute("user", user) ;
dispathURI(req, resp, "/index.jsp") ;
return ;
}else{
//用户名在数据库中不存在.
req.setAttribute("error1", "用户名不存在");
dispathURI(req, resp, "/login.jsp") ;
return ;
}
}
/**
* 该方法根据uri来转发页面.
* @param req
* @param resp
* @param uri
* @throws IOException 
* @throws ServletException 
*/
private void dispathURI(HttpServletRequest req ,HttpServletResponse resp,String uri) 
throws ServletException, IOException{
req.getRequestDispatcher(uri).forward(req, resp) ;
}
}

总结: 该实例主要是练习数据库与用户的交互操作,实际意义不大 ...