JSP|DB:会員登録と会員情報修正プログラミング

58539 ワード

  • M(model): DB- Servlet
  • V(view): JSP HTML
  • C(Controller):連結ビュー
  • 作成順序


    1. join.html(view,con) + DB



    1. join.htmlの作成
    2.1ベースのSQL文の作成

    joinOk Servlet(Model-DB)



    logIn.html(view,con)



    LogInOk Servlet(Model-DB)

  • logIn.
  • DBアクセス
  • メンバー表アクセス
  • 受信IDが
  • 存在するかどうか
  • パスワードが
  • に一致するかどうか
    package com.javalec.ex;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.Arrays;
    
    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;
    
    /**
     * Servlet implementation class LogInOk
     */
    @WebServlet("/LogInOk")
    public class LogInOk extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	private Connection connection;
    	private Statement stmt;
    	private ResultSet resultSet;
    
    	private String name, id, pw, phone1, phone2, phone3, gender;
    
    	/**
    	 * @see HttpServlet#HttpServlet()
    	 */
    	public LogInOk() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    	 *      response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		actionDo(request, response);
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    	 *      response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		actionDo(request, response);
    	}
    
    	private void actionDo(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    		id = request.getParameter("id");
    		pw = request.getParameter("pw");
    		
            //2. Member 테이블 접근
            //3. 받은 아이디가 존재하는 지 아닌지
    		//4. 비밀번호가 일치하는지 아닌지
    		String query = "select * from member where id = '" + id + "' and pw = '" + pw + "'";
    
    		try {
            	//1. DB 접근
    			Class.forName("oracle.jdbc.driver.OracleDriver");
    			connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "scott", "tiger");
    			stmt = connection.createStatement();
    			resultSet = stmt.executeQuery(query);
    
    			// resultSet객체로 반환한 쿼리 실행문 결과 데이터가 있다면: true
    			while (resultSet.next()) {
    				name = resultSet.getString("name");
    				id = resultSet.getString("id");
    				pw = resultSet.getString("pw");
    				phone1 = resultSet.getString("phone1");
    				phone2 = resultSet.getString("phone2");
    				phone3 = resultSet.getString("phone3");
    				gender = resultSet.getString("gender");
    			}
    
    			/*
    			 * 브라우저 하나당 하나의 세션 존재 
    			 * name 값에 name 입력 
    			 * id, id 
    			 * pw, pw
    			 */
    
    			HttpSession httpSession = request.getSession();
    			httpSession.setAttribute("name", name);
    			httpSession.setAttribute("id", id);
    			httpSession.setAttribute("pw", pw);
    
    			response.sendRedirect("loginResult.jsp");
    
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				if (resultSet != null)
    					resultSet.close();
    				if (stmt != null)
    					stmt.close();
    				if (connection != null)
    					connection.close();
    			} catch (Exception e2) {
    				e2.printStackTrace();
    			}
    		}
    
    	}
    
    }
    
    情報処理:SQLから戻る
    出力:Java

    modify.jsp(view,con)

    <%@page import="java.sql.DriverManager"%>
    <%@page import="java.sql.ResultSet"%>
    <%@page import="java.sql.Statement"%>
    <%@page import="java.sql.Connection"%>
    <%@ page language="java" contentType="text/html; charset=EUC-KR"
        pageEncoding="EUC-KR"%>
        
        <%!
        	Connection connection;
        	Statement statement;
        	ResultSet resultSet;
        
        	String name, id, pw, phone1, phone2, phone3, gender;
        %>
    <!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=EUC-KR">
    <title>Insert title here</title>
    </head>
    <body>
    	
    	<%
    		// 로그인 후 session에 살아있는 아이디 값을 가져옴
    		id = (String)session.getAttribute("id");
    	
    		// ID 정보로 멤버 테이블 접근
    		String query = "select * from member where id = '" + id + "'";
    		
    		//DB 연결
    		Class.forName("oracle.jdbc.driver.OracleDriver");
    		connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe" , "scott" , "tiger");
    		statement = connection.createStatement();
    		resultSet =  statement.executeQuery(query);
    		
    		while(resultSet.next()) {
    			name = resultSet.getString("name");
    			pw = resultSet.getString("pw");
    			phone1 = resultSet.getString("phone1");
    			phone2 = resultSet.getString("phone2");
    			phone3 = resultSet.getString("phone3");
    			gender = resultSet.getString("gender");
    		}
    		
    	%>
    	
    	<!-- 회원가입과 같이 정보 입력, ModifyOk로 정보 post -->
    	<form action="ModifyOk" method="post">
    		이름 : <input type="text" name="name" size="10" value=<%=name %>><br />
    		아이디 : <%=id %><br />
    		비밀번호 : <input type="text" name="pw" size="10"><br />
    		전화번호 : <select name="phone1">
    			<option value="010">010</option>
    			<option value="016">016</option>
    			<option value="017">017</option>
    			<option value="018">018</option>
    			<option value="019">019</option>
    			<option value="011">011</option>
    		</select> - 
    		<input type="text" name="phone2" size="5" value=<%=phone2 %>> - <input type="text" name="phone3" size="5" value=<%=phone3 %>> <br />
    		<%
    			if(gender.equals("man")) {
    		%>
    		성별구분 : <input type="radio" name="gender" value="man" checked="checked">&nbsp;<input type="radio" name="gender" value="woman"><br />
    		<%
    			} else {
    		%>
    		성별구분 : <input type="radio" name="gender" value="man" >&nbsp;<input type="radio" name="gender" value="woman" checked="checked"><br />
    		<%
    			}
    		%>
    		<input type="submit" value="정보수정"> <input type="reset" value="취소">
    	</form>
    
    </body>
    </html>

    ModifyOk Servlet(Model-DB)

    package com.javalec.ex;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    
    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;
    
    /**
     * Servlet implementation class ModifyOk
     */
    @WebServlet("/ModifyOk")
    public class ModifyOk extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        
    	private Connection connection;
    	private Statement stmt;
    	
    	private String name, id, pw, phone1, phone2, phone3, gender;
    	
    	HttpSession httpSession;
        /**
         * @see HttpServlet#HttpServlet()
         */
        public ModifyOk() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		actionDo(request, response);
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		actionDo(request, response);
    	}
    	
    	private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    		request.setCharacterEncoding("EUC-KR");
    		// session 가져오기
    		httpSession = request.getSession();
    		
    		// 세션에 있던 값
    		name = request.getParameter("name");
    		id = request.getParameter("id");
    		pw = request.getParameter("pw");
    		phone1 = request.getParameter("phone1");
    		phone2 = request.getParameter("phone2");
    		phone3 = request.getParameter("phone3");
    		gender = request.getParameter("gender");
    		
    		//세션의 비번값과 입력된 비번값이 일치
    		if(pwConfirm()){
    			System.out.println("OK");
    			
    			//DB에서 값 업데이트
    			String query = "update member set name ='" + name + "', phone1= '" + phone1 + "', phone2 = '" + phone2 + "', phone3 = '" + phone3 + "', gender = '" + gender + "'";
    //			System.out.println(query);
    			
    			try {
    				Class.forName("oracle.jdbc.driver.OracleDriver");
    				connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe" , "scott" , "tiger");
    				stmt = connection.createStatement();
    				int i = stmt.executeUpdate(query);
    				
    				//쿼리 실행결과가 1 이면 true
    				if(i ==1 ){
    					System.out.println("update success");
    					httpSession.setAttribute("name", name);
    					response.sendRedirect("modifyResult.jsp");
    					
    					//실행된 쿼리가 없으면
    				} else {
    					System.out.println("update fail");
    					response.sendRedirect("modify.jsp");
    				}
    				
    			} catch(Exception e) {
    				e.printStackTrace();
    			} finally {
    				try {
    					if(stmt != null) stmt.close();
    					if(connection != null) connection.close();
    				} catch (Exception e) {}
    			}
    			
    		} else {
    			System.out.println("NG");
    		}
    		
    	}
    	
    	private boolean pwConfirm() {
    		boolean rs = false;
    		
    		//Obj인 세션값 형변환, session에서 pw가져오기
    		String sessionPw =  (String)httpSession.getAttribute("pw");
    		
    		
    		//session에서 가져온 pw가 일치하면 참 
    		if(sessionPw.equals(pw)) {
    			rs = true;
    		} else {
    			rs = false;
    		}
    		
    		return rs;
    	}
    
    }