用戶註冊和登陸案例(服務器端:數據控制,業務層,dao層)

用戶註冊和登陸案例(服務器端):html

1 創建工程,搭建開發環境:
dom4j.jar
jaxen.jarjava

commons-beanutils.jar
commons-logging.jarnode

standard.jar
jstl.jar(這兩個編譯工具自己就有)web

2創建開發須要用的包:
1 itcast.cn.domain 放置javabean   導入數據庫
2 itcast.cn.dao  Dao接口
3 itcast.cn.dao.impl Dao接口的實現
4 itcast.cn.servlet  業務接口
5 itcast.cn.servlet.impl 業務接口的實現
6 itcast.web.controller.Servlet控制器
7 page.jsp  視圖數據庫

把握兩點:
1 先寫好javabean
2 寫好業務接口服務器

 

開發步驟:
1寫好javabean:
public class User implements Serializable {
 private String usename;
 private String password;
 private String email;
 private Date birthday;
 
 public String getUsename() {
  return usename;
 }
 public void setUsename(String usename) {
  this.usename = usename;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public Date getBirthday() {
  return birthday;
 }
 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }
}session

2 創建xml用以存放數據,模擬數據庫
<?xml version="1.0" encoding="UTF-8"?>
<Users>
 <User usename="djw" password="123" email="sada@qq.com" birthday="1991-06-11"></User>
</Users>dom

3創建業務接口:
public interface BusinessServlet {
 /**
  * 完成用戶註冊
  * @param user 用戶信息
  * @throws UserExistException 當用戶名已經存在時,拋出異常
  */
 void regist(User user) throws UserExistException;
 
 /**
  * 完成用戶登陸
  * @param usename 用戶名
  * @param password  密碼
  * 當賬號或者密碼不正確時,返回null
  */
 void login(String usename,String password);
 
}jsp

異常UserExistException爲一個自定義類,
代碼:
package itcast.cn.exception;工具

public class UserExistException extends Exception {

 public UserExistException() {
 }

 public UserExistException(String message) {
  super(message);
 }

 public UserExistException(Throwable cause) {
  super(cause);
 }

 public UserExistException(String message, Throwable cause) {
  super(message, cause);

 }

}

4 創建dao接口:
public interface UserDao {
 /**
  * 保存用戶信息
  * @param user
  */
 void save(User user);
 /**
  * 根據用戶名查找用戶
  * @param usename
  * @return 若是用戶名不存在,則返回null
  */
 void findUserByUsername(String usename);
 /**
  * 根據用戶名和密碼卡查找用戶
  * @param usename
  * @param password
  * @return 若是用戶名不存在,則返回null
  */
 void findUser(String usename,String password);
}

5 實現dao接口:

5.1:建立工具類:
1 dom4jUntil:
代碼:
public class Dom4jUntil {
 //建立真實路徑
 private static String DB_FILEPATH;
 //用類加載器解析xml文件
 static{
  //獲取類加載器
  ClassLoader cl=Dom4jUntil.class.getClassLoader();
  //查找全部給定名稱的資源
  URL url=cl.getResource("Users.xml");
  //獲取文件的真實路徑
  DB_FILEPATH=url.getPath();
 }
 //讀取xml文件中的屬性
 public static Document getdocument() throws Exception{
  //讀取xml中的屬性
  SAXReader sr=new SAXReader();
  return sr.read(DB_FILEPATH);
 }
 //將屬性寫入xml文件
 public static void write2xml(Document document) throws Exception, FileNotFoundException{
  OutputFormat format=OutputFormat.createPrettyPrint();
  XMLWriter xw=new XMLWriter(new FileOutputStream(DB_FILEPATH), format);
  xw.write(document);
  xw.close();
 }
}
2:WebUtil
public class WebUtil {

 public static <T>T fillBean(HttpServletRequest request,
   Class<T> class1) {
  T bean;
  try {
   bean = class1.newInstance();
   BeanUtils.populate(bean, request.getParameterMap());
   return bean;
  } catch (Exception e) {
   throw new RuntimeException();
  }
 }
 
}

5.2 實現dao接口:
public class UserDaoDom4jImpl implements UserDao {

 public void save(User user) {
  try {
   //獲取節點
   Document document=Dom4jUntil.getdocument();
   //獲取根元素
   Element root=document.getRootElement();
   //建立user元素
   Element UserElement=DocumentHelper.createElement("user");
   //往user元素中添加屬性
   UserElement.addAttribute("username", user.getUsename());
   UserElement.addAttribute("password", user.getPassword());
   UserElement.addAttribute("email", user.getEmail());
   UserElement.addAttribute("birthday", user.getBirthday().toLocaleString());
   //添加到根元素
   root.add(UserElement);
   //將節點寫回到xml
   Dom4jUntil.write2xml(document);
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

 public User findUserByUsername(String username) {
  try {
   Document document=Dom4jUntil.getdocument();
   //獲取路徑
   String xpath="//user[@username='"+username+"']";
   //獲取指定路徑文件的節點
   Node node=document.selectSingleNode(xpath);
   //若是沒有找到
   if(node==null){
    return null;
   }
   //找到了
   User user=new User();
   user.setUsename(node.valueOf("@username"));
   user.setPassword(node.valueOf("@password"));
   user.setEmail(node.valueOf("@email"));
   //將字符串解析成時間
   DateFormat df=new SimpleDateFormat();
   user.setBirthday(df.parse(node.valueOf("@birthday")));
   return user;
   
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

 public User findUser(String username, String password) {
  try {
   Document document=Dom4jUntil.getdocument();
   //獲取路徑
   String xpath="//user[@username='"+username+"' and @password='"+password+"']";
   //獲取指定路徑文件的節點
   Node node=document.selectSingleNode(xpath);
   //若是沒有找到
   if(node==null){
    return null;
   }
   //找到了
   User user=new User();
   user.setUsename(node.valueOf("@username"));
   user.setPassword(node.valueOf("@password"));
   user.setEmail(node.valueOf("@email"));
   //將字符串解析成時間
   DateFormat df=new SimpleDateFormat();
   user.setBirthday(df.parse(node.valueOf("@birthday")));
   return user;
   
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
}

6 實現業務接口:

public class BusinessServeltImpl implements BusinessServlet {
 UserDaoDom4jImpl dao=new UserDaoDom4jImpl();
 public void regist(User user) throws UserExistException {
   User dbUser= dao.findUserByUsername(user.getUsename());
   if(dbUser==null){
    throw new UserExistException(user.getUsename()+"已經存在");
   }
   dao.save(user);
 }

 public User login(String username, String password) {
   return dao.findUser(username, password);
 }
}


7測試類,測試dao接口和業務接口的實現
public class BusinessServletImplTest {
 BusinessServeltImpl bs=new BusinessServeltImpl();
 @Test
 public void testRegist() throws Exception {
  User user=new User();
  user.setUsename("fff");
  user.setPassword("123");
  user.setEmail("djw@qq.com");
  user.setBirthday(new Date());
  bs.regist(user);
 }

 @Test
 public void testLogin() {
  User u=bs.login("rrr", "123");
  assertNull(u);
  u=bs.login("djw", "123");
  assertNotNull(u);
 }
}

8寫界面:
主頁面:
 <body>
    XX網站<hr/>
    <c:if test="${sessionScope.user==null}">
     <a href="${pageContext.request.contextPath}/login.jsp">登陸</a>
     <a href="${pageContext.request.contextPath}/regist.jsp">註冊</a>
    </c:if>
    <c:if test="${sessionScope.user!=null}">
     <a href="${pageContext.request.contextPath}/servlet/Logout">註銷</a>
    </c:if>
  </body>

 註冊頁面:
  <body>
    註冊<hr/>
    <form action="${pageContext.request.contextPath}/servlet/RegistServlet" method="post">
     <table border="1">
      <tr>
      <th>用戶名:(必須輸入,3-8位字母組成)</th>
      <td><input type="text" name="username" value="${formBean.username}">${formBean.errors.username}</td>
      <tr/>
      <tr>
      <th>密碼:(必須輸入,3-8位數字組成)</th>
      <td><input type="password" name="password" value="">${formBean.errors.password}</td>
      <tr/>
      <tr>
      <th>確認密碼:(再次輸入密碼)</th>
      <td><input type="password" name="password2" value="">${formBean.errors.password2 }</td>
      <tr/>
      <tr>
      <th>郵箱:(符合郵箱格式)</th>
      <td><input type="text" name="email" value="${formBean.email }">${formBean.errors.email}</td>
      <tr/>
      <tr>
      <th>出生日期:(格式:1991-06-11)</th>
      <td><input type="text" name="birthday" value="${formBean.birthday}">${formBean.errors.birthday}</td>
      <tr/>
      <tr>
      <td><input type="submit" value="註冊" ></td>
      <tr/>
     </table>
    </form>
  </body>

  登陸頁面:
  <body>
    登陸<hr/>
    <form action="${pageContext.request.contextPath}/servlet/LoginServlet" method="post">
     <table border="1">
      <tr>
      <th>用戶名:(必須輸入,3-8位字母組成)</th>
      <td><input type="text" name="username"></td>
      <tr/>
      <tr>
      <th>密碼:(必須輸入,3-8位數字組成)</th>
      <td><input type="password" name="password"></td>
      <tr/>
      <tr>
      <td><input type="submit" value="登陸" ></td>
      <tr/>
     </table>
    </form>
  </body>

 


註冊數據控制:

RegistServlet:
public class RegistServlet extends HttpServlet {
 private BusinessServlet s=new BusinessServeltImpl();
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //編碼問題
  request.setCharacterEncoding("UTF-8");
  response.setContentType("text/html;charset=UTF-8");
  //數據封裝
  RegistServletFormBean formBean=WebUtil.fillBean(request,RegistServletFormBean.class);
  //驗證不經過,數據回顯
  if(!formBean.validate()){
   request.setAttribute("formBean", formBean);
   request.getRequestDispatcher("/regist.jsp").forward(request, response);
   return;
  }
  //數據填充模型,將formbean中的數據填充到新的user對象
  User user=new User();
  try {
   //註冊類型轉換器
   ConvertUtils.register(new DateLocaleConverter(), Date.class);
   BeanUtils.copyProperties(user, formBean);
  } catch (Exception e) {
   e.printStackTrace();
  }
    
  try {
   s.regist(user);
   //轉向默認主頁
   response.setHeader("Refresh", "2;URL="+request.getContextPath());
   response.getWriter().write("註冊成功,2秒後轉向主頁");
  } catch (UserExistException e) {
   formBean.getErrors().put("username", "用戶名已經存在");
   request.setAttribute("formBean", formBean);
   request.getRequestDispatcher("/regist.jsp").forward(request, response);
  }
 }
註冊數據封裝類:
public class RegistServletFormBean {
 private String username;
 private String password;
 private String password2;
 private String email;
 private String birthday;
 private Map<String, String> errors=new HashMap<String, String>();
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public String getBirthday() {
  return birthday;
 }
 public void setBirthday(String birthday) {
  this.birthday = birthday;
 }
 public Map<String, String> getErrors() {
  return errors;
 }
 public void setErrors(Map<String, String> errors) {
  this.errors = errors;
 }
 public String getPassword2() {
  return password2;
 }
 public void setPassword2(String password2) {
  this.password2 = password2;
 }
 public boolean validate(){
  //只要不知足要求的,就像errors中放消息
  
    //用戶名必須輸入,3~8位字母組成
    if(username==null||username.equals("")){
     errors.put("username", "請求輸入用戶名");
    }else{
     if(!username.matches("[a-zA-Z]{3,8}")){
      errors.put("username", "用戶名必須3至8位字母組成");
     }
    }
    //密碼必須輸入,3~8位數字組成
    if(password==null||password.equals("")){
     errors.put("password", "請求輸入密碼");
    }else{
     if(!password.matches("\\d{3,8}")){
      errors.put("password", "密碼必須3至8位數字組成");
     }
    }
    
    //重複密碼必須和密碼一致
    if(!password.equals(password2)){
     errors.put("password2", "兩次密碼必須一致");
    }
    //郵箱必須輸入,且要符合郵箱的格式
    if(email==null||email.equals("")){
     errors.put("email", "請輸入郵箱");
    }else{
     if(!email.matches("\\b^['_a-z0-9-\\+]+(\\.['_a-z0-9-\\+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2}|aero|arpa|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|nato|net|org|pro|tel|travel|xxx)$\\b")){
      errors.put("email", "請輸入正確的郵箱");
     }
    }
    //出生日期 必須輸入,格式2001-03-18
    if(birthday==null||birthday.equals("")){
     errors.put("birthday", "請輸入出生日期");
    }else{
//     DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
     try {
      //轉換
      new DateLocaleConverter().convert(birthday);
     } catch (Exception e) {
      errors.put("birthday", "請輸出正確的日期");
     }
    }
    
    return errors.isEmpty();
   }

}

登陸數據控制:
public class LoginServlet extends HttpServlet {
 private BusinessServlet s=new BusinessServeltImpl();
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //登陸
  request.setCharacterEncoding("UTF-8");
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out=response.getWriter();
  //獲取到用戶名和密碼
  String username=request.getParameter("username");
  String password=request.getParameter("password");
  User user=s.login(username, password);
  if(user==null){
   out.write("用戶名或者密碼錯誤,2秒後轉向登陸頁");
   response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/login.jsp");
  }else{
   out.write("登陸成功,2秒後轉向主頁");
   request.getSession().setAttribute("user", user);
   response.setHeader("Refresh", "2;URL="+request.getContextPath());
  }
 }

註銷數據控制:
public class Logout extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  request.setCharacterEncoding("UTF-8");  response.setContentType("text/html;charset=UTF-8");  PrintWriter out=response.getWriter();  request.getSession().removeAttribute("user");  out.write("註銷成功,2秒後轉向主頁");  response.setHeader("Refresh", "2;URL="+request.getContextPath()); }

相關文章
相關標籤/搜索