javaweb 도서 상점 디자인 의 사용자 모듈(1)

14777 단어 javaweb도서 상점
본 고 는 주로 여러분 을 위해 도서 상점 의 사용자 모듈 을 분 석 했 는데 구체 적 인 내용 은 다음 과 같다.

1.사용자 모듈 의 관련 클래스 생 성
domain:User
dao:UserDao
service:UserDao
web.servlet:UserServlet
2.사용자 등록
2.1 등록 절차
/jsps/user/regist.jsp -> UserServlet#regist() -> msg.jsp
2.2 등록 페이지

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>

 <title>  </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">
 <meta http-equiv="content-type" content="text/html;charset=utf-8">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

 </head>

 <body>
 <h1>  </h1>
 <%--
 1.   errors -->     
 2.       
 3.   
 --%>
<p style="color: red; font-weight: 900">${msg }</p>
<form action="<c:url value='/UserServlet'/>" method="post">
 <input type="hidden" name="method" value="regist"/>
    :<input type="text" name="username" value="${form.username }"/>
 <span style="color: red; font-weight: 900">${errors.username }</span>
 <br/>
    :<input type="password" name="password" value="${form.password }"/>
 <span style="color: red; font-weight: 900">${errors.password }</span>
 <br/>
    :<input type="text" name="email" value="${form.email }"/>
 <span style="color: red; font-weight: 900">${errors.email }</span>
 <br/>
 <input type="submit" value="  "/>
</form>
 </body>
</html>

2.3 UserServlet
User

/**
 * User     
 */
public class User {
 /*
  *       
  */
 private String uid;//   
 private String username;//    
 private String password;//   
 private String email;//   
 private String code;//    
 private boolean state;//   (       )

BaseServlet

public class BaseServlet extends HttpServlet {
 /*
  *         method,            
  */
 protected void service(HttpServletRequest req, HttpServletResponse res)
   throws ServletException, IOException {
  req.setCharacterEncoding("UTF-8");
  res.setContentType("text/html;charset=utf-8");
  try {
   //   :http://localhost:8080/demo1/xxx?m=add
   String method = req.getParameter("method");//         
   Class c = this.getClass();
   Method m = c.getMethod(method, HttpServletRequest.class,
     HttpServletResponse.class);
   String result = (String) m.invoke(this, req, res);
   if(result != null && !result.isEmpty()) {
    req.getRequestDispatcher(result).forward(req, res);
   }
  } catch (Exception e) {
   throw new ServletException(e);
  }
 }
}


UserServlet

/**
 * User   
 */
public class UserServlet extends BaseServlet {
 private UserService userService = new UserService();

 /**
  *     
  * @param request
  * @param response
  * @return
  * @throws ServletException
  * @throws IOException
  */
 public String quit(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.getSession().invalidate();
  return "r:/index.jsp";
 }

 public String login(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  /*
   * 1.        form 
   * 2.     (   )
   * 3.   service    
   * >       、form request,   login.jsp
   * 4.        session ,      index.jsp
   */
  User form = CommonUtils.toBean(request.getParameterMap(), User.class);
  try {
   User user = userService.login(form);
   request.getSession().setAttribute("session_user", user);
   /*
    *           ,  session    Cart  
    */
   request.getSession().setAttribute("cart", new Cart());
   return "r:/index.jsp";
  } catch (UserException e) {
   request.setAttribute("msg", e.getMessage());
   request.setAttribute("form", form);
   return "f:/jsps/user/login.jsp";
  }
 }

 /**
  *     
  * @param request
  * @param response
  * @return
  * @throws ServletException
  * @throws IOException
  */
 public String active(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  /*
   * 1.        
   * 2.   service      
   * >        request ,   msg.jsp
   * 3.        request ,   msg.jsp
   */
  String code = request.getParameter("code");
  try {
   userService.active(code);
   request.setAttribute("msg", "  ,      !     !");
  } catch (UserException e) {
   request.setAttribute("msg", e.getMessage());
  }
  return "f:/jsps/msg.jsp";
 }

 /**
  *     
  * @param request
  * @param response
  * @return
  * @throws ServletException
  * @throws IOException
  */
 public String regist(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  /*
   * 1.        form   
   * 2.   :uid、code
   * 3.     
   * >       、form request ,   regist.jsp
   * 4.   service      
   * >       、form request ,   regist.jsp
   * 5.    
   * 6.          msg.jsp
   */
  //       
  User form = CommonUtils.toBean(request.getParameterMap(), User.class);
  //   
  form.setUid(CommonUtils.uuid());
  form.setCode(CommonUtils.uuid() + CommonUtils.uuid());
  /*
   *     
   * 1.     Map,        ,  key       ,      
   */
  Map<String,String> errors = new HashMap<String,String>();
  /*
   * 2.   form  username、password、email    
   */
  String username = form.getUsername();
  if(username == null || username.trim().isEmpty()) {
   errors.put("username", "       !");
  } else if(username.length() < 3 || username.length() > 10) {
   errors.put("username", "        3~10  !");
  }

  String password = form.getPassword();
  if(password == null || password.trim().isEmpty()) {
   errors.put("password", "      !");
  } else if(password.length() < 3 || password.length() > 10) {
   errors.put("password", "       3~10  !");
  }

  String email = form.getEmail();
  if(email == null || email.trim().isEmpty()) {
   errors.put("email", "Email    !");
  } else if(!email.matches("\\w+@\\w+\\.\\w+")) {
   errors.put("email", "Email    !");
  }
  /*
   * 3.           
   */
  if(errors.size() > 0) {
   // 1.       
   // 2.       
   // 3.    regist.jsp
   request.setAttribute("errors", errors);
   request.setAttribute("form", form);
   return "f:/jsps/user/regist.jsp";
  }

  /*
   *   service regist()  
   */
  try {
   userService.regist(form);
  } catch (UserException e) {
   /*
    * 1.       
    * 2.   form
    * 3.    regist.jsp
    */
   request.setAttribute("msg", e.getMessage());
   request.setAttribute("form", form);
   return "f:/jsps/user/regist.jsp";
  }

  /*
   *    
   *       !
   */
  //         
  Properties props = new Properties();
  props.load(this.getClass().getClassLoader()
    .getResourceAsStream("email_template.properties"));
  String host = props.getProperty("host");//       
  String uname = props.getProperty("uname");//     
  String pwd = props.getProperty("pwd");//    
  String from = props.getProperty("from");//     
  String to = form.getEmail();//     
  String subject = props.getProperty("subject");//    
  String content = props.getProperty("content");//      
  content = MessageFormat.format(content, form.getCode());//  {0}

  Session session = MailUtils.createSession(host, uname, pwd);//  session
  Mail mail = new Mail(from, to, subject, content);//      
  try {
   MailUtils.send(session, mail);//   !
  } catch (MessagingException e) {
  }


  /*
   * 1.       
   * 2.    msg.jsp
   */
  request.setAttribute("msg", "  ,    !        ");
  return "f:/jsps/msg.jsp";
 }
}

2.4 UserService

/**
 * User   
 */
public class UserService {
 private UserDao userDao = new UserDao();

 /**
  *     
  * @param form
  */
 public void regist(User form) throws UserException{

  //      
  User user = userDao.findByUsername(form.getUsername());
  if(user != null) throw new UserException("       !");

  //   email
  user = userDao.findByEmail(form.getEmail());
  if(user != null) throw new UserException("Email    !");

  //         
  userDao.add(form);
 }

 /**
  *     
  * @throws UserException 
  */
 public void active(String code) throws UserException {
  /*
   * 1.   code     ,  user
   */
  User user = userDao.findByCode(code);
  /*
   * 2.   user   ,       
   */
  if(user == null) throw new UserException("     !");
  /*
   * 3.                ,     ,       ,    
   */
  if(user.isState()) throw new UserException("       ,      ,     !");

  /*
   * 4.        
   */
  userDao.updateState(user.getUid(), true);
 }

 /**
  *     
  * @param form
  * @return
  * @throws UserException 
  */
 public User login(User form) throws UserException {
  /*
   * 1.   username  ,  User
   * 2.   user null,    (      )
   * 3.   form user   ,   ,    (    )
   * 4.        ,  false,    (    )
   * 5.   user
   */
  User user = userDao.findByUsername(form.getUsername());
  if(user == null) throw new UserException("      !");
  if(!user.getPassword().equals(form.getPassword()))
   throw new UserException("    !");
  if(!user.isState()) throw new UserException("    !");

  return user;
 }
}

2.5 UserDao

/**
 * User   
 */
public class UserDao {
 private QueryRunner qr = new TxQueryRunner();

 /**
  *       
  * @param username
  * @return
  */
 public User findByUsername(String username) {
  try {
   String sql = "select * from tb_user where username=?";
   return qr.query(sql, new BeanHandler<User>(User.class), username);
  } catch(SQLException e) {
   throw new RuntimeException(e);
  }
 }

 /**
  *  email  
  * @param email
  * @return
  */
 public User findByEmail(String email) {
  try {
   String sql = "select * from tb_user where email=?";
   return qr.query(sql, new BeanHandler<User>(User.class), email);
  } catch(SQLException e) {
   throw new RuntimeException(e);
  }
 }

 /**
  *   User
  * @param user
  */
 public void add(User user) {
  try {
   String sql = "insert into tb_user values(?,?,?,?,?,?)";
   Object[] params = {user.getUid(), user.getUsername(), 
     user.getPassword(), user.getEmail(), user.getCode(),
     user.isState()};
   qr.update(sql, params);
  } catch(SQLException e) {
   throw new RuntimeException(e);
  }
 }

 /**
  *       
  * @param code
  * @return
  */
 public User findByCode(String code) {
  try {
   String sql = "select * from tb_user where code=?";
   return qr.query(sql, new BeanHandler<User>(User.class), code);
  } catch(SQLException e) {
   throw new RuntimeException(e);
  }
 }

 /**
  *            
  * @param uid
  * @param state
  */
 public void updateState(String uid, boolean state) {
  try {
   String sql = "update tb_user set state=? where uid=?";
   qr.update(sql, state, uid);
  } catch(SQLException e) {
   throw new RuntimeException(e);
  }
 }
}

3.사용자 활성화
흐름:사용자 의 메 일 중->UserServlet\#active()->msg.jsp
4、
사용자 로그 인
흐름:/jsps/user/log.jsp->UserServlet\#login()->index.jsp
5、
사용자 종료
흐름:top.jsp->UserServlet\#quit()->login.jsp
quit():세 션 소각!
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기