* 라이브러리 등록 및 파일 upload /download 테스트


* WEB-INF밑에 upload폴더 생성. ( 파일 저장 폴더, 이클립스에서 생성. )
 : 이클립스 개발 시 실제 파일이 upload되는 경로는 따로 있다
 해당 workspace 경로밑에
\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0

\wtpwebapps\day06_fileupload\upload
에 파일이 저장되어 있다.


<< 설정 >>
http://servlets.com/cos/ 사이트 이동


* 파일 업로드 라이브러리. (cos 사용 )
  - servlet software
       - Download the package
            - cos-26Dec2008.zip 다운.
* lib/cos.jar파일을 WEB-INF/lib/cos.jar로 복사.

* upload시 동일한 이름의 파일이 존재하면 파일명 뒤에 숫자가 붙는다.
예를 들어 a.jpg가 존재하면 a.jpg, a(1).jpg,.. 이런식으로 증가된다. 실제 저장되는 파일명과 사용자가 올린 파일명 2개가 존재한다.

* enctype="multipart/form-data"으로 전송.

* 받을때도 MultipartRequest mr=new MultipartRequest (...)로 받아 사용한다.




파일업로드 테스트






[[ 테이블 ]]

; 원본 파일명 - 사용자가 올린 파일명.

; 실제저장된 파일명 - 서버에 저장된 파일명.


create table fileinfo(
 filenum number primary key,--파일고유번호
 writer varchar2(20),--작성자
 title varchar2(20),--제목
 content varchar2(50),--내용
 orgfilename varchar2(100),--원본파일명
 savefilename varchar2(100),--실제저장된파일명
 filesize number -- 파일크기
);

create sequence fileinfo_seq;



web.xml

<?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>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</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>





META-INF > context.xml

<?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" maxTotal="20" maxIdle="10"

              maxWaitMillis="-1"/>

</Context>











[[  main.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>
<a href="file1/fileupload.jsp">파일업로드하기</a><br/>
<a href="file1/filelist.jsp">파일목록보기</a>
</body>
</html>





[[  fileupload.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="fileuploadOk.jsp"   enctype="multipart/form-data">
<table border="1" width="500">
    <tr>
        <td>작성자</td>
        <td><input type="text" name="writer"/></td>
    </tr>
    <tr>
        <td>제목</td>
        <td><input type="text" name="title"/></td>
    </tr>
    <tr>
        <td>내용</td>
        <td><textarea rows="5" cols="50" name="content"></textarea></td>
    </tr>
    <tr>
        <td>첨부파일</td>
        <td><input type="file" name="file1"/></td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <input type="submit" value="전송"/>
            <input type="reset" value="취소"/>
        </td>
    </tr>
</table>
</form>
</body>
</html>







[[  fileuploadOk.jsp  ]]

;

public MultipartRequest(javax.servlet.http.HttpServletRequest request,

                        java.lang.String saveDirectory,

                        int maxPostSize,

                        java.lang.String encoding,

                        FileRenamePolicy policy)

                 throws java.io.IOException

<%@page import="test.file.FileinfoDao"%>
<%@page import="java.io.File"%>
<%@page import="test.file.FileinfoVo"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ 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>
<%
    //upload폴더의 실제경로를 얻어옴
    String dir=application.getRealPath("/upload");

    MultipartRequest mr=new MultipartRequest(
         request,//request객체
         dir,//파일을 저장할 폴더
         1024*1024*5, //최대 업로드크기 설정(5MB설정) 
         "euc-kr",//인코딩방식
          new DefaultFileRenamePolicy()//동일한파일명이 존재하면 파일명뒤에 일련번호 부여해서파일생성
        );

    //request객체가 아닌 MultipartRequest객체로 파라미터 읽어와야 함!!!
    String writer=mr.getParameter("writer");
    String title=mr.getParameter("title");
    String content=mr.getParameter("content");

    //전송된 파일명 읽어오기
    String orgfilename=mr.getOriginalFileName("file1");


    //실제저장된 파일명 읽어오기
    String savefilename=mr.getFilesystemName("file1");

   
    ////////////  전송된 정보를 DB에 저장하기  ////////////////
    //전송된 파일크기 구하기
    File f=new File(dir + File.separator + savefilename);
    long filesize=f.length();

    //전송된 정보를 vo에 담기
    FileinfoVo vo=new FileinfoVo(0,writer,title,content,
                                   orgfilename,
                                   savefilename,
                                   filesize);
    //DB에 데이터 추가하기
    FileinfoDao dao=new FileinfoDao();
    int n=dao.insert(vo);
    if(n>0){
        out.println(" 데이터 전송 성공!<br/>");
    }else{
        out.println(" 데이터 전송 실패!<br/>");
    }   
%>

작성자 :<%=writer %><br/>
제목 :<%= title %><br/>
내용 : <%=content %><br/>
전송된 파일명:<%=orgfilename %><br/>
실제저장된 파일명:<%=savefilename %><br/>
</body>
</html>



Table >







[[  filelist.jsp  ]]


; <jsp:useBean id="빈이름" class="자바빈 클래스" scope="사용범위" />

     scope : request, page, session, application,  기본값은 page


<%@page import="java.util.ArrayList"%>

<%@page import="test.file.FileinfoVo"%>

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

<jsp:useBean id="dao" class="test.file.FileinfoDao"/>

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

<caption><h2>파일목록</h2></caption>

<tr>

<th>작성자</th>

<th>제목</th>

<th>파일명</th>

<th>파일크기</th>

<th>다운로드</th>

<th>삭제</th>

</tr>

<%

ArrayList<FileinfoVo> list = dao.getList();

for(int i=0;i<list.size();i++){

FileinfoVo vo = list.get(i);

%>

<tr>

<td><%=vo.getWriter() %></td>

<td><%=vo.getTitle() %></td>

<td><%=vo.getOrgfilename() %></td>

<td><%=vo.getFilesize() %></td>

<td><a href="filedownload.jsp?filenum=<%=vo.getFilenum() %>">다운로드</a></td>

<td><a href="filedelete.jsp?filenum=<%=vo.getFilenum() %>">삭제</a></td>

</tr>

<%

}

%>

</table>

</body>

</html>




 


[[  filedelete.jsp  ]]

; 파일 삭제


<%@page import="java.io.File"%>

<%@page import="test.file.FileinfoVo"%>
<%@page import="test.file.FileinfoDao"%>
<%@ 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>
<%
////////// 1. 파일 삭제 하기 //////////////////////
int filenum=Integer.parseInt(request.getParameter("filenum"));
FileinfoDao dao=new FileinfoDao();
FileinfoVo vo=dao.getInfo(filenum);
//실제저장된 파일명 얻어오기
String savefilename=vo.getSavefilename();
//upload폴더의 실제 경로 얻어오기
String dir=application.getRealPath("/upload");
//삭제할 파일정보를 갖는 File객체 생성
File f=new File(dir+File.separator+savefilename);
if(!f.delete()){
    out.println("삭제 오류!");
}
/////////  2. DB에서 파일정보 삭제하기 ////////////////
int n=dao.delete(filenum);
if(n>0){
    out.println("삭제성공!");
}else{
    out.println("삭제 오류!");
}
%>
</body>
</html>



[[  filedownload.jsp  ]]

<%@page import="java.io.File"%>

<%@page import="java.io.OutputStream"%>

<%@page import="java.io.BufferedInputStream"%>

<%@page import="java.io.BufferedOutputStream"%>

<%@page import="java.io.FileInputStream"%>

<%@page import="test.file.FileinfoDao"%>

<%@page import="test.file.FileinfoVo"%>

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

    pageEncoding="EUC-KR"%>

<%

//파일번호얻어오기

int filenum = Integer.parseInt(request.getParameter("filenum"));

//파일에 대한 정보를 db에서 얻어오기.

FileinfoDao dao = new FileinfoDao();

FileinfoVo vo = dao.getInfo(filenum);

String savefilename=vo.getSavefilename();

String orgfilename=vo.getOrgfilename();

long filesize = vo.getFilesize();

// 다운로드 창 설정(한글파일명이 깨지지 않도록)----------------------------------

// euc-kr로 변환한 파일명 만들기

String filename=new String(orgfilename.getBytes("euc-kr"),"8859_1");


//다운로드창으로 응답하기

response.setContentType("application/octet-stream");

//파일크기 설정하기

response.setContentLength((int)filesize);

//다운로드창에 보일 파일명(euc-kr로 변환된) 설정하기

response.setHeader("Content-Disposition", "attachment;filename=" + filename);

// 실제로 다운로드(클라이언트에 복사) 하기 --------------------------------------

OutputStream os = response.getOutputStream();

//파일이 저정된 경로 얻어오기

String dir=application.getRealPath("/upload");

//서버에 저장된 파일을 얻어오기 위한 스트림 객체

FileInputStream fis = new FileInputStream( dir + File.separator + savefilename );

//성능향상을 위해 버퍼기능을 갖는 스트림객체로 반환하기

BufferedOutputStream bos = new BufferedOutputStream(os);

BufferedInputStream bis = new BufferedInputStream(fis);

//서버의 파일을 클라이언트에 복사하기

int n=0;

byte[] b=new byte[1024];

while((n=bis.read(b))!=-1){

bos.write(b, 0, n);

}

bis.close();

bos.close();

%>


** Filedownload.jsp 파일을 Servlet으로 사용해도 된다.

[[ FiledownloadServlet.java ]]

package test.file;


import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class FiledownloadServlet extends HttpServlet {

@Override

protected void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//파일번호얻어오기

int filenum = Integer.parseInt(request.getParameter("filenum"));

//파일에 대한 정보를 db에서 얻어오기.

FileinfoDao dao = new FileinfoDao();

FileinfoVo vo = dao.getInfo(filenum);

String savefilename=vo.getSavefilename();

String orgfilename=vo.getOrgfilename();

long filesize = vo.getFilesize();

// 다운로드 창 설정(한글파일명이 깨지지 않도록)----------------------------------

// euc-kr로 변환한 파일명 만들기

String filename=new String(orgfilename.getBytes("euc-kr"),"8859_1");


//다운로드창으로 응답하기

response.setContentType("application/octet-stream");

//파일크기 설정하기

response.setContentLength((int)filesize);

//다운로드창에 보일 파일명(euc-kr로 변환된) 설정하기

response.setHeader("Content-Disposition", "attachment;filename=" + filename);

// 실제로 다운로드(클라이언트에 복사) 하기 --------------------------------------

OutputStream os = response.getOutputStream();

//파일이 저정된 경로 얻어오기

String dir= getServletContext().getRealPath("/upload"); //application.getRealPath("/upload");

//서버에 저장된 파일을 얻어오기 위한 스트림 객체

FileInputStream fis = new FileInputStream( dir + File.separator + savefilename );

//성능향상을 위해 버퍼기능을 갖는 스트림객체로 반환하기

BufferedOutputStream bos = new BufferedOutputStream(os);

BufferedInputStream bis = new BufferedInputStream(fis);

//서버의 파일을 클라이언트에 복사하기

int n=0;

byte[] b=new byte[1024];

while((n=bis.read(b))!=-1){

bos.write(b, 0, n);

}

bis.close();

bos.close();

}

}



[[  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;

}

}

}



[[  FileinfoVo  ]]

package test.file;


public class FileinfoVo {

private int filenum;

private String writer ;

private String title ;

private String content ;

private String orgfilename ;

private String savefilename ;

private long filesize;

public FileinfoVo(){}


public FileinfoVo(int filenum, String writer, String title, String content,

String orgfilename, String savefilename, long filesize) {

super();

this.filenum = filenum;

this.writer = writer;

this.title = title;

this.content = content;

this.orgfilename = orgfilename;

this.savefilename = savefilename;

this.filesize = filesize;

}

public int getFilenum() {

return filenum;

}


public void setFilenum(int filenum) {

this.filenum = filenum;

}


public String getWriter() {

return writer;

}


public void setWriter(String writer) {

this.writer = writer;

}


public String getTitle() {

return title;

}


public void setTitle(String title) {

this.title = title;

}


public String getContent() {

return content;

}


public void setContent(String content) {

this.content = content;

}


public String getOrgfilename() {

return orgfilename;

}


public void setOrgfilename(String orgfilename) {

this.orgfilename = orgfilename;

}


public String getSavefilename() {

return savefilename;

}


public void setSavefilename(String savefilename) {

this.savefilename = savefilename;

}


public long getFilesize() {

return filesize;

}


public void setFilesize(long filesize) {

this.filesize = filesize;

}

}



[[  FileInfoDao.java  ]]

package test.file;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import test.dbcp.DbcpBean;

public class FileinfoDao {
    private DbcpBean dbcp;
    public FileinfoDao() {
        dbcp=new DbcpBean();
    }
    public int delete(int filenum){
        Connection con=null;
        PreparedStatement pstmt=null;
        try{
            con=dbcp.getCon();
            String sql="delete from fileinfo where filenum=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1,filenum);
            int n=pstmt.executeUpdate();
            return n;
        }catch(SQLException se){
            System.out.println(se.getMessage());
            return -1;
        }finally{
            try{
                if(pstmt!=null) pstmt.close();
                if(con!=null) con.close();
            }catch(SQLException se){}
        }
    }
   
    //파일번호에 해당하는 파일정보 반환하는 메소드
    public FileinfoVo getInfo(int filenum){
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        try{
            con=dbcp.getCon();
            String sql="select * from fileinfo where filenum=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1,filenum);
            rs=pstmt.executeQuery();
            if(rs.next()){
                FileinfoVo vo=new FileinfoVo(
                        rs.getInt("filenum"),
                        rs.getString("writer"),
                        rs.getString("title"),
                        rs.getString("content"),
                        rs.getString("orgfilename"),
                        rs.getString("savefilename"),
                        rs.getLong("filesize"));
                return vo;
            }
            return null;
        }catch(SQLException se){
            System.out.println(se.getMessage());
            return null;
        }finally{
            try{
                if(rs!=null) rs.close();
                if(pstmt!=null) pstmt.close();
                if(con!=null) con.close();
            }catch(SQLException se){}
        }
    }
    public ArrayList<FileinfoVo> getList(){
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        try{
            con=dbcp.getCon();
            String sql="select * from fileinfo order by filenum desc";
            pstmt=con.prepareStatement(sql);
            rs=pstmt.executeQuery();
            ArrayList<FileinfoVo> list=new ArrayList<>();
            while(rs.next()){
                FileinfoVo vo=new FileinfoVo(
                        rs.getInt("filenum"),
                        rs.getString("writer"),
                        rs.getString("title"),
                        rs.getString("content"),
                        rs.getString("orgfilename"),
                        rs.getString("savefilename"),
                        rs.getLong("filesize"));
                list.add(vo);
            }
            return list;
        }catch(SQLException se){
            System.out.println(se.getMessage());
            return null;
        }finally{
            try{
                if(rs!=null) rs.close();
                if(pstmt!=null)pstmt.close();
                if(con!=null) con.close();
            }catch(SQLException se){}
        }        
    }  
    
    public int insert(FileinfoVo vo){
        Connection con=null;
        PreparedStatement pstmt=null;
        String sql="insert into fileinfo " +
                   "values(fileinfo_seq.nextval,?,?,?,?,?,?)";
        try{
            con=dbcp.getCon();//dbcp에서 컨넥션 객체 얻어오기
            pstmt=con.prepareStatement(sql);
            //?에 대응되는 값 설정하기
            pstmt.setString(1,vo.getWriter());
            pstmt.setString(2,vo.getTitle());
            pstmt.setString(3,vo.getContent());
            pstmt.setString(4,vo.getOrgfilename());
            pstmt.setString(5,vo.getSavefilename());
            pstmt.setLong(6,vo.getFilesize());
            int n=pstmt.executeUpdate();
            return n;
        }catch(SQLException se){
            System.out.println(se.getMessage());
            return -1;
        }finally{
            try{
                if(pstmt!=null) pstmt.close();
                if(con!=null) con.close();
            }catch(SQLException se){}
        }
    }
}




EX> 파일여러개 upload


fileupload.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>

<%

request.setCharacterEncoding("euc-kr");


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

int icnt=0;

if(cnt!=null){

icnt=Integer.parseInt(cnt);

}

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

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

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

if(writer==null) writer="";

if(title==null) title="";

if(content==null) content="";

%>

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

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

<tr>

<td>작성자</td>

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

</tr>

<tr>

<td>제목</td>

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

</tr>

<tr>

<td>내용</td>

<td><textarea rows="5" cols="50" name="content"><%=content %></textarea></td>

</tr>

<tr>

<td>첨부파일갯수</td>

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

<input type="submit" value="확인"/>

</td>

</tr>

</table>

</form>

<form method="post" action="fileuploadOk.jsp" enctype="multipart/form-data">

<input type="hidden" name="writer"  value="<%=writer %>"/>

<input type="hidden" name="title"   value="<%=title %>"/>

<input type="hidden" name="content" value="<%=content %>"/>

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

<%

for(int i=0;i<icnt;i++){

%>

<tr>

<td>첨부파일<%=i+1 %></td>

<td><input type="file" name="file<%=i%>"></td>

</tr>

<%

}

%>

<tr>

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

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

</td>

</tr>

</table>

</form>

</body>

</html>








fileuploadOk.jsp

<%@page import="java.util.Enumeration"%>

<%@page import="com.oreilly.servlet.MultipartRequest"%>

<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>

<%@ 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 dir=application.getRealPath("/upload");

MultipartRequest mr = new MultipartRequest(

request,

dir,

1024*1024*5,

"euc-kr",

new DefaultFileRenamePolicy()

);

String writer = mr.getParameter("writer");

String title = mr.getParameter("title");

String content=mr.getParameter("content");

%>

작성자:<%=writer %><br/>

제목:<%=title %><br/>

내용:<%=content %><br/>

<%

//전송된 파일명을 얻어옴.

Enumeration<String> em=mr.getFileNames();

while(em.hasMoreElements()){

//전송된 file의 name속성(파라미터이름) 얻어오기

String fileName=em.nextElement();

//전송된 파일의 원본파일명 얻어오기;

String orgfilename=mr.getOriginalFileName(fileName);

//실제로 저장된 파일명 얻어오기

String savefileString=mr.getFilesystemName(fileName);

%>

전송된 파일명:<%=orgfilename %><br/>

저장된 파일명:<%=savefileString %><br/>

<%

}

%>

</body>

</html>








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




Insert title here


<%
	request.setCharacterEncoding("euc-kr");

	String cnt=request.getParameter("cnt");
	int icnt=0;
	if(cnt!=null){
		icnt=Integer.parseInt(cnt);
	}
	
	String writer=request.getParameter("writer");
	String title=request.getParameter("title");
	String content=request.getParameter("content");
	if(writer==null) writer="";
	if(title==null) title="";
	if(content==null) content="";
%>
작성자
제목
내용
첨부파일갯수
<% for(int i=0;i <% } %>
첨부파일<%=i+1 %>

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

17. Thumbnail 이미지  (0) 2013.04.23
16. <jsp:useBean> 태그  (0) 2013.04.23
14. DBCP  (0) 2013.04.20
13. JSP 간단한 예제 ( 목록, 입력, 수정, 삭제 )-model1  (0) 2013.04.19
12. JSP 스코프  (0) 2013.04.19



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>





+ Recent posts