Post

반응형

JDBC로 OLACLE 접속


Oracle Database 11g Express Edition 설치 



SQL Plus


  • cmd 창을 열어서 sqlplus system/pass 를 치면 실행된다.
  • pass는 Oracle 설치 시 설정했던 비밀번호 이다.
  • 로그인 : sqlplus <id>/<pass>
  • 일반 계정 생성 : create user <id> identified by <pass>; 
  • 권한 부여 : grant connect, resource to <id>
  • 로그아웃 : exit

오라클 SQL Developer(GUI)



JDBC 사용하기


  • Java프로그램에서 sql문을 사용할 수 있는 Java API
  • DB 프로그램에서 JDBC Driver를 제공해서, 다른 DB를 사용할 때 그냥 연결만 해주면 된다.
  • Oracle 드라이버 사용을 위해 ojdbc6_g.jar 파일 복사. Copy Path에 넣는다.
  • ojdbc6_g.jar Path : C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib
  • Copy Path : C:\Program Files\Java\jdk-11\lib\ext\
  • Eclipse Menu-Window-Preferenes-Java-Build Path-Classpath Variable

JDBC DB연결 예제


<%@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 driver = "oracle.jdbc.driver.OracleDriver"// 드라이버 정보
    String url = "jdbc:oracle:thin:@localhost:1521:xe";       // 어디에 접근할 것인지
    String uid = "scott";                                                  // login id
    String upw = "tiger";                                                  // login user pass
    String query = "select * from member";
    %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content="text/html" charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
out.println("???");
       // db관련 에러가 날 수 있기 때문에 항상 예외 처리를 함
       try{
              Class.forName(driver);
              connection = DriverManager.getConnection(url, uid, upw);      // db에 로그인
              statement = connection.createStatement();
              resultSet = statement.executeQuery(query);
              out.println("query 날리기~~ ");
              while(resultSet.next())
              {
                     out.println("없다?~ ");
                     
                     String id = resultSet.getString("id");
                     String pw = resultSet.getString("pw");
                     String name = resultSet.getString("name");
                     String phone = resultSet.getString("phone");
                     
                     out.println("아이디:"+id+", 비밀번호:"+pw+"이름:"+name+",전화번호:"+phone+"<br />");
              }
       }catch(Exception e)  {
              out.println(e);
       }finally{
              
              // 마치면 접속 종료
              try{
                     if(null != resultSet) resultSet.close();
                     if(null != statement) statement.close();
                     if(null != connection) connection.close();
                     
              }
              catch(Exception e){}
       }
%>
</body>
</html>



oracle.jdbc.driver.OracleDriver 에러 해결


  • JDBC lib가 없어서 발생.
  • ProjectProperties - Java Build Path - Libraries - Add External JARs..
  • ojdbc6_g.jar 파일 선택.








반응형

Post

반응형

JSP 쿠키, Session, 예외 페이지, 자바빈


JSP 쿠키


  • client <-> server 은 request, respone 후 연결을 끊는다.(http의 특징)
  • 연결이 끊겼을 때 어떤 정보를 유지하기 위해서 쿠키 사용.
  • 예를들어 로그인 후 다른 페이지로 이동하면, 로그인 정보를 가지고 있어야 한다. 이 때 쿠키를 사용.
  • 서버에서 쿠키를 생성한 후 클라이언트가 쿠키 정보를 저장.
  • 쿠키는 보안상의 문제가 있기 때문에(text파일로 id, pass 저장) 점점 사용하지 않음.

JSP 쿠키 함수


  • setMaxAge() : 쿠키 저장시간 설정(초단위)
  • setPath() : 쿠키 유효 디렉터리 설정(잘 쓰이지 않는다고 함)
  • setValue() : 쿠키 값 설정
  • setVersion() : 쿠키 버전 설정

JSP 쿠키 생성


  • Cookie cookie = new Cookie("CookieName", CookieValue");
  • Cookie class로 쿠키 생성
  • Cookie class의 첫번째 인자는 쿠키 이름, 두번째 인자는 쿠키 값이다. 
  • 쿠키 유지 시간 설정
    • cookie.setMaxAge(60*60); // 1시간
  • 응답객체에 쿠키 저장
    • response.addCookie(cookie);

JSPExample.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Cookie cookie = new Cookie("name""value");
cookie.setMaxAge(60*60); // 1 hour
response.addCookie(cookie);
%>
<a herf="CookieEx.jsp">cookie get</a>
</body>
</html>
cs


JSP 쿠키 정보 Client 출력


  • Cookie[] cookies = request.getCookies();
  • request 객체로 Cookie 정보를 가져온다.
  • cookies[i].getName(), cookies[i].getValue() 로 Cookies 이름, 값을 알 수 있다.

CookieEx.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
for(int i =0; i <cookies.length++i)
{
       String str = cookies[i].getName();
       if(str.equals("name"))
       {
              out.println("cookies["+i+"]name:"+ cookies[i].getName()+"<br />");
              out.println("cookies["+i+"]value:"+ cookies[i].getValue()+"<br />");
       }
}
%>
<a href="CookieDel.jsp">쿠키확인</a>
</body>
</html>
cs

JSP 쿠키 삭제


  • request 객체에서 Cookies 정보를 가져온다.
  • 삭제할 쿠키를 이름으로 찾은 후 쿠키 저장시간을 0으로 초기화해서 쿠키를 지운다.
  • cookies[i].setMaxAge(0)
  • 이 전 페이지로 돌아가면 쿠키 정보를 더 이상 출력하지 않는다.

CookieDel.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
for(int i = 0; i < cookies.length++i)
{
       String str = cookies[i].getName();
       if(str.equals("name"))
       {
              out.println("name:"+cookies[i].getName()+"<br />");
              cookies[i].setMaxAge(0);
              response.addCookie(cookies[i]);
       }
}
%>
</body>
</html>
cs


JSP 쿠키 로그인 예제


  • id, pass 를 입력받아서 로그인이 성공하면 Admin.jsp 페이지로 이동한다.
  • 만약 로그아웃하려면 Cookie 시간을 0으로 설정하면 된다.

login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="SignIn.jsp" method="post">
아이디:<input type="text" name="id" size="10"><br />
비밀번호 : <input type="password" name="pw" size="10"><br />
<input type="submit" value="로그인">
</form>
</body>
</html>
Admin.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
       String id, pw;
%>
<%
       id = request.getParameter("id");
       pw = request.getParameter("pw");
       
       if(id.equals("admin") && pw.equals("1234"))
       {
              Cookie cookie = new Cookie("id", id);
              cookie.setMaxAge(60);
              response.addCookie(cookie);
              response.sendRedirect("Admin.jsp");
       }
       else
       {
              response.sendRedirect("login.html");
       }
%>
</body>

</html>


JSP Session


  • Cookies와 달리 Session은 Server에 저장된다.
  • Cookies는 1.2mb까지 저장할 수 있지만 Session은 제한이 없다.
  • Session은 Client 요청이 들어올 때 자동 생성.
  • Cookies는 요즘 사용못하게 막는 경우가 있어 Session이 많이 사용된다.

Session 메소드


  • setAttribute() : 세션에 데이터 저장.
  • getAttribute() : 세션에서 데이터 얻음.
  • getAttributeNames() : 세션의 모든 데이터의 이름을 얻음.
  • getId() : 자동 생성된 세션의 유니크한 아이디를 얻음.
  • isNew() : 세션이 최초 생성되었는지, 이전에 생성된건지 구분
  • getMaxInactiveInterval() : Session의 유효시간을 얻음. 가장 최근 요청 시점을 기준으로 카운트.
  • D:\apache-tomcat-8.5.34\conf\web.xml web.xml에 Session 유효시간이 적혀있음.
  • 30분이 설정되어있음.

<session-config>

    <session-timeout>30</session-timeout>
</session-config>
  • removeAttribute() : 세션에서 특정 데이터 제거.
  • Invalidate() : 세션의 모든 데이터를 삭제.
login.html

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="SignIn.jsp" method="post">
아이디:<input type="text" name="id" size="10"><br />
비밀번호 : <input type="password" name="pw" size="10"><br />
<input type="submit" value="로그인">
</form>
</body>
</html>
cs


SignIn.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
       String id, pw;
%>
<%
       id = request.getParameter("id");
       pw = request.getParameter("pw");
       
       if(id.equals("admin"&& pw.equals("1234"))
       {
              session.setAttribute("id", id);
              response.sendRedirect("Admin.jsp");
       }
       else
       {
              response.sendRedirect("login.html");
       }
%>
</body>
</html>
cs


Admin.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
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Enumeration<String> enumeration = session.getAttributeNames();
while(enumeration.hasMoreElements())
{
       String sName = enumeration.nextElement().toString();
       String sValue = (String)session.getAttribute(sName);
       
       if(sValue.equals("admin"))
       {
              out.println(sValue+"님 안녕하세요"+"<br/>");
       }
       
}
%>
</body>
</html>
cs


JSP 예외 페이지


  • 기본 예외 페이지는 tomcat 페이지이므로 친숙한 디자인의 예외 페이지가 필요하다.

age지시자를 이용한 예외처리


  • 현재 Page에서 error 발생 시 errorPage.jsp 로 이동하라.
    • <%@ page errorPage="errorPage.jsp" %>
  • erroPage.jsp 에러페이지에서 page지시자를 통해 에러페이지라는 것을 명시.
    • Defaul가 false이므로 반드시 명시.
    • <%@ page isErrorPage="true"%>
  • 에러 Status 값을 준다.
    • 200은 정상적인 페이지라는 뜻. 에러 표시 페이지는 정상이므로 200으로 setting.
    • <% response.setStatus(200); %>
  • 에러 메시지 출력
    • <%= exception.getMessage() %>
ExceptionEx.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page errorPage="Error.jsp" %>>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
int i = 40/0;
%>
</body>
</html>
cs


Error.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    <%@ page isErrorPage="true" %>
    <% response.setStatus(200); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
Error가 발생했습니다<br>
<%= exception.getMessage() %>
</body>
</html>
cs


web.xml 파일을 이용한 예외 처리


  • web.xml 파일로 예외처리를 할 수 있다.
  • web.xml 파일 위치
  • Project\WebContent\WEB-INF\web.xml
  • <error-page> 안에 에러페이지 정보를 기술한다.
  • <error-page> 안에 errorcode, 이동할 예외처리 페이지를 적는다
1
2
3
4
<error-page>
    <error-code>500</error-code>
    <location>/error500.jsp</location>
</error-page>
cs


JSP 자바 빈


  • JAVA언어의 속성, 메소드로 이루어진 클래스.
  • JSP페이지 안에서 액션태크를 사용해 빈을 사용.
  • 자바 빈이란 jsp에서 Java 객체를 가져와 쓸 수 있도록 해주는 것.

자바 빈 액션 태그


  • 빈을 사용한다는 선언
  • scope value
    • page일 때 : 생성된 페이지 내에서만 사용.
    • request일 때 : 요청된 페이지 내에서 사용.
    • session일 때 : 웹브라우저의 생명주기와 동일하게 사용 가능.
    • application일 때 : 웹 어플리케이션 생명주기와 동일하게 사용 가능.
    • <jsp:useBean id = "자바빈 name" class="pakage.classname" scope="area" />
  • 객체 값 설정
  • player 객체에 id속성 값을 1로 설정.
<jsp:setProperty name="player" property="id" value="1"/>

  • 객체 값 가져오기
<jsp:getProperty name="player" property="id"/><br />


BeanEx,.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="player" class="w.Player" scope="page" />
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<jsp:setProperty name="player" property="id" value="1"/>
<jsp:setProperty name="player" property="name" value="gosu" />
<jsp:setProperty name="player" property="level" value="20" />
id:<jsp:getProperty name="player" property="id"/><br />
name:<jsp:getProperty name="player" property="name"/><br />
level:<jsp:getProperty name="player" property="level"/><br />
</body>
</html>
cs


Player.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
package w;
public class Player {
       private int          id;
       private String       name;
       private int   level;
       
       public Player()
       {
       
       }
       
       public void setId(int _id)
       {
              id = _id;            
       }
       
       public int getId()
       {
              return id;
       }
       
       public void setName(String _name)
       {
              name = _name;
       }
       
       public String getName()
       {
              return name;
       }
       
       public void setlevel(int _level)
       {
              level = _level;            
       }
       
       public int getlevel()
       {
              return level;
       }
}
cs


반응형

'이전게시판 > JSP' 카테고리의 다른 글

JDBC로 OLACLE 접속  (0) 2018.10.22
JSP 태그, request, response, 지시자, 액션태그  (0) 2018.10.20
Servlet 값 초기화, 리스너  (0) 2018.10.20
Servlet Get,Post 동작  (0) 2018.10.19
Servlet 설정, 예제  (0) 2018.10.18
JSP 설치, 설정, 실행  (0) 2018.10.18

Post

반응형

JSP 태그, request, response, 지시자, 액션태그


JSP 태그


  • JSP는 html코드에 java를 사용하여 다이나믹 웹을 만들 수 있다.
  • html에서 java를 사용하기 위해 jsp 태그를 사용한다.
  • jsp 태그
    • 지시자 : <%@ @> 페이지 속성
    • 주석 : <%-- --%>
    • 선언 : <%! %> 변수, 메소드 선언
    • 표현식 : <%= %> : 결과값 출력
    • 스크립트릿 : <% %> java 코드
    • 액션태크 : <jsp:action> </jsp:action> : 자바빈 연결

JSP 동작 원리


  • client가 web에 jsp 요청 시 jsp 컨테이너가 jsp파일을 servlet파일(.java)로 변환
  • 그리고 servlet파일(.java)은 컴파일 된 후 클래스 파일(.class)로 변환되고 html 파일로 응답함.
  • jsp가 요청을 받을 시 servlet, class 파일로 변환되고 메모리에 올려지고, 요청 응답을 한다.
  • 다시 요청을 받을 시 메모리에 이미 올려져있으므로, 메모리에 올려진 데이터를 재활용해서 응답 한다. 

JSP 내부 객체


  • 개발자가 객체를 생성하지 않고 바로 사용할 수 있는 객체.
  • JSP컨테이너에 의해 Servlet으로 변화될 때 자동으로 객체가 생성 됨.
  • 내부객체 종류
    • 입출력 객체 : request, response, out
    • 서블릿 객체 : page, config
    • 세션 객체 : session
    • 예외 객체 : exception

JSP 스크립트릿, 선언, 표현식


  • <% java 코드 기술 %>
  • jsp페이지에서 java 언어를 사용하기 위한 요소
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
int i = 0;
for(i = 0; i < 10++i)
{
       out.println(i+":"+"HelloWorld"+"<br/>");
}
%>
</body>
</html>
cs


  • <% java 선언 기술 %>
  • 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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%!
int a = 10;
int b = 20;
%>
<%!
public int sum(int a, int b)
{
       return a+b;   
}
%>
<%
out.println(a+"+"+b+"="+sum(a, b)+"<br/>");
%>
</body>
</html>
cs


  • <%= java 코드 기술 %>
  • 변수의 값 또는 메소드 호출 결과값을 출력하기 위해 사용됨.
  • 결과값은 String 타입이며 ;를 사용할 수 없다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%!
int a = 10;
int b = 20;
%>
<%=%></br>
<%=%></br>
</body>
</html>
cs


JSP 지시자


  • JSP 페이지의 전체적인 속성을 지정할 때 사용.
  • <%@ 속성 %>
  • page : JSP페이지 속성. import 할 때도 쓴다.
1
2
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
cs


  • include : 다른 page의 내용을 삽입함.
  • JspEx.jsp, IncludeEx.jsp 파일을 만들고 JspEx.jsp 소스에 include 지시자를 사용한다.
  • 출력결과  JspEx.jsp 페이지 IncludeEx.jsp 페이지 라고 나오는 것을 확인할 수 있다.
JspEx.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page import="java.util.Arrays" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
JspEx.jsp 페이지
<%@ include file="IncludeEx.jsp" %>
</body>
</html>
cs


IncludeEx.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
IncludeEx.jsp 페이지
</body>
 
</html>
cs


taglib 지시자


  • 사용자가 만든 tag들을 태그 라이브러리라고 함.
  • 유명한 라이브러리로 JSTL이 있음.

JSP 주석


  • <%-- 주석 -->
  • JSP 주석은 페이지 소스 보기로 보이지 않음.
  • JSP 안에서 java 주석을 사용해도 됨.

request 객체


  • web client가 server로 정보를 요청하는 것을 request라고 함.
  • 요청정보는 request 객체가 관리함.
  • 메소드
    • getServerName() : 서버 이름 얻어옴
    • getServerPort() : 서버 포트 번호 얻어옴
    • getContextPath() : 웹어플리케이션의 컨텍스트 패스를 얻음.
    • getMethod() : get, post 방식 구분
    • getSession() : session 객체 얻음.
    • getProtocol() : protocol 객체 얻음.
    • getRequestURL() : 요청 URL을 얻음.
    • getRequestURI() : 요청 URI를 얻음.
    • getQueryString() : 쿼리스트링을 얻음.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
out.println("ServerName:"+request.getServerName()+"<br/>");
out.println("ServerPort:"+request.getServerPort()+"<br/>");
out.println("ContextPath:"+request.getContextPath()+"<br/>");
out.println("Get or Post?:"+request.getMethod()+"<br/>");
out.println("URL:"+request.getRequestURL()+"<br/>");
out.println("URI:"+request.getRequestURI()+"<br/>");
out.println("QueryString:"+request.getQueryString()+"<br/>");
%>
</body>
</html>
cs


Parameter메소드


  • JSP 코드로 요청받은 정보의 값을 얻어온다.
  • 메소드
    • getParameterNames() : Parameter 이름 구함
    • getParameter(String name) : Parameter 이름으로 값을 찾음.
    • getParameterValues(String name) : 배열같이 여러개의 값을 가지고 있을 때 이름을 구함.

form.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
28
29
30
31
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="JspEx.jsp" 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/>
취미:<input type="checkbox" name="hobby" value="read">독서
<input type="checkbox" nam="hobbpy" value="cook">요리
<input type="checkbox" nam="hobbpy" value="run">조깅
<input type="checkbox" nam="hobbpy" value="swim">수영
<input type="checkbox" nam="hobbpy" value="sleep">취침<br/>
<input type="radio" name="major" value="kor">국어
<input type="radio" name="major" value="checked">영어
<input type="radio" name="major" value="mat">수학
<input type="radio" name="major" value="des">디자인<br/>
<select name="protocol">
<option value="http">http</option>
<option value="ftp" selected="selected">ftp</option>
<option value="smtp">smtp</option>
<option value="pop">pop</option>
</select><br/>
<input type="submit" value="전송">
<input type="reset" value="초기화">
</form>
</body>
</html>
cs


JspEx.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
<%@page import ="java.util.Arrays" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equivb="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%!
String name, id, pw, major, protocol;
String[] hobbys;
%>
<%
request.setCharacterEncoding("EUC-KR");
name = request.getParameter("name");
id = request.getParameter("id");
pw = request.getParameter("pw");
major = request.getParameter("major");
protocol = request.getParameter("protocol");
hobbys = request.getParameterValues("hobby");
%>
이름:<%= name %><br/>
id:<%=id %><br/>
pw:<%=pw %><br/>
major=<%=major %><br />
protocol=<%=protocol %><br />
</body>
</html>
cs



response 객체의 이해


  • 요청의 응답 정보를 가지고 있는 객체.
  • 메소드
    • getCharacterEncoding() : 응답할 때 문자의 인코딩 형태를 구함.
    • addCookie(Cokkie) : 쿠키 지정.
    • SendRedirect(URL) : 지정한 URL로 이동.
    • 아래 예제는 id가 admin일 경우 admin. 페이지로 이동하고 일반 유저일 경우 user 페이지로 이동하게 해놨다. 

form.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="JspEx.jsp">
id를 입력해주세요
<input type="text" name="id" size="10">
<input type="submit" value="전송">
</form>
</body>
</html>
 
cs


JspEx.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equivb="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
String str = request.getParameter("id");
if(str.equals("admin"))
{
       response.sendRedirect("admin.jsp?id="+str);     
}
else
{
       response.sendRedirect("user.jsp?id="+str);      
}
       
%>
</body>
</html>
cs


JSP 액션태그


  • JSP 파일에서 어떤 동작을 하도록 지시하는 태그.
  • forward, include, param 태그 등.. 이 있다.

forward 태그


  • 다른 페이지로 이동할 때 사용
  • 다른 페이지로 이동해도 이동한 페이지 url로 변경되지 않음.
  • <jsp:forward page="sub.jsp"/>
1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equivb="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>jspEx.jsp 페이지</h1>
<jsp:forward page="user.jsp"/>
</body>
</html>
cs


include 태그


  • 현재 페이지에 다른 페이지를 삽입함.
  • <jsp:include page="otherpagename.jsp"/>
1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equivb="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>jspEx.jsp 페이지</h1>
<jsp:include page="user.jsp"/>
</body>
</html>
cs


param 태그


  • 데이터를 전달하는 태그.
  • 이름과 값으로 이루어져 있다.
  • forward, include 태그와 같이 사용하면 페이지를 넘길 때 Param을 넘겨줄 수 있다.
  • <jsp:param name="id" value="id" />

JspEx.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equivb="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="user.jsp">
<jsp:param name="id" value="id" />
<jsp:param name="pw" value="!@#!@#" />
</jsp:forward>
</body>
</html
cs


user.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%!
       String id, pw;
%>
<%
id = request.getParameter("id");
pw = request.getParameter("pw");
%>
유저정보
id : <%=id %>
pass : <%=pw%>
</body>
</html>
cs


반응형

'이전게시판 > JSP' 카테고리의 다른 글

JDBC로 OLACLE 접속  (0) 2018.10.22
JSP 쿠키, Session, 예외 페이지, 자바빈  (0) 2018.10.21
Servlet 값 초기화, 리스너  (0) 2018.10.20
Servlet Get,Post 동작  (0) 2018.10.19
Servlet 설정, 예제  (0) 2018.10.18
JSP 설치, 설정, 실행  (0) 2018.10.18

Post

반응형

Servlet Get,Post 동작


Get, Post방식


  • Client가 요청할 때 Get, Post 방식이 있다.
  • Get방식은 URL 값으로 정보가 전송되어 보안에 약함
  • Post방식은 header를 이용해 정보가 전송되어 보안에 강함.


Get방식


  • html내 form 태그의 method 속성이 get일 경우 호출됨.
  • HttpServletRequest 요청 처리 객체
  • HttpServletResponse 응답 처리 객체
  • response.setContentType("text/html") text/html로 응답을 보내겠다는 의미
  • html문법을 쓸 수 없기 때문에 PrintWriter class로 html 문법 사용 가능


Post방식


  • jsp파일에 method가 post인 form을 생성한다.
  • form action은 이동할 url 값으로 설정한다.
<form action="hw" method="post">
       <input type="submit" value="post">

</form>


Context Path


  • WSA에서 웹 어플리케이션을 구분하기 위한  Path.
  • 이클립스에서 프로젝트를 생성하면, 자동으로 server.xml에 추가됨.
  • http://localhost:8090/ex/hw

<Context docBase="ex" path="/ex" reloadable="true" source="org.eclipse.jst.jee.server:ex"/></Host>

Servlet 작동순서


  • 클라이언트에서 servlet 요청이 들어오면 서버에서는 servlet 컨테이너를 만들고 요청이 있을 때마다 스레드 생성.
  • 보통 web Server는 요청이 많을수록 객체를 생성해서 느려진다.
  • Servlet은 JVM 위에 MultiThread로 처리할 수 있어서 부하가 적다.
  • Servlet 객체 생성(최초)->Init() 호출(최초)->service(), doGet(), doPost() 호출(요청시)->destroy() 호출(마지막 한번, 서버 재가동 등..)
  • Init()호출 전 선처리 @PostConstruct 가 호출됨.
  • destory()호출 후 후처리 @PreDestroy가 호출됨.

form 태그


  • 서버쪽으로 정보를 전달할 때 사용.
  • ex) <form action = "Form" method="post">
  • action : 요청하는 컴포넌트 이름(join.jsp , info.gtml)
  • post : 요청을 처리하는 방식(get, post)
  • Get : local:8090/컨텍스트/path/MemberJoin?id="abcd"&name="ww"
  • Post : local:8090/컨텍스트/path/MemberJoin
  • 아래는 jsp, servlet 예제

jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="FormEx" 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/>
취미:<input type="checkbox" name="hobby" value="read">독서
<input type="checkbox" nam="hobbpy" value="cook">요리
<input type="checkbox" nam="hobbpy" value="run">조깅
<input type="checkbox" nam="hobbpy" value="swim">수영
<input type="checkbox" nam="hobbpy" value="sleep">취침<br/>
<input type="radio" name="major" value="kor">국어
<input type="radio" name="major" value="checked">영어
<input type="radio" name="major" value="mat">수학
<input type="radio" name="major" value="des">디자인<br/>
<select name="protocol">
<option value="http">http</option>
<option value="ftp" selected="selected">ftp</option>
<option value="smtp">smtp</option>
<option value="pop">pop</option>
</select><br/>
<input type="submit" value="전송">
<input type="reset" value="초기화">
</form>
</body>
</html>


servlet
package com.java.w;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
 * Servlet implementation class FormEx
 */
@WebServlet("/FormEx")
public class FormEx extends HttpServlet {
       private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FormEx() {
        super();
        // TODO Auto-generated constructor stub
    }
       /**
        * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
        */
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // TODO Auto-generated method stub
              response.getWriter().append("Served at: ").append(request.getContextPath());
       }
       /**
        * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
        */
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // TODO Auto-generated method stub
              doGet(request, response);
              
              System.out.println("doPost");
              
              String id = request.getParameter("id");
              String pw = request.getParameter("pw");
              String[] hobbys = request.getParameterValues("hobby");
              String major = request.getParameter("major");
              String protocol = request.getParameter("protocol");
              response.setContentType("text/html; charset=EUC-KR");
              PrintWriter writer = response.getWriter();
              
              writer.println("");
              writer.println("아이디:"+id+"
"); writer.println("비밀번호:"+pw+"
"); writer.println("취미:"+Arrays.toString(hobbys)+"
"); writer.println("전공:"+major+"
"); writer.println("프로토콜:"+protocol); writer.println(""); writer.close(); } }


한글처리


  • Tomcat 서버의 기본 문자 처리 방식은 IOS-8859-1 방식.
  • 별도의 인코딩을 하지 않으면 한글이 깨져보임
  • server.xml 수정
    • <Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8090"  protocol="HTTP/1.1" redirectPort="8443"/>
  • servlet 인코딩 세팅 추가
    • request.setCharacterEncoding("UTF-8");



반응형

'이전게시판 > JSP' 카테고리의 다른 글

JDBC로 OLACLE 접속  (0) 2018.10.22
JSP 쿠키, Session, 예외 페이지, 자바빈  (0) 2018.10.21
JSP 태그, request, response, 지시자, 액션태그  (0) 2018.10.20
Servlet 값 초기화, 리스너  (0) 2018.10.20
Servlet 설정, 예제  (0) 2018.10.18
JSP 설치, 설정, 실행  (0) 2018.10.18

Post

반응형

자바기초 정리


String


java String 선언 시 두가지 방법이 존재
String str = new String();
String srt = "value";

첫번째 방법은 String 자료형이 heap에 할당됨.
두번째 방법은 String 값이 string constant pool이라는 영역에 할당된다. 만약 이미 선언되어있다면 그 값을 가져온다.
메모리를 아끼려면 2번째 방법(String 리터널) 방법으로 사용하는게 좋을 듯..

StringBuffer 


문자열을 추가하거나 변경할 때 주로 사용한다.
String과 다른 점은 String은 문자열 연산 시 객체 생성을 하지만 StringBuffer는 한번만 객체 생성이 된다.
또 String 보다 메모리 사용량도 많고 속도도 느다고 한다.
(일단 같은 문자열을 length() 함수로 출력했을 때 메모리는 같았다.)


String, StringBuffer, StringBuilder의 차이점


String은 메모리공간이 변하지 않는다. 그래서 문자열을 붙이면, 그 문자열을 참조한다. 그래서 문자열 연산이 많을 경우 성능이 좋지 않다.
StringBuffer, StringBuilder는 문자열 연산이 있을 때 크기를 변경해 문자열을 변경한다. 그래서 연산이 많을 때 사용하면 좋다.
둘의 차이점은 StringBuffer는 동기화를 지원하지만 StringBuilder는 멀티스레드 환경에서 사용하면 위험하다.

문자열 연산 시 StringBuffer가 더 효과있는지 확인하기 위해 테스트해보았다.
테스트 결과 문자열 연산 시 StringBuffer가 String보다 5배 더 빨랐다.

package Example;
import java.text.SimpleDateFormat;
public class HelloWorld {
       public static void main(String args[])
       {
              String str = new String("Hello Java");
              String nowTime = getCurrentTime("YYYY.MM.DD. HH:mm:ssSSS");
              for(int i = 0; i < 10000; ++i)
              {
                     System.out.println(str+" Hello Java");
              }
              String nowTime2 = getCurrentTime("YYYY.MM.DD. HH:mm:ssSSS");
              
                           
              StringBuffer strBuf = new StringBuffer("Hello Java");
              String nowTime3 = getCurrentTime("YYYY.MM.DD. HH:mm:ssSSS");
                           
              for(int i = 0; i < 10000; ++i)
              {
                     System.out.println("strBuf"+"Hello Java");
              }
              String nowTime4 = getCurrentTime("YYYY.MM.DD. HH:mm:ssSSS");
              
              System.out.println("1:" + nowTime);
              System.out.println("2:" + nowTime2);
              System.out.println("3:" + nowTime3);
              System.out.println("4:" + nowTime4);
       }
       
       public static String getCurrentTime(String timeFormat)
       {
              return new SimpleDateFormat(timeFormat).format(System.currentTimeMillis());
       }
}

ArrayList


배열은 크기가 고정이지만 List는 가변이다.
원래는 Generics(<>)를 사용하지 않아 item들이 Object로 인식되어 잘못된 형변환을 하는 경우가 있었다.
현재는 자료형을 명확히 적어주기 때문에 형변환에 의한 오류가 없어졌다.

package Example;
import java.util.ArrayList;
public class HelloWorld {
       public static void main(String args[])
       {
              ArrayList<Integer> arrList = new ArrayList();
              arrList.add(2);
              arrList.add(1);
              arrList.add(4);
              arrList.add(3);
              System.out.println(arrList);
              System.out.println(arrList.get(2));             // 2번째 요소 선택(4)
              System.out.println(arrList.size());             // 크기 출력(4)
              arrList.remove(2);                                     // 2번째 요소 삭제
              System.out.println(arrList);                    // 다시 출력
                           
       }
       
}

반응형

'이전게시판 > Java' 카테고리의 다른 글

vscode 폰트 변경 안될 때  (0) 2022.12.26

Post

반응형

1. R설치

R이란? 오픈소스로 통계, 데이터 시각화를 위한 언어

다운로드 URL : https://www.r-project.org/


2. R스튜디오 설치

R스튜디오란? 운영체제 환경에 상관없이 보편적으로 활용할 수 있는 오픈소스에 기반한 R관련 툴.

다운로드 URL : https://www.rstudio.com/


한국어 설정을 위한 기본 설정

Tools - Global Option - Code - Saving

Default text encoding 에서 UTF-8 을 선택하고 OK


3. Java 설치

다운로드 URL : http://www.oracle.com/technetwork/java/index.html


JDK 설치된 후 파일 경로

C:\Program Files\Java\jdk1.9.0_111

C:\Program Files\Java\jre8

C:\Program Fies (x86)\Java\jre8


Java 환경 변수 설정

제어판 - 시스템 - 시스템속성 - 고급 - 환경변수

시스템 변수를 새로만들기 클릭


* 폴더가 실제 있는지 확인할 것

변수이름 : CLASSPATH

변수 값 :  %classpath%;.


변수이름 : JAVA_HOME

변수 값 : C:\Program Files\Java\jdk-9.0.1


변수이름 : path

변수 값 : C:\Program Files\Java\jdk-9.0.1\bin


환경변수 잘 적용되었는지 확인(cmd 창에서 아래와 같이 친다)

java -version

java

javac


3개의 명령어가 잘 동작한다면 환경변수 설정이 잘 된것.

안된다면 다시 환경변수를 설정할 것.


4. 이클립스 설치

다운로드 URL : https://www.eclipse.org/


설치 후 Project , Packege, Class 순으로 생성한다.

Class 안에다가 소스를 넣으면 된다.



5. JSOUP 설치

HTML 형식의 STRING을 넘겨주면 자바에서 사용할 수 있는 DOM 객체로 만들어주는 라이브러리

(JSON 비슷한듯?)

다운로드 URL : https://jsoup.org/


설치 후 Project에서 오른쪽클릭으로 Preperties - Java Build Path - Libraries 에서 Add External JARs...클릭

그리고 나서 방금 다운받은 jar 파일을 클릭하고 확인.

그러면 라이브러리라 프로젝트 솔루션 창에 추가되어있다.


JSPOUP를 사용하기 위해 IMPORT 추가한다.



import java.io.IOException;

import org.jsoup.Connection;

import org.jsoup.Jsoup;

import org.jsoup.nodes.Document;

import org.jsoup.select.Elements;

import org.jsoup.nodes.Element;




반응형
▲ top