JSP

 세션의 유효 시간  

 

web.xml

  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>
  <error-page>

 

 


<%
//세션의 유효시간 변경(초 단위)
//session.setMaxInactiveInterval(600);
int timeout=session.getMaxInactiveInterval();
out.println("세션의 유효시간 : " + timeout);
%>

 

 세션 로그인 로그아웃 처리  

 

SQL

CREATE TABLE MEMBER
(
   USERID      VARCHAR2 (50),
   PASSWD      VARCHAR2 (64),
   NAME        VARCHAR2 (50),
   EMAIL       VARCHAR2 (50),
   HP          VARCHAR2 (50),
   ZIPCODE     VARCHAR2 (7),
   ADDRESS1    VARCHAR2 (200),
   ADDRESS2    VARCHAR2 (200),
   JOIN_DATE   DATE DEFAULT SYSDATE
)

 

context.xml

    
        <Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource"
              driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:xe"
              username="java" password="1111" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/>
              

 

class DB

package config;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DB {

	public static Connection getConn(){
		
		DataSource ds =null;//javax.sql.DataSource
		Connection conn=null;
		try{
			//context.xml 파일을 분석하는 객체
			Context context = new InitialContext();
// context.xml 파일의 Resource 태그의 name 속성 검색	
// java:comp/env/리소스태그의name			
			ds=(DataSource)context.lookup("java:comp/env/jdbc/myoracle");
// 커넥션풀에서 커넥션을 리턴받음			
			conn=ds.getConnection(); 
		}catch(Exception e){
			e.printStackTrace();
		}
		return conn;
	}
	
	
	public static void closed(Connection conn, PreparedStatement pstmt){

		try{
			if(pstmt!=null)pstmt.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try{
			if(conn!=null)conn.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	
	
    public static void closed(Connection conn, PreparedStatement pstmt, ResultSet rs){
    	try{
			if(rs!=null)rs.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try{
			if(pstmt!=null)pstmt.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try{
			if(conn!=null)conn.close();
		}catch(Exception e){
			e.printStackTrace();
		}
    	
		
	}
	
	
}

 

 

 SHA-256 암호화

 

JHCipher 

package crypt;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import static org.hamcrest.CoreMatchers.is; 
import static org.junit.Assert.assertThat; 


public class JHCipher {

	
	
	public void base64() throws Exception {
		String str = "password";
		String encStr = Base64.encodeBase64String(str.getBytes());
		String decStr = new String(Base64.decodeBase64(encStr));
		
		System.out.println("값 : " + str);
		System.out.println("Base64 Encode : " + encStr);
		System.out.println("Base64 Decode : " + decStr);
	}
	
	
	
	public void md5() throws Exception {
		String str = "password";
		
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes()); 
		byte byteData[] = md.digest();
		StringBuffer sb = new StringBuffer();
		for(int i = 0 ; i < byteData.length ; i++){
			sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
		}
		System.out.println("값 : " + str);
		System.out.println("MD5 : " + sb.toString());
	}
	
	
	
	public static String sha256(String passwordText) throws Exception {
		String str = passwordText;
		StringBuffer sb = new StringBuffer(); 
		try{
			MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
			sha256.update(str.getBytes()); 
			byte byteData[] = sha256.digest();
			
			for(int i = 0 ; i < byteData.length ; i++){
				sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
			}		
		}catch(Exception e){
			e.printStackTrace();
		}	
//		System.out.println("값 : " + str);
//		System.out.println("SHA-256 : " + sb.toString());
//		
		//password == 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
//		if(sb.toString().equals("5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8")){
//			System.out.println("일치");
//		}else{
//			System.out.println("불일치");
//		}
//		
		return sb.toString();
	}
	
	
	
	public static String sha512(String passwordText) {
		StringBuffer sb = new StringBuffer();
		String str = passwordText;
		try{
			MessageDigest sha256 = MessageDigest.getInstance("SHA-512");
			sha256.update(str.getBytes()); 
			byte byteData[] = sha256.digest();
			 
			for(int i = 0 ; i < byteData.length ; i++){
				sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));	
			}
		}catch(Exception e){
			e.printStackTrace();
		}

//		System.out.println("값 : " + str);
//		System.out.println("SHA-256 : " + sb.toString());
		
		return sb.toString();
	}
	
	
	
	public void DES() throws Exception {
		Key key = generateKey("DES", ByteUtils.toBytes("68616e6765656e61", 16));

		String transformation = "DES/ECB/NoPadding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		String str = "korea123";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));

	}
	
	
	
	
	public void DESPadding() throws Exception {
		Key key = generateKey("DES", ByteUtils.toBytes("68616e6765656e61", 16));

		String transformation = "DES/ECB/PKCS5Padding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		String str = "korea";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	

	
	public void DESede() throws Exception {
		Key key = generateKey("DESede", ByteUtils.toBytes("696d697373796f7568616e6765656e61696d697373796f75", 16));

		String transformation = "DESede/ECB/PKCS5Padding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		String str = "hello123";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	
	
	public void AES() throws Exception {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));

		String transformation = "AES/ECB/PKCS5Padding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		String str = "hello123";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	
	
	public void AES_CBC() throws Exception {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
		
		String str = "hello123";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	

	
	public void AESFile() throws Exception {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));
		String transformation = "AES/ECB/PKCS5Padding";

		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);

		File plainFile = new File("c:/plain.txt");
		File encryptFile = new File("c:/encrypt.txt");
		File decryptFile = new File("c:/decrypt.txt");
		
		BufferedInputStream input = null;
		BufferedOutputStream output = null;
		try {
			input = new BufferedInputStream(new FileInputStream(plainFile));
			output = new BufferedOutputStream(new FileOutputStream(encryptFile));
			
			int read = 0;
			byte[] inBuf = new byte[1024];
			byte[] outBuf = null;
			while ((read = input.read(inBuf)) != -1) {
				outBuf = cipher.update(inBuf, 0, read);
				if (outBuf != null) {
					output.write(outBuf);
				}
			}
			outBuf = cipher.doFinal();
			if (outBuf != null) {
				output.write(outBuf);
			}
		} finally {
			if (output != null) try {output.close();} catch(IOException ie) {}
			if (input != null) try {input.close();} catch(IOException ie) {}
		}
				
		cipher.init(Cipher.DECRYPT_MODE, key);
		try {
			input = new BufferedInputStream(new FileInputStream(encryptFile));
			output = new BufferedOutputStream(new FileOutputStream(decryptFile));
			
			int read = 0;
			byte[] inBuf = new byte[1024];
			byte[] outBuf = null;
			while ((read = input.read(inBuf)) != -1) {
				outBuf = cipher.update(inBuf, 0, read);
				if (outBuf != null) {
					output.write(outBuf);
				}
			}
			outBuf = cipher.doFinal();
			if (outBuf != null) {
				output.write(outBuf);
			}
		} finally {
			if (output != null) try {output.close();} catch(IOException ie) {}
			if (input != null) try {input.close();} catch(IOException ie) {}
		}
	}
	
	
	
	public void password() throws Exception {
		String password = "mypassword";
		
		byte[] passwordBytes = password.getBytes();
		int len = passwordBytes.length;
		byte[] keyBytes = new byte[16];
		if (len >= 16) {
			System.arraycopy(passwordBytes, 0, keyBytes, 0, 16);
		} else {
			System.arraycopy(passwordBytes, 0, keyBytes, 0, len);
			for (int i = 0; i < (16 - len); i++) {
				keyBytes[len + i] = passwordBytes[i % len];
			}
		}
		
		Key key = generateKey("AES", keyBytes);
		String transformation = "AES/ECB/PKCS5Padding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		byte[] plain = password.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	
	/**
	 * 관리자가 지정한 키로 암호화/복호화 한다.
	 * 
	 * @throws Exception
	 */
	
	public void passwordStr() throws Exception {
		String pasword = "mypassword";
		
		String encrypt = AESEncode(pasword);
		String decrypt = AESDecode(encrypt);
		
		System.out.println("원문 : " + pasword);
		System.out.println("암호 : " + encrypt);
		System.out.println("복호 : " + decrypt);
		
		assertThat(pasword, is(decrypt));
	}
	
	
	/**
	 * 비밀번호 자체를 키로 암호화/복호화 사용한다.
	 * 본인이 아니면 알 수 없으므로 보안에 좋음.
	 * 
	 * @throws Exception
	 */
	
	public void passwordStr2() throws Exception {
		String password = "mypassword";
		
		String encrypt = AESEncode2(password);
		String decrypt = AESDecode2(encrypt, password);
		
		System.out.println("원문 : " + password);
		System.out.println("암호 : " + encrypt);
		System.out.println("복호 : " + decrypt);
		
		assertThat(password, is(decrypt));
	}
	
	
	
	/**
	 * 해당 알고리즘에 사용할 비밀키(SecretKey)를 생성한다.
	 * 
	 * @param algorithm
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	private static Key generateKey(String algorithm) throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
		SecretKey secretKey = keyGenerator.generateKey();
		return secretKey;
	}
	
	/**
	 * 주어진 데이터로, 해당 알고리즘에 사용할 비밀키(SecretKey)를 생성한다.
	 * 
	 * @param algorithm
	 * @param keyData
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 * @throws InvalidKeySpecException
	 */
	public static Key generateKey(String algorithm, byte[] keyData) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
		if ("DES".equals(algorithm)) {
			KeySpec keySpec = new DESKeySpec(keyData);
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
			return secretKey;
		} else if ("DESede".equals(algorithm) || "TripleDES".equals(algorithm)) {
			KeySpec keySpec = new DESedeKeySpec(keyData);
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
			return secretKey;
		} else {
			SecretKeySpec keySpec = new SecretKeySpec(keyData, algorithm);
			return keySpec;
		}
		/*
		String upper = algorithm.toUpperCase();
		if ("DES".equals(upper)) {
			KeySpec keySpec = new DESKeySpec(keyData);
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
			return secretKey;
		} else if ("DESede".equals(upper) || "TripleDES".equals(upper)) {
			KeySpec keySpec = new DESedeKeySpec(keyData);
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
			return secretKey;
		} else {
			SecretKeySpec keySpec = new SecretKeySpec(keyData, algorithm);
			return keySpec;
		}
		*/
	}
	
	
	public static String AESEncode(String str) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
		
		byte[] encrypt = cipher.doFinal(str.getBytes("UTF-8"));
		String encryptStr = new String(Base64.encodeBase64(encrypt));
		return encryptStr;
	}
	
	public static String AESEncode2(String str) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		byte[] strBytes = str.getBytes();
		int len = strBytes.length;
		byte[] keyBytes = new byte[16];
		if (len >= 16) {
			System.arraycopy(strBytes, 0, keyBytes, 0, 16);
		} else {
			System.arraycopy(strBytes, 0, keyBytes, 0, len);
			for (int i = 0; i < (16 - len); i++) {
				keyBytes[len + i] = strBytes[i % len];
			}
		}
		
		
		Key key = generateKey("AES", keyBytes);
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
		
		byte[] encrypt = cipher.doFinal(str.getBytes("UTF-8"));
		String encryptStr = new String(Base64.encodeBase64(encrypt));
		return encryptStr;
	}
	
	
	public static String AESDecode(String str) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
		
		byte[] encrypt = Base64.decodeBase64(str.getBytes());
		byte[] decrypt = cipher.doFinal(encrypt);
		String decryptStr = new String(decrypt, "UTF-8");
		return decryptStr;
	}
	
	
	public static String AESDecode2(String encryptStr, String str) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		byte[] strBytes = str.getBytes();
		int len = strBytes.length;
		byte[] keyBytes = new byte[16];
		if (len >= 16) {
			System.arraycopy(strBytes, 0, keyBytes, 0, 16);
		} else {
			System.arraycopy(strBytes, 0, keyBytes, 0, len);
			for (int i = 0; i < (16 - len); i++) {
				keyBytes[len + i] = strBytes[i % len];
			}
		}
		
		Key key = generateKey("AES", keyBytes);
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
		
		byte[] encrypt = Base64.decodeBase64(encryptStr.getBytes());
		byte[] decrypt = cipher.doFinal(encrypt);
		String decryptStr = new String(decrypt, "UTF-8");
		return decryptStr;
	}
	
}

 

 class MemberDAO

	public int insertSha256(MemberDTO dto){
		int rows=0;
		Connection conn=null;
		PreparedStatement pstmt =null;
		try{
			String sql ="insert into member (USERID, PASSWD, NAME) " 
					+ " VALUES ( ?,  ?, ?) ";
			conn=DB.getConn();
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, dto.getUserid());
			
			//SHA-256암호화 적용
			pstmt.setString(2, JHCipher.sha256(dto.getPasswd()));
			pstmt.setString(3, dto.getName());
			//insert 실행 후 성공한 레코드 갯수
			//affected rows(영향을 받은 행)
			rows=pstmt.executeUpdate();
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{

			DB.closed(conn, pstmt);
		}
		
		return rows;
	}
	
	public String loginCheckSha256(String userid, String passwd){
		String result=null;
		Connection conn=null;
		PreparedStatement pstmt =null;
		ResultSet rs=null;
		
		try{		
			conn=DB.getConn();//DB 커넥션 리턴
			String sql=" select name from member where USERID=? and passwd=? ";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, userid);//1번 물음표
			pstmt.setString(2, JHCipher.sha256(passwd));//2번 물음표
			rs=pstmt.executeQuery();
			if(rs.next()){//로그인 성공하면 이름을 저장
				result=rs.getString("name");
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DB.closed(conn, pstmt,rs);
		}
		return result;
	}

 

 

class SessionController

 

package member;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/session_servlet/*")
public class SessionController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url=request.getRequestURI().toString();
		MemberDAO dao =new MemberDAO();
		
		
		 if(url.indexOf("join_session.do")!=-1){
				//사용자가 입력한 값
				String userid=request.getParameter("userid");
				String passwd=request.getParameter("passwd");
				String name=request.getParameter("name");
				MemberDTO dto=new MemberDTO();
				dto.setUserid(userid);
				dto.setPasswd(passwd);
				dto.setName(name);
				int rows =dao.insertSha256(dto);
				String message ="";
				if(rows>0){
					message="회원 가입 처리가 완료되었습니다.";
				}else{
					message="회원 가입 처리 과정에서 오류가 발생했습니다.";
				}
				
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out =response.getWriter();
				out.print(message);
			
		}else if(url.indexOf("login.do")!=-1){
			String userid=request.getParameter("userid");
			String passwd=request.getParameter("passwd");


			String result=dao.loginCheckSha256(userid, passwd);
			
			if(result==null){
				result="아이디 또는 비밀번호가 일치하지 않습니다.";
			}else{//로그인 성공
				HttpSession session =request.getSession();
				session.setAttribute("loginUser", result);
				
				result =result+"님 환영합니다.";				
			}	
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out =response.getWriter();
			out.print(result);	
			
		}else if(url.indexOf("logout.do")!=-1){
			//로그아웃 처리	
			//세션 객체 생성
			HttpSession session=request.getSession();
			//세션을 초기화시킴(JSESSIONID 도 재발급됨)
			session.invalidate();
			String page=request.getContextPath()+"/ch12/session_login.jsp?message=logout";
			response.sendRedirect(page);
		}
		
		
	}

	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

 

회원가입

아이디 : 
비밀번호 : 
이름 : 
회원가입 로그인현재 로그인 유저 :

 

 

 

 

 

아이디  
비밀번호  로그인
회원가입

 

 

 

 

 

메인 페이지

홍길동 님이 접속 중입니다. 
로그아웃

 

 

 

 

 

 

 

 

join_session.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ include file="../include/header.jsp" %>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
	$("#btnJoin").click(function(){
		var userid=$("#userid");
		var passwd=$("#passwd");
		var name=$("#name");
		$.ajax({
			type:"post",
			url:"${path}/session_servlet/join_session.do",
			data:{
				userid:userid.val(),
				passwd:passwd.val(),
				name:name.val()
			},
			success:function(result){
				$("#result").html(result);
				
				userid.val("");
				passwd.val("");
				name.val("");
						
			}		
		});
			
	});
	
});

</script>
</head>
<body>

<!--  /ch092/join_oracle.jsp -->

<h2>회원가입</h2>
아이디 : <input id="userid"><br>
비밀번호 : <input type="password" id="passwd"><br>
이름 : <input id="name"><br>
<button id="btnJoin">회원가입</button> 
<a href="${path }/ch12/session_login.jsp">로그인</a>
<div id="result"></div>



현재 로그인 유저 :
${loginUser }


</body>
</html>


 

 

session_login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ include file="../include/header.jsp" %>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
	$("#btnLogin").click(function(){
		var userid=$("#userid").val();
		var passwd=$("#passwd").val();
		$.ajax({
			type:"post",
			url:"${path}/session_servlet/login.do",
			data:{
				userid:userid,
				passwd:passwd
			},
			success:function(result){
				loginSuccess(result);
					
			}
		});
				
		
	});
	
	
});


function loginSuccess(result){
	
	if(result.search("님 환영합니다.")>0){
		location.href="${path}/ch12/main.jsp";
		
	}else{
		$("#result").html(result);	
	}
	
}

</script>
</head>
<body>

아이디 <input id="userid"> <br>
비밀번호 <input type="password" id="passwd">
<button id="btnLogin">로그인</button>
<div id="result"></div>


<br>
<a href="${path }/ch12/join_session.jsp">회원가입</a>

<c:if test="${param.message =='logout' }">
	<div style="color:blue">
	로그아웃되었습니다.
	</div>
</c:if>


</body>
</html>

 

session_check.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!--  JSTL(Jsp Standard Tag Library) -->    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${sessionScope.loginUser==null }" >
<script>
 alert("로그인하신 후 사용하세요.");
 location.href="${path}/ch12/session_login.jsp";
</script>
</c:if>

 

 

 

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ include file="../include/header.jsp" %>
<%@ include file="session_check.jsp" %>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
	 $("#btnLogout").click(function(){
		
		 location.href="${path}/session_servlet/logout.do";
	 });
	
});
</script>
</head>
<body>

<h2>메인 페이지</h2>

${sessionScope.loginUser } 님이 접속 중입니다.
<br>

<button type="button" id="btnLogout">로그아웃</button>

</body>
</html>


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

완벽함이 아닌 탁월함을 위해 노력하라.

댓글 ( 4)

댓글 남기기

작성