kangdong

Untitled

Jun 8th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. package mvc;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Map;
  5.  
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8.  
  9. import login.LoginFailException;
  10. import login.LoginService;
  11. import login.User;
  12. import mvc.CommandHandler;
  13.  
  14. public class LoginHandler implements CommandHandler {
  15.  
  16.     private static final String FORM_VIEW = "/view/loginForm.jsp";
  17.     private LoginService loginService = new LoginService();
  18.  
  19.     @Override
  20.     public String process(HttpServletRequest req, HttpServletResponse res) throws Exception {
  21.         if (req.getMethod().equalsIgnoreCase("GET")) {
  22.             return processForm(req, res);
  23.         } else if (req.getMethod().equalsIgnoreCase("POST")) {
  24.             return processSubmit(req, res);
  25.         } else {
  26.             res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
  27.             return null;
  28.         }
  29.     }
  30.  
  31.     private String processForm(HttpServletRequest req, HttpServletResponse res) {
  32.         return FORM_VIEW;
  33.     }
  34.  
  35.     private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws Exception {
  36.         String id = trim(req.getParameter("id"));
  37.         String password = trim(req.getParameter("password"));
  38.  
  39.         Map<String, Boolean> errors = new HashMap<>();
  40.         req.setAttribute("errors", errors);
  41.  
  42.         if (id == null || id.isEmpty())
  43.             errors.put("id", Boolean.TRUE);
  44.         if (password == null || password.isEmpty())
  45.             errors.put("password", Boolean.TRUE);
  46.  
  47.         if (!errors.isEmpty()) {
  48.             return FORM_VIEW;
  49.         }
  50.  
  51.         try {
  52.             User user = loginService.login(id, password);
  53.             req.getSession().setAttribute("authUser", user);
  54.             res.sendRedirect(req.getContextPath() + "/index.jsp");
  55.             return null;
  56.         } catch (LoginFailException e) {
  57.             errors.put("idOrPwNotMatch", Boolean.TRUE);
  58.             return FORM_VIEW;
  59.         }
  60.     }
  61.  
  62.     private String trim(String str) {
  63.         return str == null ? null : str.trim();
  64.     }
  65. }
Add Comment
Please, Sign In to add comment