DBCP

* TOMCAT 5.0 이상은 등록되어 있음. (라이브러리) 이전 버전은 사이트에서 다운받아 셋팅.
* 아파치 사이트로 이동. ( http://www.apache.org/ )
   - tomcat - document - tomcat7.0 - user Guide - 9) JDBC DataSoureces   에서 오라클 context사용 예 사용.

* -project
      - WebContent
            - MEMA-INF
                 - context.xml (파일 생성)
            - WEB-INF
                 - web.xml (내용 추가)



* 설치된 oracle에서 ojdbc6.jar ( 테스트 버전 oracle XE 11.) 를 복사하여 JAVA 설치된 곳의

  ..\Java\jre1.8.0_121\lib\ext

   ..\Java\jdk1.8.0_121\jre\lib\ext

 두곳에 복사한다.




* context.xml

: url, username, password 등 기본 사항 변경.

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<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="scott"
              password="tiger"
              maxActive="20"
              maxIdle="10"
              maxWait="-1"/>
</Context>



* web.xml

jdbc/myoracle는 동일해야 한다.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>day06_dbcp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
 
  <!-- /////////////   DBCP설정  //////////////////////// -->
  <resource-ref>
  <description>Oracle Datasource example</description>
  <res-ref-name>jdbc/myoracle</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
  </resource-ref>
  <!-- ////////////////////////////////////////////////// -->
</web-app>



[[  test.jsp  ]]

<%@page import="test.dbcp.DbcpBean"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.naming.Context"%>
<%@ 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>
<%
Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
%>
conn:<%=conn %><br/>

<%
    DbcpBean dbcp=new DbcpBean();
    Connection con=dbcp.getCon();

%>
con:<%=con %><br/>
</body>
</html>


[[  DbcpBean.java  ]]

package test.dbcp;

import java.sql.Connection;
import java.sql.SQLException;

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

public class DbcpBean {
    private DataSource ds;
    public DbcpBean(){
        try{
            Context initContext = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            ds = (DataSource)envContext.lookup("jdbc/myoracle");   
        }catch(NamingException ne){
            System.out.println(ne.getMessage());
        }
    }
    public Connection getCon(){
        Connection con=null;
        try{
            con = ds.getConnection();
            return con;
        }catch(SQLException se){
            System.out.println(se.getMessage());
            return null;
        }
    }
}




'WEB > JSP' 카테고리의 다른 글

16. <jsp:useBean> 태그  (0) 2013.04.23
15. 파일 첨부  (0) 2013.04.20
13. JSP 간단한 예제 ( 목록, 입력, 수정, 삭제 )-model1  (0) 2013.04.19
12. JSP 스코프  (0) 2013.04.19
11. JSP 예제1  (0) 2013.04.19

간단한 회원가입, 수정, 삭제, 조회  예제( JSP )


- 목록


create table MEMBERS

(

  ID      VARCHAR2(30) primary key,

  PWD     VARCHAR2(30),

  EMAIL   VARCHAR2(100),

  PHONE   VARCHAR2(100),

  REGDATE DATE

)


DBConnection.java

package test.db;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;


public class DBConnection {

public static Connection getCon() throws SQLException{

Connection con=null;

try{

Class.forName("oracle.jdbc.OracleDriver");

String url = "jdbc:oracle:thin:@localhost:1521:xe";

con=DriverManager.getConnection(url, "scott", "tiger");

return con;

}catch(ClassNotFoundException ce){

System.out.println(ce.getMessage());

return null;

}

}

}



index.html

<!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>

<ul>

<li><a href="member/insert.html">회원가입</a></li>

<li><a href="member/list.jsp">회원목록</a></li>

</ul>

</body>

</html>





insert.html

<!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>

<style type="text/css">

#regbox{ width : 300px; }

#regbox label{ display : block; width: 100px; float : left; }

</style>

</head>

<body>

<form method="post" action="insert.jsp">

<fieldset id="regbox">

<legend>회원가입</legend>

<label for="id">아이디</label>

<input type="text" name="id"/><br/>

<label for="pwd">비밀번호</label>

<input type="password" name="pwd"/><br/>

<label for="email">이메일</label>

<input type="text" name="email"/><br/>

<label for="phone">전화번호</label>

<input type="text" name="phone"/><br/>

<input type="submit" value="가입">

<input type="reset" value="취소"/>

</fieldset>

</form>

</body>

</html>





insert.jsp

<%@page import="java.sql.SQLException"%>

<%@page import="java.sql.PreparedStatement"%>

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.Connection" %>

<%@page import="test.db.DBConnection"%>

<!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>

<%

request.setCharacterEncoding("euc-kr");

String id=request.getParameter("id");

String pwd=request.getParameter("pwd");

String email=request.getParameter("email");

String phone=request.getParameter("phone");

//db에 저장하기

Connection con = null;

PreparedStatement pstmt = null;

String sql = "insert into members values(?,?,?,?, sysdate)";

int n=0;

try{

con = DBConnection.getCon();

pstmt = con.prepareStatement(sql);

pstmt.setString(1, id);

pstmt.setString(2, pwd);

pstmt.setString(3, email);

pstmt.setString(4, phone);

n = pstmt.executeUpdate();

}catch(SQLException se){

System.out.println(se.getMessage());

}finally{

try{

if(pstmt!=null) pstmt.close();

if(con!=null) con.close();

}catch(SQLException se){

System.out.println(se.getMessage());

}

}

// 결과 응답하기

%>

<script type="text/javascript">

if(<%=n%> > 0){

alert("정상적으로 회원가입되었습니다.");

location.href="../index.html";//

}else{

alert("회원가입에 실패했습니다.");

history.go(-1);//이전페이지로 가기

}

</script>

</body>

</html>





list.jsp

<%@page import="test.db.DBConnection"%>

<%@page import="java.sql.Timestamp"%>

<%@page import="java.sql.SQLException"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@ 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>

<h2>회원목록</h2>

<table border="1" width="600">

<tr>

<td>아이디</td>

<td>비밀번호</td>

<td>이메일</td>

<td>전화번호</td>

<td>가입일</td>

<td>삭제</td>

<td>수정</td>

</tr>

<%

//db 에서 회원목록 얻어와 테이블에 출력하기.

Connection con=null;

PreparedStatement pstmt=null;

ResultSet rs = null;

try{

con = DBConnection.getCon();

String sql="select * from members";

pstmt = con.prepareStatement(sql);

rs = pstmt.executeQuery();

while(rs.next()){

String id = rs.getString("id");

String pwd = rs.getString("pwd");

String email = rs.getString("email");

String phone = rs.getString("phone");

Timestamp regdate = rs.getTimestamp("regdate");

%>

<tr>

<td><%=id %></td>

<td><%=pwd %></td>

<td><%=email %></td>

<td><%=phone %></td>

<td><%=regdate %></td>

<td><a href="delete.jsp?id=<%=id%>" >삭제</a></td>

<td><a href="update.jsp?id=<%=id%>" >수정</a></td>

</tr>

<%

}

}catch(SQLException se){

System.out.println(se.getMessage());

}finally{

try{

if(rs!=null)  rs.close();

if(pstmt!=null)  pstmt.close();

if(con!=null)  con.close();

}catch(SQLException se){

System.out.println(se.getMessage());

}

}

%>

</table>

</body>

</html>




update.jsp

<%@page import="java.sql.SQLException"%>

<%@page import="java.sql.Timestamp"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="test.db.DBConnection"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@ 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>

<%

request.setCharacterEncoding("euc-kr");

String id=request.getParameter("id");

Connection con=null;

PreparedStatement pstmt=null;

ResultSet rs = null;

try{

con = DBConnection.getCon();

String sql="select * from members where id=?";

    

pstmt = con.prepareStatement(sql);

                pstmt.setString(1, id);

rs = pstmt.executeQuery();


String pwd = rs.getString("pwd");

String email = rs.getString("email");

String phone = rs.getString("phone");

Timestamp regdate = rs.getTimestamp("regdate");

%>

<form name='frm1' method='post' action='updateOk.jsp'>

<table>

<tr>

<td>아이디</td>

<td><%=id %><input type="hidden" name="id" value="<%=id%>"/></td>

</tr>

<tr>

<td>비밀번호</td>

<td><input type="text" name="pwd" value="<%=pwd %>"/></td>

</tr>

<tr>

<td>이메일</td>

<td><input type="text" name="email" value="<%=email %>"/></td>

</tr>

<tr>

<td>전화번호</td>

<td><input type="text" name="phone" value="<%=phone %>"/></td>

</tr>

<tr>

<td>등록일</td>

<td><%=regdate %></td>

</tr>

<tr>

<td colspan="2" align="center">

<input type="button" name="btn1" value="저장" onclick="javascript:frm1.submit();"/>

<input type="button" name="btn2" value="목록" onclick="javascript:location.href='list.jsp';"/>

</td>

</tr>

</table>

</form>

<%

}catch(SQLException se){

System.out.println(se.getMessage());

}finally{

try{

if(rs!=null)  rs.close();

if(pstmt!=null)  pstmt.close();

if(con!=null)  con.close();

}catch(SQLException se){

System.out.println(se.getMessage());

}

}


%>

<script type="text/javascript">

function update(){

document.frm1.submit();

}

function list(){

location.href="list.jsp";

}

</script>

</body>

</html>




updateOk.jsp

<%@page import="java.sql.SQLException"%>

<%@page import="test.db.DBConnection"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@ 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>

<%

request.setCharacterEncoding("euc-kr");


String id=request.getParameter("id");

String pwd=request.getParameter("pwd");

String email=request.getParameter("email");

String phone=request.getParameter("phone");


//db에 저장하기

Connection con = null;

PreparedStatement pstmt = null;

String sql = "update members set pwd=?, email=?, phone=? where id= ?";

int n=0;

try{

con = DBConnection.getCon();

pstmt = con.prepareStatement(sql);

pstmt.setString(1, pwd);

pstmt.setString(2, email);

pstmt.setString(3, phone);

pstmt.setString(4, id);

n = pstmt.executeUpdate();

}catch(SQLException se){

System.out.println(se.getMessage());

}finally{

try{

if(pstmt!=null) pstmt.close();

if(con!=null) con.close();

}catch(SQLException se){

System.out.println(se.getMessage());

}

}

%>


<script type="text/javascript">

if(<%=n%>>0 ){

alert("수정되었습니다.");

location.href="list.jsp";

}else{

alert("수정 실패");

history.go(-1);

}

</script>

</body>

</html>


delete.jsp

<%@page import="test.db.DBConnection"%>

<%@page import="java.sql.SQLException"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@ 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>

<%

//삭제할 아이디

Connection con = null;

PreparedStatement pstmt = null;

String id = request.getParameter("id");

int n=0;

try{

con = DBConnection.getCon();

String sql="delete from members where id=?";

pstmt = con.prepareStatement(sql);

pstmt.setString(1, id);

n = pstmt.executeUpdate();

}catch(SQLException se){

System.out.println(se.getMessage());

}finally{

if(pstmt!=null) pstmt.close();

if(con!=null) con.close();

}

response.sendRedirect("list.jsp");

%>

</body>

</html>




'WEB > JSP' 카테고리의 다른 글

15. 파일 첨부  (0) 2013.04.20
14. DBCP  (0) 2013.04.20
12. JSP 스코프  (0) 2013.04.19
11. JSP 예제1  (0) 2013.04.19
10. JSP - 특정페이지로 이동방법(forward/redirect)  (0) 2013.04.19


[[ JSP에서의 스코프(영역 ***) ]]


1.application

 - 모든 서블릿, jsp에서 공유하는 영역

 - 웹서버가 종료될때까지 유효한 영역

 - 값을 저장할때는 application.setAttribute("이름", 객체);

   값을 꺼내올때는 Object ob = application.getAttribute("이름");

   

2. session(**)

 - 웹브라우저가 종료될때까지 또는 일정유지시간(세션유지시간)동안 유효한 영역

 - 값을 저장할때는 session.setAttribute("이름",객체);

   값을 꺼내올때는 Object ob = session.getAttribute("이름");

 - 사용예: 로그인 처리, 장바구니, ..

 

 3. request(**)

 - 클라이언트에 응답할때까지 유효

 - 값을 저장할때는 request.setAttribute("이름",객체);

   값을 꺼내올때는 Object ob = request.getAttribute("이름");

   

4. page

 - 하나의 페이지에서만 유효(기본값으로 설정되어 있음)






1. application


1.jsp

<%@ 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>

<%

//어플리케이션 스코프에 값 저장하기.

String user="song";

String pwd="1234";

application.setAttribute("user",user);

application.setAttribute("pwd",pwd);

%>

어플리케이션영역에 값 저장성공<br/>

<%

String a=(String)application.getAttribute("user");

String b=(String)application.getAttribute("pwd");

%>

user:<%=a %><br/>

pwd:<%=b %><br/>

<a href="2.jsp">2.jsp로 이동</a>

</body>

</html>


2.jsp

; 페이지 이동후에도 값 유지.

<%@ 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>

<%

String a = (String)application.getAttribute("user");

String b = (String)application.getAttribute("pwd");

%>

user:<%=a %><br/>

pwd:<%=b %>

</body>

</html>




2. session(**)


1.jsp

<%@ 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.setAttribute("id","song");

session.setAttribute("pwd","1234");

//세션에 저장된 값 꺼내오기

String id=(String)session.getAttribute("id");

String pwd=(String)session.getAttribute("pwd");

%>

<h1>세션에 저장된 데이터</h1>

id:<%=id %><br/>

pwd:<%=pwd %><br/>

<a href="2.jsp">2.jsp</a>

</body>

</html>


2.jsp

<%@ 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>

<%

String id=(String)session.getAttribute("id");

String pwd=(String)session.getAttribute("pwd");

%>

<h1>세션에 저장된 값</h1>

id:<%=id %><br/>

pwd:<%=pwd %>

</body>

</html>




3. request(**)


login.jsp

<%@ 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>

<form method="post" action="loginOk.jsp">

아이디<input type="text" name="id"/><br/>

비밀번호<input type="password" name="pwd"/><br/>

<input type="submit" value="로그인"/>

<input type="reset" value="취소"/>

</form>

</body>

</html>


loginOk.jsp

<%@page import="java.sql.SQLException"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@page import="test.db.DBConnection"%>

<%@ 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>

<%

// 전송된 아이디와 비밀번호 얻어오기.

request.setCharacterEncoding("euc-kr");

String id=request.getParameter("id");

String pwd=request.getParameter("pwd");

//DB에 해당정보가 존재하는 지 검사하기.

Connection con=null;

PreparedStatement pstmt=null;

ResultSet rs=null;

boolean isMember = false;

try{

con=DBConnection.getCon();

String sql="select * from members where id=? and pwd=?";

pstmt = con.prepareStatement(sql);

pstmt.setString(1, id);

pstmt.setString(2, pwd);

rs=pstmt.executeQuery();

if(rs.next()){

isMember=true;

}

}catch(SQLException se){

System.out.println(se.getMessage());

}finally{

if(rs!=null) rs.close();

if(pstmt!=null) pstmt.close();

if(con!=null) con.close();

}

if(isMember){

session.setMaxInactiveInterval(60);

session.setAttribute("id", id );

response.sendRedirect("../main.jsp");

}else{

%>

<script type="text/javascript">

alert("아이디/비밀번호가 맞지 않습니다.");

history.go(-1);

</script>

<%

}

%>

</body>

</html>







'WEB > JSP' 카테고리의 다른 글

14. DBCP  (0) 2013.04.20
13. JSP 간단한 예제 ( 목록, 입력, 수정, 삭제 )-model1  (0) 2013.04.19
11. JSP 예제1  (0) 2013.04.19
10. JSP - 특정페이지로 이동방법(forward/redirect)  (0) 2013.04.19
9. JSP - Servlet 파라미터 받기  (0) 2013.04.18



EX1> 간단한 입력 폼을 만들고, 가입 시 파라미터 전달하기.





 입력한 폼을 insert.jsp로 전송.


insert.html


: name 지정. 

<!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>

<style type="text/css">

#regbox{

width : 300px;

}

#regbox label{

display : block;

width: 100px;

float : left;

}

</style>

</head>

<body>

<form method="post" action="insert.jsp">

<fieldset id="regbox">

<legend>회원가입</legend>

<label for="id">아이디</label>

<input type="text" name="id"/><br/>

<label for="pwd">비밀번호</label>

<input type="password" name="pwd"/><br/>

<label for="email">이메일</label>

<input type="text" name="email"/><br/>

<label for="phone">전화번호</label>

<input type="text" name="phone"/><br/>

<input type="submit" value="가입">

<input type="reset" value="취소"/>

</fieldset>

</form>

</body>

</html>







insert.jsp


getParameter로 받기.

; <%=변수 %> 

  <%=리턴값이 있는 메소드 %> 

<%@ 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>

<%

String id = request.getParameter("id");

String pwd= request.getParameter("pwd");

String email=request.getParameter("email");

String phone=request.getParameter("phone");

%>

<h2>사용자가 전송한 정보</h2>

아이디:<%= id %><br/>

패스워드:<%= pwd %><%-- 와 같은 의미 --%><br/>

이메일:<%=email %></br>

전화번호:<%=phone %><br/>

</body>

</html>







EX2> multi 선택값(체크박스) 을 넘기고 받기




insert1.html

<!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>

<form method='post' action="insert1.jsp">

아이디<input type="text" name="id"/><br/>

패스워드<input type="password" name="pwd"/><br/>

취미<br/>

<input type="checkbox" name="hobby" value="sleep" checked="checked">잠자기

<input type="checkbox" name="hobby" value="sing">노래하기

<input type="checkbox" name="hobby" value="game">게임하기

<br/>

연령대<br/>

<!--  radio는 name이 동일해야 그룹으로 묶인다. -->

<input type="radio" name="age" value="10" checked="checked"/>10대

<input type="radio" name="age" value="20" />20대

<input type="radio" name="age" value="30" />30대

<input type="radio" name="age" value="40" />40대

<input type="radio" name="age" value="50" />50대

<input type="radio" name="age" value="60" />60대이상

<br/>

기타하고싶은말<br/>

<textarea rows="5" cols="50" name="desc"></textarea>

<br/>

<input type="submit" value="전송"/>

<input type="reset" value="취소"/>

</form>

</body>

</html>





insert1.jsp

getParameterValues : multi 선택값 배열로 받음.


<%@ 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>

<%

request.setCharacterEncoding("euc-kr");

//html에서 전송된 값들 얻어오기

String id=request.getParameter("id");

String pwd= request.getParameter("pwd");


//체크박스로 전송된 취미 얻어오기. 여러개 전송될수 있으므로 배열형태로 얻어옴.

String hobby[]=request.getParameterValues("hobby");

String age=request.getParameter("age");

String desc=request.getParameter("desc");

%>

<h2>전송된 정보</h2>

아이디:<%=id %><br/>

패스워드:<%=pwd %><br/>

취미:<%

for(int i=0;i<hobby.length;i++){

out.println(hobby[i] + " ");

}

 %><br/>

나이:<%=age %><br/>

상세내역:<%=desc %><br/>

</body>

</html>







EX3> <%!  %>  선언문 사용하기


test03.jsp

<%@ 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>test02.jsp</title>

</head>

<body>

<form method="post" action="add.jsp">

수1<input type="text" name="num1"/><br/>

수2<input type="text" name="num2"/><br/>

<input type="submit" value="전송하기"/>

</form>

</body>

</html>



add.jsp;

<%!  %>  선언문


; 선언문으로 선언된 변수는 JSP파일이 웹컨테이너에 의해 컴파일될때 멤버변수로 인식된다.

 JSP페이지 어느 위치에서도 변수 참조가 가능하다.

<%@ 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>add.jsp</title>

</head>

<body>

<%!

//선언문 ==> 멤버변수나 메소드정의시 사용.

public int sum(int x, int y){

return x + y;

}

%>

<%

String num1 = request.getParameter("num1");

String num2 = request.getParameter("num2");

int n1 = Integer.parseInt(num1);

int n2 = Integer.parseInt(num2);

int n3 = sum(n1,n2);

%>

<%=n3%>입니다.


</body>

</html>








페이지이동방법(**)



1. 포워드(forward)

- request스코프에 담긴값이 유효하다.(request,response가 유지된다.)

- 이동된 url이 화면에 안보인다.(사용자는 이동했는지 알수없음)

- 포워드하는 방법

  1) pageContext.forward("이동할페이지");

  2) <jsp:forward page="이동할페이지"/>;

  3) RequestDispatcher rd = request.getRequestDispatcher("이동할페이지");

    rd.forward(request,response);



2. 리다이렉트(redirect)

- 클라이언트가 새로 페이지를 요청한 것과 같은 방식으로 페이지가 이동됨.

  request, response가 유지되지 않는다.(새로 만들어짐.)

- 이동된 url이 화면에 보인다.

- 리다이렉트 하는 방법

  response.sendRedirect("이동할페이지");



EX>

아이디, 비밀번호를 받아서 submit.

login.jsp  --> loginOk.jsp  --> result.jsp



login.jsp

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<form method="post" action="loginOk.jsp">

아이디<input type="text" name="id"/><br/>

비밀번호<input type="password" name="pwd"/><br/>

<input type="submit" value="로그인"/>

</form>

</body>

</html>




loginOk.jsp

; forward , redirect  하나씩 해보면 

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<%

String id=request.getParameter("id");

String pwd=request.getParameter("pwd");

// request스코프에 값 저장하기.

request.setAttribute("id", id);

request.setAttribute("pwd", pwd);

//포워드방식으로 페이지 이동하기.

//pageContext.forward("result.jsp");


//redirect방식

response.sendRedirect("result.jsp");

%>

</body>

</html>



result.jsp

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<%

String id=(String)request.getAttribute("id");

String pwd=(String)request.getAttribute("pwd");

id=request.getParameter("id");

%>

<h3>request 스코프에 담긴 데이터<br/></h3>

id:<%=id %><br/>

pw:<%=pwd %><br/>

</body>

</html>



; forward 방식으로 전달하면 값은 전달되고, 주소는 result.jsp로 변경되지 않는다.


; redirect방식으로 넘기면 값은 null이다. loginOk.jsp에서 값을 넘기지 않아서.. 주소는 바뀌어 있다.

; redirect방식은 request유지하지 않기 때문에 다른 페이지로 이동하면 없어진다. 

response.sendRedirect("result.jsp?id=1"); 이렇게 찍어보면 1이 넘어간다.  




<jsp:forward> 태그 사용하기.


...

<%

String id = request.getParameter("id");

String pwd= request.getParameter("pwd");

request.setAttribute("id", id);

request.setAttribute("pwd", pwd);

//forward

//pageContext.forward("result.jsp");

// redirect

//response.sendRedirect("result.jsp?id="+id);

%>

<jsp:forward page="result.jsp"></jsp:forward>

..




<RequestDispatcher사용하기>

...

<%

String id = request.getParameter("id");

String pwd= request.getParameter("pwd");

request.setAttribute("id", id);

request.setAttribute("pwd", pwd);

//forward

//pageContext.forward("result.jsp");

// redirect

//response.sendRedirect("result.jsp?id="+id);

RequestDispatcher rd = request.getRequestDispatcher("result.jsp");

rd.forward(request, response);

%>

...




EX2>

로그인 후 ID/PWD가 맞지않으면 오류메시지 찍어주고, 맞으면 다른 페이지로 이동하기.

; post방식으로 전달

; id/pwd가 맞으면 session에 저장. 페이지 이동 후 아이디를 화면에 보여줌.

; 맞지 않으면 request에 담아서 login.jsp로 dispatch함. (forward)



login.jsp

<%@ 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>

<style type="text/css">

#error{

color:red;

font-size:10pt;

}

</style>

<%

//request스코프에 담긴 오류메시지 얻어오기.

String errMsg = (String)request.getAttribute("errMsg");

if(errMsg==null){

errMsg="";

}

%>

</head>

<body>

<form method="post" action="loginOk.jsp">

아이디<input type="text" name="id"/><br/>

비밀번호<input type="password" name="pwd"/><br/>

<div id="error"><%=errMsg %></div>

<input type="submit" value="로그인"/>

</form>

</body>

</html>




loginOk.jsp

<%@ 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>

<%

String id=request.getParameter("id");

String pwd=request.getParameter("pwd");

if(id.equals("song") && pwd.equals("1234")){

session.setAttribute("id", id);

response.sendRedirect("../main.jsp");

}else{

//request에 오류메시지 담기.

request.setAttribute("errMsg", "아이디 또는 비밀번호가 일치하지 않아요.");

RequestDispatcher rd = request.getRequestDispatcher("login.jsp");

rd.forward(request, response);

}

%>

</body>

</html>



맞지않으면


맞으면







'WEB > JSP' 카테고리의 다른 글

12. JSP 스코프  (0) 2013.04.19
11. JSP 예제1  (0) 2013.04.19
9. JSP - Servlet 파라미터 받기  (0) 2013.04.18
8. 한글 처리  (0) 2013.04.18
7. Servlet 컨텍스트 영역에 값넣기  (0) 2013.04.18

+ Recent posts