Cohe
4. application, param, include, forward, action tag, error page 본문
728x90
반응형
OWASP Top Ten | OWASP Foundation
Application
- applicationn 객체는 sessio 과 사용방법이 거의 비슷하다. set, get을 쓴다. 서버가 동작할 때 1개의 application 객체가 생성되고 서버가 꺼질 때까지 유지됨
- 예매하기 사이트 제작
- 인증하기를 제작한다.
- 자바 uuid 중복되지 않는 16비트(진수) 값 생성 -> 전체 16바이트 길이로 생성
- splite은 특정 문자열을 기준으로 자르는 메서드
<%@page import="java.util.Arrays"%>
<%@page import="java.util.UUID"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
//자바 uuid 중복되지 않는 16비트(진수) 값 생성 -> 전체 16바이트 길이로 생성
UUID uuid = UUID.randomUUID();
//splite은 특정 문자열을 기준으로 자르는 메서드
String struuid = uuid.toString();
String[] arr = struuid.split("-");
System.out.println(Arrays.toString(arr));
session.setAttribute("auth", arr[1]);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>auth.jsp</title>
</head>
<body>
<h2>인증 페이지</h2>
<form action="auth_ok.jsp">
<h3>인증문자 : <del><%=arr[1] %></del></h3>
위 문자열을 입력하세요 : <input type="text" name="code" size="8">
<input type="submit" value="인증">
</form>
</body>
</html>
- auth_ok.jsp 작성
- 앞페이지에서 사용자가 입력한 값과 arr[1] 값을 비교합니다. arr[1]은 세션에 저장했습니다.
- 두 값이 일치한다면 reserve.jsp(예약페이지) 리다이렉트, 두 값이 일치하지 않는다면 auth.jsp로 리다이렉트
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
request.setCharacterEncoding("utf-8");
String code = request.getParameter("code");
String auth = (String)session.getAttribute("auth");
if(code.equals(auth)){
response.sendRedirect("reserve.jsp");
}
else{
response.sendRedirect("auth.jsp");
}
%>
- 예약페이지
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>콘서트 예약</title>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
width: 80%;
margin: 0 auto;
text-align: center;
}
h2, h3 {
color: #333;
}
table {
margin: 0 auto;
}
table td {
padding: 5px;
}
input[type="checkbox"] {
transform: scale(1.5);
margin: 5px;
}
input[type="submit"] {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
transition: background-color 0.3s ease;
}
input[type="submit"]:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<h2>콘서트 예약</h2>
<h3>예약할 좌석을 선택하세요</h3>
<hr>
<h3>좌석 배치도</h3>
<form action="reserve_ok.jsp">
<table>
<tbody>
<tr>
<%
out.print("<td> </td>");
for(char i=65; i<=90; i++) {
%>
<td><strong><%= i %></strong></td>
<% } %>
</tr>
<% for(int i=1; i<7; i++) { %>
<tr>
<td><strong><%= i %></strong></td>
<% for(int j=1; j<27; j++) { %>
<td><input type="checkbox" name="seat" value="<%= (char)(j+64) + "" + i %>"></td>
<% } %>
</tr>
<% } %>
</tbody>
</table>
<br>
<input type="submit" value="예약">
<input type="submit" value="취소">
</form>
</div>
</body>
</html>
- reserve_ok.jsp
- double cooking이 일어나는지 확인하기, 예약할 때 이전 사람이 예약하지 않았는지 확인할 필요가 있다.
- 해당 리스트는 application에 집어 넣을 것이다.
<%@page import="java.util.List"%> <%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <!DOCTYPE html> <html> <head> <meta charset="EUC-KR"> <title>콘서트 예약</title> <style> body { font-family: Arial, sans-serif; } .container { width: 80%; margin: 0 auto; text-align: center; } h2, h3 { color: #333; } table { margin: 0 auto; } table td { padding: 5px; } input[type="checkbox"] { transform: scale(1.5); margin: 5px; } input[type="submit"] { padding: 10px 20px; background-color: #007bff; color: #fff; border: none; cursor: pointer; transition: background-color 0.3s ease; } input[type="submit"]:hover { background-color: #0056b3; } </style> </head> <body> <% // 예약 현황이 있다면 예약 좌석을 꺼내서 처리... List<String> list = new ArrayList<>(); if(application.getAttribute("seats")!=null){ list= (List<String>)application.getAttribute("seats"); } %> <div class="container"> <h2>콘서트 예약</h2> <h3>예약할 좌석을 선택하세요</h3> <hr> <h3>좌석 배치도</h3> <form action="reserve_ok.jsp"> <table> <tbody> <tr> <% out.print("<td> </td>"); for(char i=65; i<=90; i++) { %> <td><strong><%= i %></strong></td> <% } %> </tr> <% for(int i=1; i<7; i++) { %> <tr> <td><strong><%= i %></strong></td> <% for(int j=1; j<27; j++) { if(list.contains((char)(j+64)+"-"+i)){%> <td><input type="checkbox" name="seat" value="<%= (char)(j+64) + "-" + i %>" disabled></td> <% } else{%> <td><input type="checkbox" name="seat" value="<%= (char)(j+64) + "-" + i %>"></td> <% } %> <% } %> </tr> <% } %> </tbody> </table> <br> <input type="submit" value="예약"> <input type="submit" value="취소"> </form> </div> </body> </html>
- 생명주기
- request : 객체는 요청마다 생성, 요청하는 그 주소까지만이 가질 수 있는 전까지가 생명주기
- 다른 쪽에 있는 것들을 가져와서 처리하는데, url 주소가 바뀌는 상황에서는 전달이 안되니까 포어드?? 를 작성한다.
- session은 브라우저별로 생성
- application 프로그램 전체에서 딱 한 번 최초 가동시 생성됨
- request : 객체는 요청마다 생성, 요청하는 그 주소까지만이 가질 수 있는 전까지가 생명주기
- error
- 100번 때 : 그냥 실행 중 에러
- 400번 때 : 클라이언트 측 에러
- 500번 때 : 서버 측 에러
- 500 : 내부 서버 에러
- try-catch 문
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>error_trycatch.jsp</title>
</head>
<body>
<%
try{
String num = request.getParameter("num");
Integer.parseInt(num);
}catch(Exception e){
out.print("num 값이 없습니다.");
}
%>
</body>
</html>
- url을 JSP_Basic/errorPage/error_trycatch.jsp?num=10 이렇게 써주면 된다!!
- error 페이지를 따로 만들기!
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page isELIgnored="true" %> <%--에러 발생 시 보여질 페이지 선언 --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<style type="text/css">
.box{
height: 1000px;
text-align: center;
}
</style>
</head>
<body>
<div class="box">
예기치 못한 에러가 발생했습니다. <br>
<a href="#">홈으로</a>
</div>
</body>
</html>
- web.xml에 설정하기
- 개발 다 하고 배포하기 전에 이런 에러 페이지를 삽입해준다!!
<error-page>
<error-code>404</error-code>
<location>/errorpage/error_view.jsp</location>
</error-pa
ge>
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/errorpage/error_view.jsp</location>
</error-page>
Action Tag
- 액션 태그 : jsp 안에서 특정 동작 지시 태그들 액션태그는 여는 태그가 있는 닫는 태그가 존재 추가적으로 종속된 태그가 없다면 "/>"로 닫기 처리
- forward
- 요청받은 요청객체를 위임하는 컴포넌트에 요청 객체 값을 동일하게 전달할 수 있다.
- 요청을 처리함과 동시에 해당 결과를 바로 보여줘야 하는 경우
- url 주소는 변화하지 않는다.
- request에 1회성으로 사용하기 위해 값을 강제로 저장 가능!
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<jsp:forward page="forward_ex03.jsp" />
- sendRedirect와 비교
- 요청 받은 요청 객체를 위임하는 컴포넌트에 전달하는 것이 아닌 새로운 요청 객체를 생성
- url 주소가 변화한다. 그러므로 전달이 안된다!
- com.servlet.Forward에서 작업
package com.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Forward")
public class Forward extends HttpServlet {
private static final long serialVersionUID = 1L;
public Forward() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
System.out.println(id);
//request에 1회성으로 사용하기 위해 값을 강제로 저장
request.setAttribute("name","hyeonyeong");
//-> 하지만 sendRedirect 하게 되면 새 객체로 저장되기 때문에 아무것도 전달되지 않는다.
// response.sendRedirect("actionTag/forward_ex04.jsp");
RequestDispatcher dp = request.getRequestDispatcher("actionTag/forward_ex04.jsp");
dp.forward(request, response);
}
}
- include
<%@ 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>
<h2>여기는 1번 페이지 입니다.</h2>
<hr>
<%@ include file="include_ex02.jsp" %>
<hr>
<jsp:include page="include_ex02.jsp"/>
</body>
</html>
- param
- forward 시 에 파라미터 값을 추가해서 넘기고자 할 경우
Quiz
- 앞에서 넘어온 폼값을 받아서 평균을 구합니다.
- 평균이 60점 이상이면 score_quiz03.jsp로 이동 "~~님 평균 xx점 합격" 을 출력
- 평균이 60점 미만이면 score_quiz04.jsp로 이동 "~~님 평균 xx점 불합격" 을 출력
728x90
반응형
'개발 언어 > JSP' 카테고리의 다른 글
JSP mini project : mypage 실습 (0) | 2024.04.15 |
---|---|
6-1 JSP-JDBC 연동2 (0) | 2024.04.12 |
6. JSP-JDBC 연동 (0) | 2024.04.11 |
5. javaBean (0) | 2024.04.11 |
3. Cookie, Session (0) | 2024.04.08 |