1)내장객체 정리
2)나머지 내장객체
2-1) application
2-2) out
2-3) exception
1) 에러를 파일에서처리
2) web.xml에서처리
3)error페이지 우선순위
3) cookie
4)JDBC
4-1) 업로드관련
1) 내장객체 정리
========내장 객체==========
1. request 요청객체
setCharacterEncoding(인코딩방식)
파라미터이름 : 전송페이지<input name="파라미터명"..>
<select name="파라미터명">
String getParameter ('파라미터명') : 파라미터의 값 한개
String[] getParameterValues("파라미터이름") : 파라미터의 모든 값
Enumeration getParameterNames() : 모든파라미터의 이름 Enumeration객체 리턴
2.response : 응답객체
sendRedirect("프로젝트내부의 페이지URL") : 다른페이지를 요청함(같은request영역X)
3.pageContext : 현재페이지의 자원관리
forward("프로젝트내부 페이지URL") : 서버내에서 다른페이지 요청(같은 request영역)
include("프로젝트내부 페이지URL") : 서버내에서 다른페이지 포함
4.session : 브라우저별로 연결관리하는 객체. 클라이언트의 상태정보 저장가능
session.setMaxInactiveInterval(초단위) : 세션유지시간(default : 60*30초{30분})
setAttribute("속성명",객체) : 속성등록
Object getAttribute("속성명") : 속성조회(객체타입에 맞게 형변환필요함)
removeAttribute("속성명") : 속성삭제
invalidate() : session 객체 종료 새로운session객체로 치환
2)나머지 내장객체
2-1)application
application영역 : 하나의 프로젝트내의 모든jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>application 객체</title>
</head>
<body>
<h3>applcation객체는 웹 어플리케이션 당 한개의 객체 제공 <br>
현재 웹어플리케이션 jspStudy 프로젝트의 모든 jsp는 하나의 application객체 공유
</h3>
<table border="1" style="border-collapse : collapse;">
<tr><td>jsp버전</td>
<td><%=application.getMajorVersion() %>
.<%= application.getMinorVersion() %></td>
</tr>
<tr><td>웹컨테이너 정보(WAS 서버정보)</td>
<td><%=application.getServerInfo() %></td>
</tr>
<tr><td>웹어플리케이션 경로</td>
<td><%= application.getRealPath("/") %></td>
</tr>
</table>
<h3>applacation객체는 application 영역을 담당하는 객체</h3>
<% application.setAttribute("test","application객체 TEST"); %>
</body>
</html>
다음과같이 정보들이 나온다 ( 웹어플리케이션경로를 들어가보면)
또한
application.setAttribute("test","application객체 TEST"); 로 application 속성을 생성 후
그냥 아무파일이나 만들어서 getAttribute("test")으로 속성 조회 가능
2-2) out
<% 와 <%= 을 왔다갔다 하면서 출력하는것은 불편하다out객체는 그런점을 해결해줌
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>out 내장객체</title>
</head>
<body>
<h3>out 객체는 response 객체의 출력버퍼에 데이터를 출력할수있는 출력스트림 객체</h3>
<%
int sum=0;
for(int i=1;i<=10;i++){
sum+= i ;
%>
1부터 <%=i %>까지의 부분합 : <%=sum %><br>
<%} %>
1부터10까지의 합 : <%=sum %>
<hr>
<h3>out객체 활용</h3>
<%
sum=0;
for(int i=1;i<=10;i++){
sum+= i ;
out.println("1부터"+i+"까지의 부분합 : "+sum+"<br>");
}
out.println("1부터10까지의합 " +sum);
%>
</body>
</html>
2-3) exception
1) 에러를 파일에서 처리
<%@page errorPage="errorPage.jsp" %> :
오류가발생하면 errorPage.jsp로 이동해라!
ex01_error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%--errorPage = "errorPage.jsp : 현재페이지오류발생시 errorPage.jsp 호출 --%>
<%@page errorPage="errorPage.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% int num = Integer.parseInt("abc"); %>
</body>
</html>
numberFormatException 발생할것임
errorPage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %> <!--현재페이지는 오류페이지임을 명시.exception객체추가 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ERROR page</title>
</head>
<body>
<h1>error 발생</h1>
<h2>입력값을 다시확인해주세요</h2>
<h3>숫자만입력가능</h3>
<%= exception.getMessage() %><br> <%--에러메시지 --%>
<% //오류메시지를 브라우저에 띄워라
//exception.printStackTrace(response.getWriter()); %>
</body>
</html>
<%@page errorPage="errorPage.jsp" %> 를 사용안할 시
IT를 모르는사람들은 이 오류를 알수없음
<%@page errorPage="errorPage.jsp" %> 를 사용 시
2) 에러 or 오류 처리방법 2
web.xml을 건드려보자 (같은 프로젝트라면 404,500 에러들은 이 방식대로 처리될것임)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>jspStudy</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>
<error-page>
<!-- 404(페이지에 오류발생) 오류발생시 호출되는 jsp페이지설정 -->
<error-code>404</error-code> <!-- 404에러발생시 -->
<location>/ex09_exception/error404.jsp</location> <!-- 해당경로의파일을 실행 -->
</error-page>
<error-page>
<!-- NumberFormatException 에러발생시 호출되는 jsp페이지설정 -->
<exception-type>java.lang.NumberFormatException</exception-type> <!-- 예외발생시 -->
<location>/ex09_exception/errorNumberFormat.jsp</location>
</error-page>
<error-page>
<!-- 500(페이지에 오류발생) 오류발생시 호출되는 jsp페이지설정 -->
<error-code>500</error-code> <!-- 500에러발생시 -->
<location>/ex09_exception/error500.jsp</location>
</error-page>
</web-app>
해당코드 실행 시
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>오류발생 페이지</title>
</head>
<body>
<% String str = null; %>;
<%= str.trim() %> <!-- 500번에러발생 -->
<!-- NumnerformatException -->
<%
int num = Integer.parseInt("abc");
%>
</body>
</html>
3) error 페이지 설정시 우선순위
1.해당페이지에서 오류페이지설정 : <%@page errorPage="errorPage.jsp" %>
2.web.xml에서 예외클래스별로 설정
<error-page><exception-type>..
3.web.xml에서 HTTP오류코드로 설정 시
<error-page><error-code>..
4.WAS에서 제공해주는 에러페이지
3) Cookie
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Cookie cookie = new Cookie("name","hongkildong");
//new Cookie(name,value)
cookie.setMaxAge(600);//유효기간설정
response.addCookie(cookie);
%>
<h2>
쿠키이름 : <%=cookie.getName() %><br>
쿠키값 : <%=cookie.getValue() %><br>
쿠키유효기간 : <%=cookie.getMaxAge() %><br>
</h2>
<a href="ex02_cookie.jsp"> 쿠키값 불러오기</a>
<a href="ex03_cookieRemove.jsp">쿠키삭제</a>
</body>
</html>
4)JDBC
2025.03.12 - [부트캠프(DB)] - 부트캠프28일차 (JDBC)
부트캠프28일차 (JDBC)
1)JDBC 1-1) jar파일 이클립스에연동1-2) jdbc연결1-3) JDBC사용해보기1-4) JDBC 사용 객체와 작동방식1-4)JDBC사용 예제1-5) PreparedStatement1-6)DB연결부분 develop1-7)MetaData1-8)execute1-9) 예제2) 내가만든 총 예제
ddkk1120.tistory.com
자세한연동법은 위에글을 참고해보자
jsp에 db연동
WEB-INF 하위에 lib폴더에 jar파일(driver)붙여넣자
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.ResultSetMetaData"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/jspStudy/css/main.css"> <!-- 해당경로의 css파일을 사용 -->
<%-- http://localhost:8080/jspStudy/
이클립스폴더 : /jspStudy/src/main/wepapp 폴더를 시작
--%>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Class.forName("org.mariadb.jdbc.Driver");//JDBC Drive 클래스 로드
Connection conn = DriverManager.getConnection
("jdbc:mariadb://localhost:3306/gdjdb","gduser","1234"); //db와연결
//gdjdb : DB명 , gduser:유저명 , 1234 : 비번)
PreparedStatement pstmt = conn.prepareStatement("select * from professor");
//prepareStatement : SQL명령문을 DB에 전달하기위한 객체(Statement의 하위)
//executeQuery() : sql문 실행해 ResultSet으로 리턴
//ResultSet : select구문의 결과를 저장하는 객체
ResultSet rs = pstmt.executeQuery();
//ResultSetMetaData : 결과데이터의 정보 저장
ResultSetMetaData rsmt = rs.getMetaData();
%>
<table><tr>
<% for(int i=1;i<=rsmt.getColumnCount();i++){%>
<th><%=rsmt.getColumnName(i)%></th><%}%></tr> <!-- 모든 컬럼명 -->
<% while(rs.next()) {%><tr>
<% for(int i=1;i<=rsmt.getColumnCount();i++){ %> <!-- rs.getString("컬럼명") : 컬럼의값 읽어오기 -->
<td><%=rs.getString(i)%></td><%}%></tr><!-- for문종료 -->
<%} %><!-- while문 종료 -->
</table>
</body>
</html>
4-1) 업로드관련
해당 폴더의 압축 푼 후 lib>cos.jar 파일을 찾아서
다음과같이 붙여넣는다 (테스트용임 좋지않은 Driver임)
JSP코드
enctype="multipart/form-data" : 파일의 이름뿐만아니라 데이터까지 추가로넘긴단 의미
method = "post" --> get방식처럼 파일의 데이터를 URL에 띄울순없다
파일업로드 시
<form method="post" enctype="multipart/form-data" ....>필수
서버에서는 request를 이용해 파라미터값을 가져올수없다
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일업로드</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <!-- jQeury -->
</head>
<body>
<div>
<form id="frm_upload" action="ex01_upload.jsp"
method="post" enctype="multipart/form-data">
<!-- enctype="multipart/form-data" : 파일의 이름뿐만아니라 데이터까지 추가로넘긴단 의미
=> 서버에서는 request를 이용해 파라미터값을 가져올 수 없다
=>ex01_upload.jsp 에게 요청시
1개의 파라미터(uploader)와
1개의 파일정보+파일내용(filename)
-->
<div>
<label for="uploader">작성자</label>
<input type="text" id="uploader" name="uploader">
</div>
<div>
<label for="filename">파일첨부</label>
<input type="file" id="filename" name="filename">
<!-- 파일의이름만넘어간다고 다른곳에서열리지않음 (파일자체가 넘어가야함)-->
</div>
<div>
<button>첨부하기</button> <!-- button태그는 submit과 같다 -->
<input type="reset" value="다시작성">
</div>
</form></div>
<script type="text/javascript">
$("#filename").on("change",function(){
let filename = $(this).val();
let extname = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();//확장자만 가져옴
let acceptList = ["jpg","jpeg","png","gif","tif"];
if($.inArray(extname,acceptList)== -1){
alert("이미지만 첨부");
$(this).val("");
return;
}
})
</script>
</body></html>
업로드파일을 관리하는 jsp(ex01_upload.jsp)
<%@page import="java.text.DecimalFormat"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//request.getServletContext() : application객체
//realPath : ..../org.eclipse.wst.server.core/tmp0/wtpwebapps\/jspStudy/upload/
String realPath = application.getRealPath("upload");//업로드되는폴더설정
File dir = new File(realPath);
if(!dir.exists()){
dir.mkdirs(); //존재x 시 폴더생성
}
//MultipartRequest : 파일 업로드를 처리하는 역할
MultipartRequest multi = new MultipartRequest(
request, //요청정보,파라미터정보,파일정보(처리를할수없을 뿐 내용은 존재)
realPath,//업로드되는 폴더설정 => 폴더에파일저장 => 업로드
1024*1024*10,//10M => 업로드되는 파일의 최대크기
"UTF-8",//인코딩방식
new DefaultFileRenamePolicy()); // 파일명 중복시 이름 변경(뒤에숫자를붙여줌)
String uploader = multi.getParameter("uploader"); //파라미터정보조회(name=uploader)
String originName = multi.getOriginalFileName("filename");//선택된파일명(name=filename)
String fileSystemName = multi.getFilesystemName("filename");//저장할떄의 파일명
File file = multi.getFile("filename"); //업로드된파일의 정보를 File객체로반환
String name = file.getName();//파일의이름
String parents = file.getParent();//파일이속해있는 폴더명
String lastModified = new SimpleDateFormat("yyyy-MM-dd").format(file.lastModified());
//#,##0 : 숫자출력시 3자리마다 , 를표시
//file.length() : 파일의 바이트크기
//file.length()/ 1024 => KB로 화산
String size = new DecimalFormat("#,##0").format(file.length() / 1024 +
(file.length() % 1024 == 0? 0:1));
%>
<ul style="list-style-type:circle; font-size:24px"></ul>
<li>작성자 : <%= uploader %></li>
<li>원래업로드파일명 : <%= originName %></li>
<li>저장된 업로드파일명 : <%=fileSystemName %></li>
<li>파일의 폴더경로 : <%= parents %></li>
<li>파일명 : <%= name %></li>
<li>최종수정일 : <%= lastModified %></li>
<li>파일크기 : <%= size %>KB</li>
<img src="/jspStudy/upload/<%= fileSystemName%>">
</body>
</html>
MultipartRequest : 파일 업로드를 처리하는 역할
(업로드에서 가장 중요)
(request는 내용은존재함 MultipartRequest에서 처리해줄수있음)
new MultipartRequest (request,
realPath,
1024*1024*10,
"UTF-8",
new DefaultFileRenamePolicy());
'JSP' 카테고리의 다른 글
부트캠프46일차 (delete , 사진등록 , id,pw찾기) (0) | 2025.04.08 |
---|---|
부트캠프45일차(로그인 , main , sitemesh , 회원목록 , updateForm) (0) | 2025.04.07 |
부트캠프44일차(model1 ) (0) | 2025.04.04 |
부트캠프42일차 (JSP내장객체 request, response,pageContext,session) (1) | 2025.04.02 |
부트캠프41일차(servelt , JSP) (0) | 2025.04.01 |