・조건연산자가 특이하므로 주목하도록 한다. ${(1>2)?1:2} -> 1>2가 참이면1, 거짓이면 2







































































・expression language는 객체에 값설정은 불가능하고, 설정된 값들을 가져오는 기능만을 할 수 있는 것 같다.


























・노드js 의 경우에는 외부 모듈이 npm install을 통해 node_modules 폴더에 쌓인다. 일반적으로 자바에서는 어디에 외부 모듈을 저장하는 건지 궁금했는데 WEB-INF안에 저장한다.


・eclipse에서 build path를 보면 알겠지만, eclipse의 web프로젝트는 톰캣의 jar들을 포함한다. 따라서, tomcat 내부에도 내가 실행한 프로젝트 패스들이 생성되어 있다.(C:\apache_tomcat\apache-tomcat-8.5.23\wtpwebapps\helloworld)







・이클립스에서 웹프로젝트를 위한 파일을 구성하면, WebContent에 html,jsp 등의 파일을 구성하는데, WebContent직하에 MultipartRequest모듈 실행시 업로드된 파일이 담기게될 디렉토리 패스를 만들어 놓는다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <form action="22fileUpload.jsp" method="post" enctype="multipart/form-data">
        파일 : <input type="file" name="file">
        <input type="submit" value="file uplaod">
    </form>
 
</body>
</html>
cs

・클라이언트 단에서 MultipartRequest을 사용하기 위해선, enctype="multipart/form-data">을 적어주는 것이 필수적이다.

또한 <input type="file" 을 명기하여 file업로드를 위한 input태그임을 알린다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import ="java.util.*"%>
<%@ page import ="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import ="com.oreilly.servlet.MultipartRequest" %>
<!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>
 
<%
    String path = request.getRealPath("uploadedFiles");
    System.out.println(path);
    int size = 1024 * 1024 * 10;
    String file="";
    String oriFile="";
 
    try{
        MultipartRequest multi = new MultipartRequest(request,path,size,"EUC-KR",new DefaultFileRenamePolicy());
        
        Enumeration files = multi.getFileNames();
        String str =(String)files.nextElement();
 
        file = multi.getFilesystemName(str);
        oriFile = multi.getOriginalFileName(str);
        
        System.out.println(file);
        System.out.println(oriFile);
    }
    catch(Exception e){
        e.printStackTrace();
    }
 
 
%>
 
upload success!!
 
<a href="22fileUpload.html">돌아가기</a>
 
</body>
</html>
cs

MultipartRequest multi = new MultipartRequest(request,path,size,"EUC-KR",new DefaultFileRenamePolicy());

로 파일 업로딩은 끝이 난다.

multi.getOriginalFileName(str);은 유저가 업로드한 파일명을 그대로 얻어오는 함수이다.

multi.getFilesystemName(str);은 MultipartRequest모듈 내ㅣ부에서 업로드한 파일명을 얻어오는 함수이다. 

getFilesystemName는 유저가 같은명의 파일을 업로드시 MultipartRequest모듈은 내부로직으로 겹치는 파일명을 수정해주는데, 이 수정된 파일명을 얻어온다.

Express에서 정적 파일 제공

이미지, CSS 파일 및 JavaScript 파일과 같은 정적 파일을 제공하려면 Express의 기본 제공 미들웨어 함수인 express.static을 사용하십시오.

정적 자산이 포함된 디렉토리의 이름을 express.static 미들웨어 함수에 전달하면 파일의 직접적인 제공을 시작할 수 있습니다. 예를 들면, 다음과 같은 코드를 이용하여 public이라는 이름의 디렉토리에 포함된 이미지, CSS 파일 및 JavaScript 파일을 제공하십시오.


app.use(express.static('public'));

이제 다음과 같이 public 디렉토리에 포함된 파일을 로드할 수 있습니다.


http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

Express는 정적 디렉토리에 대해 상대적으로 파일을 검색하며, 따라서 정적 디렉토리의 이름은 URL의 일부가 아닙니다.

여러 개의 정적 자산 디렉토리를 이용하려면 다음과 같이 express.static 미들웨어 함수를 여러 번 호출하십시오.


app.use(express.static('public'));
app.use(express.static('files'));

Express는 express.static 미들웨어 함수를 이용해 정적 디렉토리를 설정한 순서대로 파일을 검색합니다.

express.static 함수를 통해 제공되는 파일에 대한 가상 경로 접두부(파일 시스템 내에 해당 경로가 실제로 존재하지 않는 경우)를 작성하려면, 아래에 표시된 것과 같이 정적 디렉토리에 대한 마운트 경로를 지정하십시오.


app.use('/static', express.static('public'));

이제 /static 경로 접두부를 통해 public 디렉토리에 포함된 파일을 로드할 수 있습니다.


http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

그러나 express.static 함수에 제공되는 경로는 node 프로세스가 실행되는 디렉토리에 대해 상대적입니다. Express 앱을 다른 디렉토리에서 실행하는 경우에는 다음과 같이 제공하기 원하는 디렉토리의 절대 경로를 사용하는 것이 더 안전합니다.


app.use('/static', express.static(__dirname + '/public'));












-DTO : 데이터 접속에 필요한 변수와 데이터를 일반적인 변수에 할당하지 않고 DTO 클래스를 통해서 일괄 관리하는 것







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.javalec.daotoex;
 
public class MemberDTO {
 
    private String name;
    private String id;
    private String pw;
    private String phone1;
    private String phone2;
    private String phone3;
    private String gender;
    
    public MemberDTO(String name, String id, String pw, String phone1, String phone2, String phone3, String gender) {
        this.name = name;
        this.id = id;
        this.pw = pw;
        this.phone1 = phone1;
        this.phone2 = phone2;
        this.phone3 = phone3;
        this.gender = gender;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getPw() {
        return pw;
    }
 
    public void setPw(String pw) {
        this.pw = pw;
    }
 
    public String getPhone1() {
        return phone1;
    }
 
    public void setPhone1(String phone1) {
        this.phone1 = phone1;
    }
 
    public String getPhone2() {
        return phone2;
    }
 
    public void setPhone2(String phone2) {
        this.phone2 = phone2;
    }
 
    public String getPhone3() {
        return phone3;
    }
 
    public void setPhone3(String phone3) {
        this.phone3 = phone3;
    }
 
    public String getGender() {
        return gender;
    }
 
    public void setGender(String gender) {
        this.gender = gender;
    }
    
}
 
cs









1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.javalec.daotoex;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
 
public class MemberDAO {
 
    private String url = "jdbc:oracle:thin:@localhost:1521:xe";
    private String uid = "scott";
    private String upw = "tiger";
    
    
    public MemberDAO() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public ArrayList<MemberDTO> memberSelect() {
        
        ArrayList<MemberDTO> dtos = new ArrayList<MemberDTO>();
        
        Connection con =null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            con = DriverManager.getConnection(url, uid, upw);
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from member");
            
            while (rs.next()) {
                String name = rs.getString("name");
                String id = rs.getString("id");
                String pw = rs.getString("pw");
                String phone1 = rs.getString("phone1");
                String phone2 = rs.getString("phone2");
                String phone3 = rs.getString("phone3");
                String gender = rs.getString("gender");
                
                MemberDTO dto = new MemberDTO(name, id, pw, phone1, phone2, phone3, gender);
                dtos.add(dto);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null) rs.close();
                if(stmt != null) stmt.close();
                if(con != null) con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return dtos;
    }
    
}
 
cs










1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<%@page import="com.javalec.daotoex.MemberDTO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.javalec.daotoex.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>
 
    <%
        MemberDAO memberDAO = new MemberDAO();
        ArrayList<MemberDTO> dtos = memberDAO.memberSelect();
        
        for(int i=0; i<dtos.size(); i++) {
            MemberDTO dto = dtos.get(i);
            String name = dto.getName();
            String id = dto.getId();
            String pw = dto.getPw();
            String phone = dto.getPhone1() + " - "+ dto.getPhone2() + " - " + dto.getPhone3();
            String gender = dto.getGender();
            
            out.println("이름 : " + name + ", 아이디 : " + id + ", 비밀번호 : " + pw + ", 연락처 : " + phone + ",  성별 : " + gender + "<br />" );
        }
        
    %>
 
</body>
</html>
cs







-쿼리문을 작성할 때, 쿼리에 변수를 넣는 과정이 귀찮기 때문에 그것을 편리하게 하기 위해 나온 객체


1
2
3
4
5
6
7
String id = "abc"
String pw = "123"
String name = "홍길동"
String phone ="0103323123"
 
String query = "insert into member(id,pw,name,phone) values("'+id+"','"+pw+"','"+name+"','"+phone+"')"
cs





1
2
3
4
5
6
7
8
9
10
String id = "abc"
String pw = "123"
String name = "홍길동"
String phone ="0103323123"
 
String query = "insert into member(id,pw,name,phone) values(?,?,?,?)"
preparedStatement.setString(1,id)
preparedStatement.setString(2,pw)
preparedStatement.setString(3,name)
preparedStatement.setString(4,phone)
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    <%!
        Connection connection;
        PreparedStatement preparedStatement;
        ResultSet resultSet;
    
        String driver = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String uid = "scott";
        String upw = "tiger";
    %>
<!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>
 
    <%
        try{
            
            Class.forName(driver);
            connection = DriverManager.getConnection(url, uid, upw);
            int n;
            String query = "insert into memberforpre (id, pw, name, phone) values (?, ?, ?, ?)";
            preparedStatement = connection.prepareStatement(query);
            
            preparedStatement.setString(1"abc");
            preparedStatement.setString(2"123");
            preparedStatement.setString(3"홍길동");
            preparedStatement.setString(4"010-1234-5678");
            n = preparedStatement.executeUpdate();
            
            preparedStatement.setString(1"def");
            preparedStatement.setString(2"456");
            preparedStatement.setString(3"홍길자");
            preparedStatement.setString(4"010-9012-3456");
            n = preparedStatement.executeUpdate();
            
            preparedStatement.setString(1"ghi");
            preparedStatement.setString(2"789");
            preparedStatement.setString(3"홍길순");
            preparedStatement.setString(4"010-7890-1234");
            n = preparedStatement.executeUpdate();
            
            preparedStatement.setString(1"AAA");
            preparedStatement.setString(2"111");
            preparedStatement.setString(3"이길동");
            preparedStatement.setString(4"010-1234-1111");
            n = preparedStatement.executeUpdate();
            
            if(n == 1) {
                out.println("insert success");
            } else { 
                out.println("insert fail");
            }
            
        } catch(Exception e) {
                e.printStackTrace();
        } finally {
            try{
                if(resultSet != null) resultSet.close();
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch(Exception e){}
        }
    %>
    
    <br />
    <a href="memberDateView.jsp">회원정보 보기</a>
 
</body>
</html>
cs















-동시에 클라이언트로부터 database connection 객체 생성 요청이 들어오와 그때그때 connection객체를 생성하면 데이터 베이스에 부하가 걸리기 때문에, 일단 커넥션풀에 connection객체를 미리 만들어놓고, 클라이언트로부터 요청이 들어오면 하나하나 배당하는 로직

-DBCP는 자바에서 존재하는 것이 아니고 tomcat WAS에 미리 만들어 놓으라고 요청하는 것. 따라서  tomcat컨테이너가  connection을 미리 만들어 놓도록 context.xml에 설정해둔다.
















-context.xml을 수정한 후에는 톰캣에 싱크를 하기 위해서 위 스크린샷의 버튼을 눌러준다.






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.javalec.daotoex;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
public class MemberDAO {

//원래 일반적인 ODBC접속이라면  Class.forName("oracle.jdbc.driver.OracleDriver");로 디비 접속을 하지만, 톰캣커넥션 풀에 이미 //커넥션 객체를 쌓아놓은 경우라면 디비 접속하는 부분은 필요 없어진다.
//아래의 빨간색 폰트들은 커넥션풀을 이용하면서 삭제된 코드들이고, 파랑색 폰트들은 새로 추가된 코드들이다. 
 
//    private String url = "jdbc:oracle:thin:@localhost:1521:xe";
//    private String uid = "scott";
//    private String upw = "tiger";
    
    private DataSource dataSource;
    
    public MemberDAO() {
   

    
//        try {
//            Class.forName("oracle.jdbc.driver.OracleDriver");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        try {
            Context context = new InitialContext(); dataSource = (DataSource)context.lookup("java:comp/env/jdbc/Oracle11g");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public ArrayList<MemberDTO> memberSelect() {
        
        ArrayList<MemberDTO> dtos = new ArrayList<MemberDTO>();
        
        Connection con =null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
//          con = DriverManager.getConnection(url, uid, upw);
            con = dataSource.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from member");
            
            while (rs.next()) {
                String name = rs.getString("name");
                String id = rs.getString("id");
                String pw = rs.getString("pw");
                String phone1 = rs.getString("phone1");
                String phone2 = rs.getString("phone2");
                String phone3 = rs.getString("phone3");
                String gender = rs.getString("gender");
                
                MemberDTO dto = new MemberDTO(name, id, pw, phone1, phone2, phone3, gender);
                dtos.add(dto);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null) rs.close();
                if(stmt != null) stmt.close();
                if(con != null) con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return dtos;
    }
    
}
 
cs










19join.html

19JoinFail.html

19JoinSuccess.html

ProcessJoin19.java

19login.html

19loginFail.html

19loginSuccess.html

19loginSuccess.jsp

19processLogin.jsp

19processLogout.jsp


loginLogic.zip





19join.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <form action="ProcessJoin" method="post">
    이름 : <input type="text" name="name" size="10"><br/>
    아이디 : <input type="text" name="id" size="10"><br/>
    비밀번호 : <input type="password" name="pw" size="10"><br/>
    전화번호 : <select name="ph1">
        <option value="010">010</option>
        <option value="010">011</option>
        <option value="010">019</option>
        <option value="010">017</option>
    </select> -
    <input type="text" name="ph2" size="4"> - <input type="text" name="ph3" size="4"><br/>
    성별 : 남<input type="radio" name="gender" value ="남" size="5">여<input type="radio" name="gender" value ="여" size="5"><br/>
    <input type="submit" value="회원가입"><input type="reset" value="취소">
    
    
    </form>
 
 
</body>
</html>
cs




ProcessJoin19.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class ProcessJoin19
 */
@WebServlet("/ProcessJoin")
public class ProcessJoin19 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    
    private Connection conn;
    private Statement stmt;
    private String query;
    private String driver,url,uId,uPw,name,id,pw,phoneNum,gender;
    
//    String driver = "oracle.jdbc.driver.OracleDriver";
//    String url = "jdbc:oracle:thin:@localhost:1521:xe";
//    String uId ="Java_webApp";
//    String uPw ="kk5dd0ss2";
 
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessJoin19() {
        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");
        driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:@localhost:1521:xe";
        uId ="Java_webApp";
        uPw ="kk5dd0ss2";
        
        name = request.getParameter("name");
        id = request.getParameter("id");
        pw = request.getParameter("pw");
        phoneNum = request.getParameter("ph1"+ "-" +request.getParameter("ph2"+ "-" + request.getParameter("ph3");
        gender = request.getParameter("gender");
        
        query = "insert into member values('"
                +name+"', '"
                +id+"', '"
                +pw+"', '"
                +phoneNum+"', '"
                +gender+"')";
 
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(url, uId, uPw);
            stmt = conn.createStatement();
            int i = stmt.executeUpdate(query);
            if(i==1){
                System.out.println("insert success");
                response.sendRedirect("19JoinSuccess.html");
            }
            else{
                System.out.println("insert fail");
                response.sendRedirect("19JoinFail.html");
            }
            
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("insert fail");
            response.sendRedirect("19JoinFail.html");
            
        }
        finally{
            try{
                if(stmt!=null)stmt.close();
                if(conn!=null)conn.close();
            }
            catch(Exception e){
                e.printStackTrace();
                
            }
        }
    
    }
}
 
cs



19JoinFail.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    회원가입에 실패하셨습니다 다시 작성해주세요.
    <a href="19join.html">
        <h2>돌아가기</h2>
    </a>
</body>
</html>
cs




19JoinSuccess.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    회원가입에 성공했습니다. 로그인 페이지로 이동해주세요.
    <a href="19login.html">
        <h2>로그인 페이지로 이동</h2>
    </a>
</body>
</html>
cs




19login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <form action="19processLogin.jsp" method="post">
        아이디 : <input type="text" name="id" size="10"><br/>
        비밀번호 : <input type="password" name="pw" size="10"><br/>
        <input type="submit" value="로그인"><input type="reset" value="취소">
    </form>
    
    <form action="19join.html" method="get">
        <input type="submit" value="회원가입">
    </form>
    
</body>
</html>
cs




19processLogin.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
 
<%!
    Connection conn;
    Statement stmt;
    ResultSet rSet;
    
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:xe";
    String uId ="Java_webApp";
    String uPw ="kk5dd0ss2";
    String id,pw,query,result;
%>
 
 
<!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>
    
    <!-- Driver load -->
    <%
    
        request.setCharacterEncoding("EUC-KR");
        driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:@localhost:1521:xe";
        uId ="Java_webApp";
        uPw ="kk5dd0ss2";
        
        id = request.getParameter("id");
        pw = request.getParameter("pw");
        
        query = "select pw from member where id='" + id + "'";
        System.out.println(query);
        
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(url, uId, uPw);
            stmt = conn.createStatement();
            rSet = stmt.executeQuery(query);
            
            while(rSet.next()){
                result = rSet.getString("pw");
            }
            
            if(result == null){
                System.out.println("login fail");
                response.sendRedirect("19loginFail.html");
            }
            else{
                System.out.println("pw : "+pw);
                System.out.println("result : "+result);
                if(result.equals(pw)){
                    session.setAttribute("id", id);
                    session.setAttribute("pw", pw);
                    System.out.println("login success");
                    response.sendRedirect("19loginSuccess.jsp");
                }
                else{
                    System.out.println("password is not matched");
                    response.sendRedirect("19loginFail.html");
                }
            }
    
            
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("login fail");
            response.sendRedirect("19loginFail.html");
            
        }
        finally{
            try{
                if(rSet!=null){rSet.close();}
                if(stmt!=null){stmt.close();}
                if(conn!=null){conn.close();}
            }
            catch(Exception e){
                e.printStackTrace();
                
            }
        }
        
        
    
    
    
    
    %>
 
</body>
</html>
cs



 session.setAttribute("id", id);session.setAttribute("pw", pw);

:세션에 로그인 정보를 주고 다른 로그인 페이지에서 유저가 로그인을 한 후 접속하는건지 그렇지 않은지를 세션을 통해 관리한다. 만약.로그인을 성공하지 않고도 login성공화면을 get으로 받으려고 한다면 문제가 되기때문이다.



19loginSuccess.jsp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<!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>
 
    <%
    try{
        Object id = session.getAttribute("id");
        Object pw = session.getAttribute("pw");
        
        out.println(id.toString() + "님 접속을 환영합니다");%>
        <form action="19processLogout.jsp" method="post">
            <input type="submit" value="로그아웃">
        </form>
    <%}
    catch(NullPointerException e){
        e.printStackTrace();
        out.println("올바른 경로로 엑세스해주세요");    
    }
 
 
    %>
 
</body>
</html>
cs


 Object id = session.getAttribute("id");Object pw = session.getAttribute("pw");

:세션을 통해 로그인 정보를 받고, 세션에 있는 로그인 정보와 사용자의 정보가 같을시에만 페이지를 렌더링하는 로직을 취할 수 있을 것이다. 


19processLogout.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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.invalidate();
    %>
    
    logout되었습니다.
</body>
</html>
cs


session.invalidate();

: 세션 객체에 저장되어 있는 세션을 제거한다.







































・각 데이터베이스 컴페니가 JDBC용 API를 제공하기 때문에 그 jar파일만 받으면 됨. 오라클과 같은경우는 자바와 사이가 좋아서(오라클 사가 자바소유) 자바 jar파일 모둠안에 odbc6_g.jar 이 들어있음


・일단 odbc6_g.jar을 받아와야 하는데, 어디있냐..

보통 일반적으로 c직하에 odbc가 설치되었을때의 패스는 C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib이다.

odbc6_g.jar를 복사한다.


・다음은 이클립스를 사용할 것이므로, 이클립스가 어떤 패스로 자바 라이브러리를 참조하는지 알아야함

window - preference - Java - Build path - Classpath Variable로 가서 이클립스가 참조하는 라이브러리를 확인함

패스를 타고들어가면 그 디렉토리가 이클립스에서 라이브러리로 사용하는 jar들을 모두 가지고 있음. 그중에 ext라는 외부 jar을 보관하는 폴더가 있는데 그 안에다가 odbc6_g.jar을 넣으면 된다.




















1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
 
<%!
    Connection conn;
    Statement stmt;
    ResultSet rSet;
    
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:xe";
    String uId ="Java_webApp";
    String uPw ="kk5dd0ss2";
    String id;
 
%>
 
 
<!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>
    
    <!-- Driver load -->
    <%
    
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(url, uId, uPw);
            stmt = conn.createStatement();
            
            request.setCharacterEncoding("EUC-KR");
            id = request.getParameter("id");
            System.out.println(id);
            String query = "select pw from member where id='"+id+"'";
            rSet = stmt.executeQuery(query);
            
            while(rSet.next()){
                String result = rSet.getString("pw");
                
                out.println("검색값 :" + result);
            }
        
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                if(rSet!=null)rSet.close();
                if(stmt!=null)rSet.close();
                if(conn!=null)rSet.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    %>
 
</body>
</html>
cs




Node.js (Express Framework) 앞단에 Nginx 사용하기

InspiredJW 2012.03.17 15:31
본글 출처 : 
http://inspiredjw.com/entry/Nodejs-Express-Framework-앞단에-Nginx-사용하기 [Inspired World]

Node.js의 창시자인 Ryan Dahl에 의하면


 "You just may be hacked when some yet-unknown buffer overflow is discovered. Not that that couldn't happen behind nginx, but somehow having a proxy in front makes me happy". 

"아직 발견되지 않은 버퍼 오버플로우 취약점에 의해서 해킹 당할 수 있습니다. 
Nginx를 앞단에 둠으로써 이런 취약점에 의해서 해킹을 완전히 막아주지는 않지만, 저는 Nginx을 Proxy서버로써 앞단에 두는 것이 좋다고 생각합니다."






좀 의역을 한 부분이 없잖아 있지만, 중요한 포인트는 Nginx를 앞단에 둠으로써 Express가 사용하는 실제 포트를 숨기고 Nginx의 80포트를 통해 Reverse Proxying 을 함으로써 저런 보안 이슈를 방지할수도 있고 Nginx의 우수한 기능 활용할 수 있습니다.

실제 Static File 과 같은 경우에는 Node.js 보다는 Nginx가 훨씬 성능이 뛰어나다고 합니다.




유의 하실 점은 Nginx 1.0.x버전은 HTTP 1.1을 아예 지원하지 않고 (TCP Module 사용 예외)

Nginx 1.1.x버전은 HTTP 1.1을 지원하지만 Websocket은 지원하지 않기 때문에 Socket.IO와 같은 모듈을 사용할 때 Websocket 방식으로 연결을 시도할 경우에는 Nginx를 거쳐서 연결을 시도하지 않고 직접 연결을 하거나 TCP Module을 사용해야 합니다.



그럼 Nginx 를 Reverse Proxy로 설정하는 방법을 알아볼까요?

Ubuntu 11.04 Natty에서 패키지 인스톨로러를 통해 Nginx를 설치한 경우로 설명하겠습니다.

 

1. ngnix 설치

참고로 Ubuntu에서 nginx 설치는 


sudo apt-get update
sudo apt-get install nginx

하시면 됩니다.



2. nginx 설정 파일 작성

먼저 , nginx 설정파일을 만들어 주어야 합니다. nginx설정파일을 아래의 디렉토리에 만들어주도록 합니다. [example]은 설정파일의 이름으로 확장자는 따로 적어주지 않습니다.






sudo nano /etc/nginx/sites-available/[example]

이렇게 사용하고 싶은 이름 (일반적으로 도메인 이름, 여기선 example) Nginx 설정 파일을 열고


server {
    listen 80;
    server_name example.com; #nginx와 도메인 주소를 연결해 주는 역할을 합니다. 외부에서 example.com으로 들어오는 도메인 주소에서 
요청이 들어오면 로컬에서 오픈되어 있는 아래의 " proxy_pass http://127.0.0.1:3000/; " 를 포워딩해줍니다.

    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://127.0.0.1:3000/; # server_name example.com;로 들어온 요청을 nginx가 받아, 로컬에서 오픈되어 있는
"proxy_pass http://127.0.0.1:3000/;"를 포워딩해줍니다.
      proxy_redirect off;
    }

    gzip on;
    gzip_comp_level 2;
    gzip_proxied any;
    gzip_min_length  1000;
    gzip_disable     "MSIE [1-6]\."
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
 }

이렇게 입력 해주고 CTRL + X 를 눌러 빠져나오고 Y를 눌러 파일을 저장합니다.




다음에는 /etc/nginx/sites-available에 만든 nginx설정 파일을 /etc/nginx/sites-enabled/ 직하로 옮겨주는 작업을 합니다.


cd /etc/nginx/sites-enabled/ 
ln -s /etc/nginx/sites-available/example example

이렇게 해주게 되면 방금 만든 Nginx 설정파일이 적용됩니다. 설정을 변경한 이후에는 Nginx를 반드시 재시작 해줘야 변경한 것이 적용이 되므로


sudo /etc/init.d/nginx restart
혹은sudo service nginx reload

를 쉘에서 실행하여 재시작을 합니다.




혹시 아직 만든 Node.js 앱이 없다면

테스트용으로


var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

//express 모듈을 사용하고 있다면, app.listen(3000,'127.0.0.1', function(){ });


위와 같이 입력하고 이름을 app.js로 저장합니다.

쉘에서 

node app.js


이렇게 테스트 앱을 실행해주면



http://localhost:3000으로는 직접 연결해서 Hello World 를 볼 수도 있고

nginx설정 파일에서 적어준 server_name example.com;
http://example.com로도 같은 Hello World를 볼 수 있습니다.


실제 Production 에서는 방화벽에서 3000포트를 허용하지 않고 80포트만 Inbound 해주면 Nginx 를 통해서만 앱에 접근할 수 있게 됩니다.




'frameworks > NodeJs' 카테고리의 다른 글

nodejs 로그인 로직  (0) 2019.03.12
npm 명령어  (0) 2019.01.08
PM2로 Nodejs어플을 서비스 가동시키기  (0) 2018.06.15
forever로 Nodejs어플을 서비스 가동시키기  (0) 2018.06.15
Express에서 정적 파일 제공  (0) 2018.03.21

jsp에서의 자바빈이란? : java파일로 class파일(객체)를 설계해 놓고, jsp에서 필요에 따라 class를 끌어다 쓰는데 이때 class(객체)를 빈이라고 부른다.

<jsp: ~~> 라는 jsp 액션태그를 이용한다.


















・매회 객체의 클래스 이름을 통해 가져오는게 아니라 useBean을 통해서 클래스와 id값을 연결시키고, 이후부터는 id값을 통해 객체의 프로퍼티에 접근한다.



































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.javalec.ex;
 
public class javaBeanTest {
    private String id;
    private String pw;
    private String bank;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPw() {
        return pw;
    }
    public void setPw(String pw) {
        this.pw = pw;
    }
    public String getBank() {
        return bank;
    }
    public void setBank(String bank) {
        this.bank = bank;
    }
}
 
cs





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    
<jsp:useBean id="personalInfo" class="com.javalec.ex.javaBeanTest" scope="page"></jsp:useBean>
<!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>
 
    <jsp:setProperty name="personalInfo" property="id" value="da91love"/>
    <jsp:setProperty name="personalInfo" property="pw" value="123123"/>
    <jsp:setProperty name="personalInfo" property="bank" value="kookmin"/>
    
    id : <jsp:getProperty  name="personalInfo" property="id"/><br/>
    pw : <jsp:getProperty  name="personalInfo" property="pw"/><br/>
    bank : <jsp:getProperty  name="personalInfo" property="bank"/><br/>
    
</body>
</html>
cs


+ Recent posts