2017년 12월 6일 수요일

스프링웤 로그인 제작

스프링 mybatis 연동 < 편해짐 
주소록 스프링웤으로 만들어보기
mybatis 사용해보기
제이쿼리
AJAX
차트
엑셀 파일로 저장
성수 메이커스페이스


제작
먼저  스프링 레거시 - > 스프링 MVC -> 아래로 쭉쭉


UserAccountDAO //

package com.cid.login.DAO;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.cid.login.DO.UserAccount;

public class UserAccountDAO {
    Connection conn = null;
    PreparedStatement pstmt = null;
    String jdbc_driver = "oracle.jdbc.driver.OracleDriver";
    String jdbc_url = "jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
    void connect() {
        try {
            Class.forName(jdbc_driver);
            conn = DriverManager.getConnection(jdbc_url, "scott", "tiger");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    void disconnect() {
        if(pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
            }
        }
        if(conn != null) {
            try {
            conn.close();
        } catch (SQLException e) {
                }
        }
    }

    public UserAccount getuserAccount(String userId) {
        connect();
       
        String sql = "SELECT * FROM UserAccount WHERE userId=?";
        UserAccount userAccount = new UserAccount();
       
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
           
            System.out.println("PSTMT:" + pstmt.toString());
            ResultSet rs = pstmt.executeQuery();
           
            if(rs.next() == true) {
            userAccount.setUserId(rs.getString(1));
            userAccount.setUserPassword(rs.getString(2));
            }
            else {
                userAccount = null;
            }
            System.out.println(rs.getString("userid"));
            System.out.println(rs.getString("userPassword"));
            rs.close();
        } catch(Exception e) {
            userAccount = null;
            e.printStackTrace();
        } finally {
            disconnect();
        }
        return userAccount;
    }
}
---------------------------------------------------------------------------
UserAccountDo .java //

package com.cid.login.DO;

public class UserAccount {
    private String userId;
    private String userPassword;
   
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserPassword() {
        return userPassword;
    }
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
}
----------------------------------------------------------------------------
HomeController.java //

package com.cid.login;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.cid.login.DAO.UserAccountDAO;
import com.cid.login.DO.UserAccount;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
   
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
   
    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
   
    public ModelAndView home(
            HttpSession hsession) {
        ModelAndView mav = new ModelAndView();
       
        String userId = (String) hsession.getAttribute("user_id");
        if(userId == null) {
            mav.setViewName("login");
        }
        else {
            mav.setViewName("home");
            mav.addObject("user_id", userId);
        }
        return mav;
    }
   
   
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public ModelAndView login(
            @RequestParam(value="user_id", defaultValue="")String userId,
            @RequestParam(value="user_password", defaultValue="")String userPassword,
            HttpSession hsession) {
        ModelAndView mav = new ModelAndView();
       
        UserAccountDAO userAccountDAO = new UserAccountDAO();
       
        System.out.println("UserID : <" + userId +">");
       
        UserAccount userAccount = userAccountDAO.getuserAccount(userId);
               
        if(userAccount == null) {
            mav.addObject("code", 1); //아이디없음
            mav.setViewName("login_alert");
            System.out.println("null 반환됨");
        } else {
            if(userPassword.equals(userAccount.getUserPassword())== true) {
                mav.addObject("code", 0); //비밀번호 확인
                mav.setViewName("home");
                mav.addObject("user_id", userId);
            }else {
                mav.addObject("code",2); //비밀번호 다름
                mav.setViewName("passworderror");
            }
        }
        return mav;
    }

       
   
       
       
    /*    if(userId.equals("admin")==true && userPassword.equals("1234")==true) {
            hsession.setAttribute("user_id", userId);
            mav.addObject("user_id");
            mav.setViewName("home");
        }
        else {
            hsession.removeAttribute("user_id");
            mav.setViewName("login_alert");
        }
        return mav;
    }
    */
    @RequestMapping(value = "/logout.do", method = RequestMethod.GET)
    public ModelAndView logout(
            HttpSession hsession) {
        ModelAndView mav = new ModelAndView ();
       
        String userId = (String) hsession.getAttribute("user_id");
            if(userId == null) {
                mav.setViewName("login");
            }
            else {
                mav.setViewName("logout");
                mav.addObject("user_id",userId);
               
                hsession.removeAttribute("user_id");
            }
            return mav;
    }
   
   
   
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
       
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
       
        String formattedDate = dateFormat.format(date);
       
        model.addAttribute("serverTime", formattedDate );
       
        return "home";
    }
   
}
---------------------------------------------------------------------
home.jsp//
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Home</title>
</head>
<body>
    <center>
            <h1>로그인</h1>
            <p> ${user_id} 님 접속을 환영합니다 .</p>   
            <button type="button" onclick="location.href='/login/logout.do' ">로그아웃</button>
    </center>
</body>
</html>
--------------------------------------------------------------
login_alert.jsp //
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login Fail</title>
</head>
<body>
<script>
    alert('아이디가 없거나 틀렸습니다.');
    history.back();
</script>
</body>
</html>
--------------------------------------------------------------------------------
login.jsp //
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
    <form method ="POST" action ="/login/login.do">
      <table>
        <tbody>
        <tr>
            <td>아이디</td> <td><input type="text" name="user_id" /></td>
        </tr>
        <tr>
            <td>비밀번호</td> <td><input type="password" name ="user_password" /></td>
        </tr>
        </tbody>
      </table>
      <input type ="submit" value ="로그인" />
    </form>
    </center>
</body>
</html>
------------------------------------------------------------------------
logout.jsp //
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>log out</title>
</head>
<body>
<center>
    <p> ${user_id} 로그아웃 되셨습니다. </p>
    <button type="button" onclick="location.href='/login' ">홈으로</button>
</center>
</body>
</html>
------------------------------------------------------------------------
passworderror.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login Fail</title>
</head>
<body>
<script>
    alert('비밀번호가 틀림');
    history.back();
</script>
</body>
</html>
------------------------------------------------------------------------
Share:

0 개의 댓글:

댓글 쓰기

Scroll To Top